File size: 12,273 Bytes
5bde15f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
"""Reference-style logs derived from independent UE input, without invented state."""
from bisect import bisect_left,bisect_right
import json
import math

ACTION={'j':'Attack','k':'HeavyAttack','space':'Dodge','c':'Guard','f':'Riposte',
        't':'Heal','tab':'Lock','r':'Reset','shift':'Run','m':'Map'}
PHASE={'battle_round_start':'combat','battle_result':'result_pending',
       'precombat_roam_start':'roam','boss_approach_start':'approach',
       'natural_combat_entry':'combat',
       'full_map_exploration_start':'roam','full_map_result':'episode_complete',
       'return_to_arena_start':'return_to_arena','return_to_arena_complete':'reset_pending',
       'episode_boundary':'reset','encounter_round_complete':'episode_complete',
       'encounter_recording_complete':'episode_complete'}
MODE={'active':'combat','explore':'roam','result_hold':'result_pending',
      'roam_before_combat':'roam','approach_boss':'approach',
      'reset_key':'reset','settle':'reset_pending'}
STAGES={'startup':(0,'启动'),'episode_start':(0,'回合准备'),'roam':(1,'漫游'),
        'approach':(2,'接近Boss'),'combat':(3,'Boss战'),'result_pending':(4,'结果确认'),
        'return_to_arena':(5,'返回'),'episode_complete':(6,'流程完成'),
        'reset_pending':(7,'回合间等待'),'reset':(8,'回合重置')}


def timecode(frame,fps):
    seconds,sub=divmod(frame,fps)
    return f'{seconds//3600:02d}:{seconds//60%60:02d}:{seconds%60:02d}:{sub:02d}'


def export_reference_logs(output,summary,frames,engine,events,source_video=None):
    if not frames:return dict(exported=False,reason='No video frames')
    fps=int(summary.get('fps',summary.get('output_fps',16)))
    if fps<=0 or fps!=summary.get('fps',summary.get('output_fps',16)):
        raise ValueError('Reference timecode requires the actual positive integer video FPS')
    ids=[int(f['engine_frame']) for f in frames]
    if any(b<=a for a,b in zip(ids,ids[1:])):raise ValueError('Nonmonotonic video engine frames')
    if any(int(b['engine_frame'])<int(a['engine_frame']) for a,b in zip(engine,engine[1:])):
        raise ValueError('Nonmonotonic UE events')
    if any(e['type'] not in ('key_down','key_up') for e in engine):raise ValueError('Unknown UE input event')
    names=['输入日志.jsonl','输入日志.json','输入日志.vrising.json','事件日志.jsonl','session.json']
    if any((output/name).exists() for name in names):raise FileExistsError('Do not overwrite reference export evidence')
    output.mkdir(parents=True,exist_ok=True)
    native_path=output/'engine_session.jsonl'
    native=[json.loads(line) for line in native_path.read_text(encoding='utf-8').splitlines() if line.strip()] if native_path.exists() else []
    spawns=[e for e in native if e['type']=='spawn_applied']
    spawn_frames=[int(e['engine_frame']) for e in spawns]
    def aligned(event):
        i=bisect_left(ids,int(event['engine_frame']))
        valid=i<len(frames) and int(event['engine_frame'])>=ids[0]
        return dict(vt=float(frames[i]['video_t']) if valid else None,
                    视频时间=timecode(i,fps) if valid else None,outside_video=not valid)
    def key(event):
        k=event['key'].lower()
        return {'spacebar':'space','leftshift':'shift','two':'2'}.get(k,k)
    changes=[e for e in events if 'engine_frame' in e and (e['type'] in PHASE or e['type']=='bot_mode')]
    changes.sort(key=lambda e:e['engine_frame'])
    has_precombat=any(e['type'] in ('precombat_roam_start','natural_combat_entry') for e in events)
    def phase_for(e):
        if e['type']=='battle_round_start' and has_precombat:return 'episode_start'
        return MODE.get(e.get('mode'),e.get('mode',PHASE.get(e['type'],'unknown')))
    markers=[(int(e['engine_frame']),1,i,phase_for(e))
             for i,e in enumerate(changes)]
    markers += [(int(e['engine_frame']),0,i,'reset') for i,e in enumerate(engine)
                if e['type']=='key_down' and key(e)=='r']
    markers.sort()
    cursor=phase_cursor=episode=0;phase='startup';held=set()
    with (output/'输入日志.jsonl').open('w',encoding='utf-8') as stream:
        for i,frame in enumerate(frames):
            engine_frame=int(frame['engine_frame'])
            while phase_cursor<len(markers) and markers[phase_cursor][0]<=engine_frame:
                phase=markers[phase_cursor][3];phase_cursor+=1
            pressed=[];released=[];edges=[];discontinuity=False
            while cursor<len(engine) and engine[cursor]['engine_frame']<=engine_frame:
                event=engine[cursor];k=key(event);down=event['type']=='key_down'
                if down:held.add(k)
                else:held.discard(k)
                if down and k=='r':episode+=1
                cursor+=1
                # Earlier events establish the first held state, but are not
                # presses or resets that occurred in the first video frame.
                if event['engine_frame']<ids[0]:continue
                if k in ACTION:(pressed if down else released).append(ACTION[k])
                if down and k=='r':discontinuity=True
                edges.append(dict(key=k,state='down' if down else 'up',
                    engine_frame=event['engine_frame'],game_time=event['game_time'],
                    engine_real_time=event['engine_real_time']))
            x=int('d' in held)-int('a' in held);y=int('w' in held)-int('s' in held)
            mag=math.hypot(x,y)
            row=dict(type='input',vt=float(frame['video_t']),视频时间=timecode(i,fps),
                frame=i,t=float(frame['game_t']),f=engine_frame,w=None,
                engine_real_time=float(frame['engine_real_time']),
                wall_relative=float(frame['engine_real_time'])-float(frames[0]['engine_real_time']),
                episode=episode,phase=phase,discontinuity=discontinuity,
                down=sorted(ACTION[k] for k in held if k in ACTION),pressed=pressed,released=released,
                keys=sorted(held),mv=dict(keys='+'.join(sorted(k.upper() for k in held if k in 'wasd')),
                    x=x/mag if mag else 0,y=y/mag if mag else 0,mag=min(1.,mag),
                    deg=math.degrees(math.atan2(x,y))%360 if mag else None,
                    source='camera_relative_keyboard_input_not_measured_velocity'),
                aim=None,edges=edges,input_source='independent_UE_received_keys')
            if spawns:
                spawn_i=bisect_right(spawn_frames,engine_frame)-1
                row['spawn_index']=spawns[spawn_i]['spawn_index'] if spawn_i>=0 else None
                row['round']=spawns[spawn_i]['round'] if spawn_i>=0 else 0
            stream.write(json.dumps(row,ensure_ascii=False)+'\n')
    marker_frames=[m[0] for m in markers]
    def input_stage(e):
        index=bisect_right(marker_frames,int(e['engine_frame']))-1
        phase=markers[index][3] if index>=0 else 'startup'
        if e['type']=='key_down' and key(e)=='r':phase='reset'
        number,name=STAGES.get(phase,(None,phase))
        return dict(阶段=number,阶段名=name,phase=phase)
    human=[dict(时间戳=None,按键=key(e).upper(),状态='按下' if e['type']=='key_down' else '松开',
                来源='UE实际接收输入',engine_frame=e['engine_frame'],game_time=e['game_time'],engine_real_time=e['engine_real_time'],
                **input_stage(e),**aligned(e)) for e in engine]
    # EYBXBOSS uses JSON Lines; the inspected vrising4stage input file is an
    # actual JSON array. Export both explicitly rather than conflate the formats.
    with (output/'输入日志.json').open('w',encoding='utf-8') as stream:
        for row in human:stream.write(json.dumps(row,ensure_ascii=False)+'\n')
    (output/'输入日志.vrising.json').write_text(json.dumps(human,ensure_ascii=False,indent=2),encoding='utf-8')
    timeline=[dict(type='event',ev=e['type'],round=e.get('round'),f=e['engine_frame'],
              phase=phase_for(e),**aligned(e)) for e in changes]
    timeline += [dict(type='event',ev='reset_boundary',discontinuity=True,f=e['engine_frame'],
                  source='UE_R_key_down',**aligned(e)) for e in engine if e['type']=='key_down' and key(e)=='r']
    timeline += [dict(type='event',ev='spawn_applied',round=e['round'],spawn_index=e['spawn_index'],
                     position_cm=[e['x'],e['y'],e['z']],discontinuity=True,f=e['engine_frame'],
                     source='UE_after_native_reset',**aligned(e)) for e in spawns]
    if native:
        with (output/'玩家状态.jsonl').open('x',encoding='utf-8') as stream:
            for e in native:
                if e['type']!='player_state':continue
                row=dict(type='s',e='player',round=e['round'],f=e['engine_frame'],
                         t=e['game_time']-float(frames[0]['game_time']),
                         engine_real_time=e['engine_real_time'],units='cm and cm/s',
                         **{k:e[k] for k in ('x','y','z','vx','vy','vz')},**aligned(e))
                row.update({k:e[k] for k in ('health','stamina','action','boss_known','boss_x','boss_y','boss_z','boss_health','boss_action','camera_yaw') if k in e})
                stream.write(json.dumps(row,ensure_ascii=False)+'\n')
        names.append('玩家状态.jsonl')
    with (output/'事件日志.jsonl').open('w',encoding='utf-8') as stream:
        for event in sorted(timeline,key=lambda e:e['f']):
            stream.write(json.dumps(event,ensure_ascii=False)+'\n')
    session=dict(schema='gamebot.reference.v3',video_file=str(source_video) if source_video is not None else 'gameplay.mp4',fps=fps,
        frame_count=len(frames),sessionId=summary.get('run_id',output.name),case_id=summary.get('case_id'),
        clock='vt is MP4 playback seconds; t is relative UE game time; wall_relative is real elapsed time',
        w=None,w_note='UTC for independent UE events was not recorded; do not infer a Unix timestamp',
        source='Existing UE events and actual video frames, not model intentions',
        state_fields_not_recorded=([] if native else ['world_position','actual_velocity'])+['aim','entity_id','boss_action'],
        action_note='Action names map received keys to commands; they do not establish successful game actions',
        reference_datasets=['yuzhewu207/EYBXBOSS','yuzhewu207/vrising4stage'],
        reference_revisions={'yuzhewu207/EYBXBOSS':'371c8a04249901f58d5d794dc19f42c3787b3f92',
                             'yuzhewu207/vrising4stage':'89051f72fb2ea1688c4fcb3e197d63c783406f69'},
        file_formats={'输入日志.json':'JSON Lines; one independent UE edge per line, not a JSON array',
                      '输入日志.vrising.json':'JSON array; the same UE edges and order, for vrising-style consumers',
                      '输入日志.jsonl':'JSON Lines; one row per actual video frame',
                      '事件日志.jsonl':'JSON Lines; controller phase and actual reset boundaries'},
        timecode_format='HH:MM:SS:frame (uses this video fps, not the reference game fps)',
        action_mapping=ACTION,
        stage_mapping={key:dict(code=value[0],name=value[1]) for key,value in STAGES.items()},
        stage_note='Codes describe this Bot workflow; they are not the reference game level IDs',
        compatibility='Video/input/phase conventions only; not a complete engine-state schema clone')
    if native:
        session.update(native_player_state='玩家状态.jsonl: measured UE position and velocity in cm / cm per second',
                       spawn_cycle=summary.get('spawn_cycle'),recording_mode=summary.get('recording_mode'),
                       duration_policy='Exact distinct-frame budget; final unfinished round is preserved',
                       spawn_change='Explicit native R reset followed by authorized player spawn change; no combat-rule changes')
        if any('boss_action' in e for e in native):
            session['state_fields_not_recorded']=['aim','entity_id']
            session['native_action_note']='action/boss_action are the original UE reflected action states, not inferred from pressed keys'
    (output/'session.json').write_text(json.dumps(session,ensure_ascii=False,indent=2),encoding='utf-8')
    return dict(exported=True,frames=len(frames),ue_edges=len(engine),episodes=episode,
                files=names)