Repository navigation
Expand file tree
/
Copy pathmachine.zig
More file actions
2757 lines (2578 loc) · 129 KB
/
Copy pathmachine.zig
File metadata and controls
2757 lines (2578 loc) · 129 KB
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The script VM at run time: the VM's globals, its threads, the interpreter, the clock and the
//! timers, `for_each_ship`, and the commands that live beside them (the timers', `Wait`,
//! `InterruptTriggerCode`, `KillAllScriptExecutionExecptMe`, `OpenInstrument` and
//! `CloseInstrument`). [docs/engine/script-vm.md](../../../docs/engine/script-vm.md) describes the
//! VM.
//!
//! Where the game holds an address on a thread's stack, OpenReliant holds where the place lies in
//! the mission image, which holds the script, its strings and every record a script names: a
//! ship's, a flight group's, a global's. The instruction pointer and a block's end are such places
//! too, and a thread's frame is its place on the thread's own stack. The bound mission finds a
//! record by its place and reads the image (`bind.Mission.shipIndex`, `bind.Mission.byte` and the
//! rest). Where the game would fault, or read past a table, OpenReliant ends the thread and logs
//! why.
//!
//! While the editor link has an editor there, `vm_run` stops a thread at the bytes the editor
//! flagged and steps it as the editor asks (`vm.editor`, docs/engine/editor-link.md).
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const log = std.log.scoped(.vm);
const dte = @import("../../formats/dte.zig");
const Random = @import("../random.zig").Random;
const math = @import("../surrender/math.zig");
const vm = @import("../vm.zig");
const executor = @import("../game/executor.zig");
const hooks = @import("../hooks.zig");
const mission = @import("../game/mission.zig");
const bind = mission.bind;
const SquadPath = bind.Mission.SquadPath;
const aigeneric = @import("../game/aigeneric.zig");
const create = @import("../game/create.zig");
const gameobj = @import("../game/gameobj.zig");
const hud = @import("../game/hud.zig");
/// The bit of a script byte's flag that the editor sets to stop the script before the byte
/// (`vm_run`, `0x0045C9AD`).
pub const stop_flag: u8 = 1 << 0;
/// The value `push_null` pushes: no object (`0x0045C4B5`), which the mission's lookups take for
/// none (`bind.Mission.named`).
pub const none: u32 = bind.Mission.null_place;
/// A command as OpenReliant runs it. Its result is stored in the thread's result, and a zero result
/// ends the thread's run, which a waiting command gives: most give `run_on` or `yield`.
pub const Implementation = *const fn (call: Call) u32;
/// The work of a command that does nothing outside a game and always lets its thread run on
/// (`run_on`): the command's call, and the game.
pub const GameImplementation = *const fn (call: Call, game: aigeneric.Context) void;
/// The result of a command that lets its thread run on, as the game's commands end (`MOV EAX,0x1`,
/// such as `0x00458119` in `cmd_WaitForSpeech`).
pub const run_on: u32 = 1;
/// A command's result, as the hook on `vm_command` gives it to scripts: `wait` (0) ends the thread's
/// run until it runs next, `run_on` (1) lets it run on, and any other number is the command's own
/// result, which the script reads as the command's value and which lets the thread run on too.
/// Only a hook's handler gives `hold` (`Machine.command`).
pub const CommandResult = enum(u32) {
wait = yield,
run_on = run_on,
/// The command doesn't run yet: the thread waits, and runs it again on the same arguments the
/// next time it runs, the way a waiting command runs itself again (`Call.againItself`). None of
/// the game's commands give this value.
///
/// **Improvement:** the original has no scripting apart from its mission scripts.
hold = std.math.maxInt(u32),
_,
/// What a command gives where a handler stops it: the thread runs on.
pub const stopped: CommandResult = .run_on;
pub const script_name = "MissionCommandResult";
};
/// The result of a command that ends its thread's run until the thread runs next, as a command
/// that waits ends (`XOR EAX,EAX`, such as `0x00458115` in `cmd_WaitForSpeech`).
pub const yield: u32 = 0;
/// The size of the `command` instruction: its opcode and its operand, the command's number.
pub const command_size: u32 = size: {
const info = dte.Opcode.command.info() orelse @compileError("the VM has no command opcode");
break :size 1 + info.operands;
};
comptime {
// The game's commands that wait step back over themselves by 2 (`againItself`).
assert(command_size == 2);
}
/// What a command runs with.
pub const Call = struct {
machine: *Machine,
/// The thread that runs it, by its place in the pool (`vm_thread`, `0x00537578`).
thread: u8,
/// Its arguments on the thread's stack, the first first.
args: []u32,
/// Has the thread run the command again when it runs next, and yields, as a command that waits
/// does: its instruction pointer goes back `back` bytes, to the command itself, or to the
/// pushes of its arguments before it too, which then push them afresh (`*ip -= back`).
pub fn again(call: Call, back: u32) u32 {
const thread = &call.machine.threads[call.thread];
if (thread.ip) |at| thread.ip = at -% back;
return yield;
}
/// `again`, back over the command instruction alone (`command_size`), as `WaitForSpeech`,
/// `WaitForMovie` and `WaitForDirectorCam` run again (`ADD EAX,-0x2` at `0x00458110`,
/// `0x0045818B` and `0x00459C9C`).
pub fn againItself(call: Call) u32 {
return call.again(command_size);
}
/// The slot of the object of the ship its argument `index` names, where it is one of `all`'s;
/// null where it names none (`ship_object`, `mission.shipSlot`).
pub fn argumentShip(call: Call, all: *const create.Objects, index: usize) ?u16 {
return mission.shipSlot(call.machine.mission, all, call.args[index]);
}
};
/// What ends a thread where the game faults or reads past a table.
pub const Fault = error{
/// An instruction, a constant or a record past the mission image.
OutsideImage,
/// An opcode the VM has no handler for.
UnknownOpcode,
StackOverflow,
StackUnderflow,
/// A number past what it indexes: a part, a local, a command, an event's value.
OutOfRange,
/// `push_argument` or `select_argument` in a block started with no arguments.
NoFrame,
/// A store with no `select_` before it.
NoStore,
/// An integer division by zero.
DivisionByZero,
/// The thread ran `most_steps` opcodes in one run without waiting, which would hang the game.
RunsTooLong,
};
/// The most opcodes a thread runs in one run (`Machine.run`), far more than a run of a shipped
/// mission takes.
pub const most_steps: usize = 1_000_000;
/// A thread as OpenReliant runs it: the game's record, with the places the game keeps in it as
/// pointers kept beside it.
pub const Running = struct {
/// The game's record: its wake time, locals, stack, call depth, trigger and result. Its
/// pointers stay null.
record: vm.Thread = std.mem.zeroes(vm.Thread),
/// Where its next instruction lies in the mission image; null for a free slot (`Thread.ip`).
ip: ?u32 = null,
/// Where the running block ends, and its constants start (`Thread.block_end`).
block_end: u32 = 0,
/// Where the running block ended as the editor's step over began (`Thread.step_block_end`).
step_block_end: u32 = 0,
/// Where the running part's first argument lies on the stack; null for a block started with
/// none (`Thread.frame`).
frame: ?u8 = null,
/// The first free place of its stack (`Thread.stack_top`).
top: u8 = 0,
/// The index of the trigger that started it in the trigger list, whole, where one did; the
/// record keeps its low byte (`Thread.trigger`).
trigger: ?usize = null,
/// Whether its slot is free (`ip`).
pub fn isFree(thread: *const Running) bool {
return thread.ip == null;
}
fn push(thread: *Running, value: u32) Fault!void {
if (thread.top >= thread.record.stack.len) return error.StackOverflow;
thread.record.stack[thread.top] = value;
thread.top += 1;
}
/// The value `back` places below the top of the stack: 1 for the top.
fn below(thread: *Running, back: u8) Fault!*u32 {
if (thread.top < back) return error.StackUnderflow;
return &thread.record.stack[thread.top - back];
}
fn drop(thread: *Running, count: u8) Fault!void {
if (thread.top < count) return error.StackUnderflow;
thread.top -= count;
}
fn pop(thread: *Running) Fault!u32 {
const value = (try thread.below(1)).*;
thread.top -= 1;
return value;
}
/// The two values on top of the stack, `a` below `b`, which a binary opcode takes, and leaves
/// its result in `a`'s place.
fn pair(thread: *Running) Fault!struct { a: *u32, b: u32 } {
const b = (try thread.below(1)).*;
const a = try thread.below(2);
thread.top -= 1;
return .{ .a = a, .b = b };
}
};
/// A walk of a pool as the game walks its threads and its timers (`vm_threads_run`,
/// `vm_run_timers`, `cmd_DestroyTimer`, `trigger_thread_running`): each entry that is not free
/// (`isFree`) in turn, until as many have been given as were in use as the walk began (`count`).
/// An entry is looked at as the walk reaches it, so one that comes into use in a later slot before
/// then is given too, and the count the walk began with holds whatever its work does to the pool's.
pub fn Live(comptime T: type, comptime isFree: fn (*const T) bool) type {
return struct {
/// The pool itself.
entries: []T,
/// How many more entries in use the walk gives.
left: usize,
/// The next entry to look at.
at: usize = 0,
const Walk = @This();
pub fn init(entries: []T, count: usize) Walk {
return .{ .entries = entries, .left = count };
}
/// The next entry in use, and its index in the pool.
pub fn next(walk: *Walk) ?struct { *T, usize } {
while (walk.left != 0 and walk.at < walk.entries.len) {
const index = walk.at;
walk.at += 1;
const entry = &walk.entries[index];
if (isFree(entry)) continue;
walk.left -= 1;
return .{ entry, index };
}
return null;
}
};
}
/// What the last `select_` opcode chose for `assign` and the compound stores (`vm_store_target`,
/// `0x00537408`).
pub const Store = union(enum) {
none,
/// A dword of the mission image: a global's value.
image: u32,
/// A place on a thread's stack: an argument's.
stack: struct { thread: u8, place: u8 },
/// One of the game's variables.
variable: u8,
};
/// The components `push_component` named for the values it pushed since the last command
/// (`vm_component_tag_list`, `0x00537420`), each by the place of its value on the running thread's
/// stack.
pub const Tags = struct {
tags: [vm.ComponentTag.max]Tag = undefined,
count: u8 = 0,
pub const Tag = struct { place: u8, component: u8 };
/// `vm_tag_component` (`0x0045D8B0`). **Fix:** the game writes a ninth past its list.
fn add(tags: *Tags, component: u8, place: u8) void {
if (tags.count == tags.tags.len) return;
tags.tags[tags.count] = .{ .place = place, .component = component };
tags.count += 1;
}
/// `vm_tags_clear` (`0x0045D890`), after every command.
fn clear(tags: *Tags) void {
tags.count = 0;
}
/// `vm_tag_pop` (`0x0045D8E0`): the last tag taken off the list.
fn pop(tags: *Tags) void {
if (tags.count > 0) tags.count -= 1;
}
};
/// A free timer, as `mission_script_start` fills the table: every byte `0xFF`.
const free_timer = std.mem.bytesToValue(vm.Timer, &@as([@sizeOf(vm.Timer)]u8, @splat(0xFF)));
comptime {
assert(free_timer.isFree());
}
/// What `_unknown_00537401` is set to as the script starts and before every command
/// (`0x0045CC38`, `0x0045BEDF`).
const unknown_00537401_reset: u8 = 0xFF;
/// The value `push_percent` scales by (`0x004DC730`), a hundredth as a float rounds it.
const percent: f32 = 0.01;
/// The records of the second command catalogue that `command_b` reads (`command_catalogue_b`,
/// `0x004F3AD0`): its one command, Test_AI_Function, which has no implementation, and the empty
/// record that ends the catalogue. The catalogue counts no commands (`catalogue_count`), but
/// `command_b` reads a record by its number whatever the count: past these two, the game's strings.
const catalogue_b = [_]struct { name: []const u8, arguments: u8 }{
.{ .name = "Test_AI_Function", .arguments = 2 },
.{ .name = "", .arguments = 0 },
};
/// What `command_b` gives: the game calls a stub in place of the command's implementation, which
/// returns 1 (`0x0045D800`).
const stub_result = run_on;
pub const Machine = struct {
gpa: Allocator,
/// The mission it runs: its image, which the script reads its records from and writes its
/// globals into, and the tables binding it made.
mission: *bind.Mission,
/// The game's random numbers (`rand`), which `random_branch` draws.
random: *Random,
/// `vm_thread_pool` (`0x00537590`).
threads: [vm.max_threads]Running = @splat(.{}),
/// `vm_thread_count` (`0x00537415`).
thread_count: u8 = 0,
/// `vm_finished` (`0x00537574`): set by a `return` at call depth zero.
finished: bool = false,
/// `vm_first_finished` (`0x00537410`): set once the pool's first thread finishes.
first_finished: bool = false,
/// What the VM keeps for the editor link: whether an editor is there, its hold on the script,
/// its step and its pause of the mission.
editor: vm.editor.Editor = .{},
/// OpenReliant's: the thread the editor stopped last, until it runs again, which the script's
/// start runs on as the editor releases it (`startPart`).
stopped: ?u8 = null,
store: Store = .none,
tags: Tags = .{},
/// `vm_clock` (`0x00538C9C`): seconds of the mission.
clock: u32 = 0,
/// `vm_clock_ticked` (`0x00537580`): set as the clock ticks, until the timers have run for the
/// tick.
ticked: bool = false,
/// `vm_timers_running` (`0x00537400`): whether the timers run, set as the script starts.
timers_running: bool = true,
/// `vm_timer_table` (`0x00537470`).
timers: [vm.max_timers]vm.Timer = @splat(free_timer),
/// `vm_timer_count` (`0x00537468`).
timer_count: u16 = 0,
variables: vm.Variables = .{},
/// `vm_command_flag` (`0x00537584`): whether `forEachShip` passes over the players' ships in a
/// flight group, as the running command's flags in section 24 have it
/// (`dte.CommandFlags.players`, inverted).
skips_players: bool = false,
/// `0x00537401`: **Unknown.** Set to `unknown_00537401_reset` as the script starts and before
/// every command.
_unknown_00537401: u8 = unknown_00537401_reset,
/// `event_values` (`0x00538CA0`): the last events of the conditions that keep them, for each
/// object.
event_values: []vm.ObjectEvents = &.{},
/// The commands not ported yet that have run, each logged the first time.
logged: std.bit_set.Static(executor.commands.table.len) = .empty,
/// What the commands act on the game through, which the game's code reaches through its
/// globals: the world and its clock, as the mission's start and its frame give them. Null where
/// there is no game, as in a test of the script alone, and the commands that act on it then do
/// nothing.
game: ?aigeneric.Context = null,
/// `for_each_ship_first` (`0x00537418`): the first ship the running `forEachShip` has run its
/// command for, which each later one's object names (`GameObject._unknown_698`); and
/// `for_each_ship_count` (`0x00537575`), how many it has.
walk_first: ?u16 = null,
walk_count: u8 = 0,
/// `wait_still_moving` (`0x0052A1E0`): whether the ships `WaitForJumpOrLaunch` walks are still
/// jumping or launching.
still_moving: bool = false,
/// `condition_verdict` (`0x00525F84`): the condition's handlers' verdict on the event being
/// raised on a flight group or a squad (`vm.triggers.raiseOnGroups`). While it is false, only
/// the triggers of the repeat mode the condition exempts answer. Each event raised sets it
/// again, as the script's start does.
verdict: bool = true,
/// `vm_last_jump` (`0x005373F4`): the script's clock when JUMP DRIVE last took a jump or a warp
/// the mission had ready, which `WhenPlayerLastJumped` counts from; `never_jumped` until then.
last_jumped: u32 = never_jumped,
/// The problems with the mission's file already logged: each is logged the first time in a
/// mission (`firstTime`), so that a looping script or a trigger tested every frame can't
/// repeat it.
warned: std.EnumSet(Warning) = .empty,
/// `last_jumped` as the script starts (`0x0045CC2E`).
pub const never_jumped: u32 = 0xFFFF;
/// The problems with a mission's file that the machine and its commands log.
pub const Warning = enum {
/// A trigger's operand names no ship, flight group or squad.
named_nothing,
/// A command's text argument runs outside the mission's file.
text_outside,
/// A name is too long for the game's buffer.
long_name,
/// A script block's length lies outside the mission's file.
block_outside,
/// The squads section can't be read.
squads,
/// A squad's members can't be walked.
squad_members,
};
/// Whether `warning` is new in this mission, which it then no longer is.
pub fn firstTime(machine: *Machine, warning: Warning) bool {
if (machine.warned.contains(warning)) return false;
machine.warned.insert(warning);
return true;
}
pub fn init(gpa: Allocator, bound: *bind.Mission, random: *Random) Machine {
return .{ .gpa = gpa, .mission = bound, .random = random };
}
pub fn deinit(machine: *Machine) void {
machine.gpa.free(machine.event_values);
}
/// `mission_script_start` (`0x0045CBC0`), as the mission's binding ends: every object's kept
/// events emptied, the clock, the timers, the threads and the tags reset, the handlers' verdict
/// and the last jump's time too, the editor's pause, hold and step cleared, and the timers set
/// running. Then, while an editor is linked, the start waits for its flags
/// (`vm.editor.Editor.waitForFlags`), before each start part runs (`startPart`). Then every
/// object's triggers are armed, and each ship's Destroyed flag is cleared and its components
/// all intact. Where a curve starts at the ship, the first such curve's ships are made
/// (`0x0045CD71`): the ship it starts at, those its tangents are drawn to, and the ship it ends
/// at, each where its slot holds no object made yet, which the start part may have left
/// (`executor.createShip`).
///
/// **Fix:** the game takes the object past its array for a curve that names no ship;
/// OpenReliant passes over it.
pub fn start(machine: *Machine) !void {
const file = machine.mission.file;
machine.gpa.free(machine.event_values);
machine.event_values = &.{};
machine.event_values = try machine.gpa.alloc(vm.ObjectEvents, (try file.objects()).len);
@memset(machine.event_values, std.mem.zeroes(vm.ObjectEvents));
machine._unknown_00537401 = unknown_00537401_reset;
machine.first_finished = false;
machine.editor.reset();
machine.last_jumped = never_jumped;
machine.verdict = true;
machine.clock = 0;
machine.timers = @splat(free_timer);
machine.resetThreads();
machine.tags.clear();
machine.timer_count = 0;
machine.ticked = false;
machine.timers_running = true;
machine.editor.waitForFlags();
for (try file.parts()) |part| {
if (part.flags.start and !part.isEmpty()) machine.startPart(part);
}
const triggers = try machine.mission.triggers();
for (try file.objects()) |object| {
for (vm.triggers.sliceOf(triggers, object).triggers) |*trigger| trigger.armed = 1;
}
const curves = try file.curves();
for (try machine.mission.ships(), 0..) |*ship, index| {
ship.flags = .{ .destroyed = false, ._unknown = 0 };
ship.intact_components = dte.Ship.all_intact;
const game = machine.game orelse continue;
const curve = curves[executor.curves.starting(curves, @intCast(index)) orelse continue];
const all = game.world.objects;
for ([_]dte.Reference{ curve.start, curve.leaving_handle, curve.arriving_handle, curve.end }) |point| {
if (point.index >= all.slots.len or all.slots[point.index].object.created) continue;
executor.createShip(game, machine.mission, point.index);
}
}
}
/// `part_run` (`0x0045BAA0`): runs a part's block at once, on a new thread.
pub fn runPart(machine: *Machine, part: dte.Part) void {
_ = machine.startThread(machine.mission.blockAt(.script, part.block()), null, false, null, null);
}
/// A start part, as the script starts (`mission_script_start`, `0x0045CCCD`): run at once
/// (`runPart`), then the editor's messages read and a millisecond waited. While the editor
/// holds the script, the start waits on it, reading its messages each millisecond. Once the
/// editor releases the thread it stopped, the thread runs on. A step that left the script
/// released as its thread yielded ends the wait, and the next thread to run takes the step on.
///
/// **Fix:** while the editor holds the script, the game runs the part again on a new thread
/// each time round. Each one runs the part's statements before the stop again and stops at the
/// same byte, and a release goes to the newest. OpenReliant runs the stopped thread on from
/// where it stopped.
fn startPart(machine: *Machine, part: dte.Part) void {
const editor = &machine.editor;
machine.runPart(part);
while (true) {
editor.check();
editor.sleep(vm.editor.part_wait_ms);
switch (editor.hold) {
.none => return,
.held => {},
.released => machine.runThread(machine.stopped orelse return),
}
}
}
/// `vm_thread_start` (`0x0045B8D0`): starts a thread on `block`, the one at `into` or a free
/// one, which runs now unless `deferred`, for the trigger `trigger`, by its index in the
/// trigger list, where one starts it. None starts while 31 run, or on no block.
/// **Fix:** the game takes a free thread past its pool where none is free.
/// **Fix:** the game reads the length of a block past its copy of the file; OpenReliant starts
/// no thread there, and logs it once.
pub fn startThread(machine: *Machine, block: ?u32, into: ?u8, deferred: bool, frame: ?u8, trigger: ?usize) ?u8 {
const at = block orelse return null;
if (machine.thread_count + 1 >= vm.max_threads) return null;
const index = into orelse machine.allocThread() orelse return null;
const length = machine.mission.halfword(at) catch |err| {
if (machine.firstTime(.block_outside)) log.warn("the script block at 0x{X:0>8} lies outside the mission's file, so no thread starts on it: {s}", .{ at, @errorName(err) });
return null;
};
const thread = &machine.threads[index];
thread.ip = at + @sizeOf(u16);
thread.frame = frame;
thread.record.wake_time = 0;
thread.record._unknown_b4 = 0;
thread.block_end = at + length;
thread.record.call_depth = 0;
thread.record.interrupted = false;
thread.trigger = trigger;
thread.record.trigger = if (trigger) |started| @truncate(started) else vm.Thread.no_trigger;
thread.record._unknown_ac = vm.Thread.unknown_ac_start;
machine.thread_count += 1;
if (!deferred) machine.runThread(index);
return index;
}
/// `vm_thread_alloc` (`0x0045B960`): the first free thread, its stack emptied.
pub fn allocThread(machine: *Machine) ?u8 {
for (&machine.threads, 0..) |*thread, index| {
if (thread.ip != null) continue;
thread.top = 0;
return @intCast(index);
}
return null;
}
/// The threads running, from the pool's first (`Live`).
pub fn liveThreads(machine: *Machine) Live(Running, Running.isFree) {
return .init(&machine.threads, machine.thread_count);
}
/// The timers set, from the table's first (`Live`).
fn liveTimers(machine: *Machine) Live(vm.Timer, vm.Timer.isFree) {
return .init(&machine.timers, machine.timer_count);
}
/// `vm_threads_reset` (`0x0045B990`): frees every thread.
fn resetThreads(machine: *Machine) void {
machine.thread_count = 0;
machine.threads = @splat(.{});
machine.stopped = null;
}
/// `vm_thread_run` (`0x0045BA30`): runs a thread until it yields or finishes, unless it waits
/// for a later clock. A finished thread's slot is freed.
fn runThread(machine: *Machine, index: u8) void {
const thread = &machine.threads[index];
if (thread.record.wake_time != 0) {
if (machine.clock <= thread.record.wake_time) return;
thread.record.wake_time = 0;
}
machine.finished = false;
if (!machine.run(index)) return;
thread.ip = null;
machine.thread_count -= 1;
}
/// `vm_threads_run` (`0x0045B9B0`), once a frame (`process_mission`): each thread that was
/// running as the pass began, and not waiting for its trigger (`InterruptTriggerCode`), runs
/// on. A thread the pass starts in a later slot runs in it too, while the pass has threads
/// still to count.
pub fn runThreads(machine: *Machine) void {
var threads = machine.liveThreads();
while (threads.next()) |found| {
const thread, const index = found;
if (!thread.record.interrupted) machine.runThread(@intCast(index));
}
}
/// `vm_run_timers` (`0x0045D140`), once the clock has ticked (`process_mission`): each timer
/// counts down once a clock value, and at zero starts its part on a new thread, then reloads
/// its countdown, or after its last firing is destroyed.
pub fn runTimers(machine: *Machine) void {
var timers = machine.liveTimers();
while (timers.next()) |found| {
const timer = found[0];
if (timer.last_tick == machine.clock) continue;
timer.countdown -%= 1;
if (timer.countdown == 0) machine.fire(timer);
}
}
fn fire(machine: *Machine, timer: *vm.Timer) void {
timer.last_tick = machine.clock;
const part = machine.partEntry(.a, timer.part);
if (timer.remaining == 0) {
timer.countdown = timer.period;
} else {
timer.remaining -= 1;
if (timer.remaining != 0) timer.countdown = timer.period else machine.destroyTimers(timer.id);
}
_ = machine.startThread(part.block, null, true, null, null);
}
/// A part table's entry `index`: none past the table.
fn partEntry(machine: *Machine, table: enum { a, b }, index: anytype) vm.Part {
const parts = switch (table) {
.a => &machine.mission.parts,
.b => &machine.mission.parts_b,
};
const at = std.math.cast(usize, index) orelse return .{};
return if (at < parts.len) parts[at] else .{};
}
/// `cmd_CreateTimer` (`0x0045D210`, command `0x01`): a timer with an ID, which destroys any
/// timer with the same, that starts a part every so many seconds, so many times or for ever.
/// **Fix:** the game takes a timer past its table where none is free.
pub fn createTimer(call: Call) u32 {
const machine = call.machine;
const id: u16 = @truncate(call.args[0]);
machine.destroyTimers(id);
const timer = for (&machine.timers) |*timer| {
if (timer.isFree()) break timer;
} else return run_on;
machine.timer_count += 1;
timer.id = id;
timer.part = @bitCast(call.args[1]);
timer.period = @truncate(call.args[2]);
timer.countdown = timer.period;
if (timer.period == 1) timer.countdown += 1;
timer.last_tick = 0;
timer.remaining = @truncate(call.args[3]);
return run_on;
}
/// `cmd_DestroyTimer` (`0x0045D290`, command `0x02`): destroys every timer with an ID.
pub fn destroyTimer(call: Call) u32 {
call.machine.destroyTimers(@truncate(call.args[0]));
return run_on;
}
/// Every timer set with the ID `id` is freed.
fn destroyTimers(machine: *Machine, id: u16) void {
var timers = machine.liveTimers();
while (timers.next()) |found| {
const timer = found[0];
if (timer.id != id) continue;
timer.free();
machine.timer_count -= 1;
}
}
/// `cmd_Wait` (`0x0045D2E0`, command `0x05`): the thread waits until the clock has passed so
/// many seconds more.
pub fn wait(call: Call) u32 {
const machine = call.machine;
machine.threads[call.thread].record.wake_time = call.args[0] +% machine.clock;
return yield;
}
/// `cmd_InterruptTriggerCode` (`0x0045D450`, command `0x17`): the thread stops until its
/// trigger fires again.
pub fn interruptTriggerCode(call: Call) u32 {
call.machine.threads[call.thread].record.interrupted = true;
return yield;
}
/// `cmd_KillAllScriptExecutionExecptMe` (`0x0045D990`, command `0x51`): every thread but the
/// caller's ends.
pub fn killAllScriptExecutionExceptMe(call: Call) u32 {
const machine = call.machine;
for (&machine.threads, 0..) |*thread, index| {
if (thread.ip == null or index == call.thread) continue;
thread.ip = null;
machine.thread_count -= 1;
}
return run_on;
}
/// The display, and its window a command's argument numbers, in a game with a display and
/// where the argument numbers one of its windows.
fn instrument(game: aigeneric.Context, value: u32) ?struct { *hud.State, hud.windows.Window } {
const display = game.world.display orelse return null;
const number = std.math.cast(u4, value) orelse return null;
return .{ display, std.enums.fromInt(hud.windows.Window, number) orelse return null };
}
/// `cmd_OpenInstrument` (`0x0045D9D0`, command `0x40`): the display's window the argument
/// numbers opens (`hud.windows.Windows.open`) and is held open until the script closes it. The
/// radio's menu, window 11, starts from its top (`radio.menu.Menu.start`), and opening
/// the objectives, window 10, closes the wing status window where it is up. **Unknown:** the
/// byte after the window's hold (`+0x25`), which the command clears. **Unverified:** it lies
/// among the interpreter's code, after `cmd_KillAllScriptExecutionExecptMe`, as
/// `CloseInstrument` does, rather than in the Executor's.
///
/// **Fix:** the game opens a window past its fifteen from past its table; OpenReliant opens
/// none.
pub fn openInstrument(call: Call, game: aigeneric.Context) void {
const display, const window = instrument(game, call.args[0]) orelse return;
const windows = &display.windows;
_ = windows.open(window, false);
windows.status.getPtr(window).held = true;
if (window == .comms) game.world.player.menu.start(game);
if (window == .objectives and windows.up(.wing_status)) windows.close(.wing_status);
}
/// `cmd_CloseInstrument` (`0x0045DA30`, command `0x41`): the display's window the argument
/// numbers closes (`hud.windows.Windows.close`), held open no more.
pub fn closeInstrument(call: Call, game: aigeneric.Context) void {
const display, const window = instrument(game, call.args[0]) orelse return;
display.windows.close(window);
display.windows.status.getPtr(window).held = false;
}
/// `vm_argument_component` (`0x0045D950`): the component `push_component` named for the
/// running command's argument `index`, or null for none.
pub fn argumentComponent(machine: *const Machine, thread: u8, index: u8) ?u8 {
const first = machine.threads[thread].top;
for (machine.tags.tags[0..machine.tags.count]) |tag| {
if (tag.place -% first == index) return tag.component;
}
return null;
}
/// `vm_tag_matches` (`0x0045D910`): whether `component` is one that `push_component` named for
/// the running command's arguments, any of them; or, where it names none of them, the object
/// itself (`dte.Trigger.whole_object`).
pub fn tagged(machine: *const Machine, component: u8) bool {
for (machine.tags.tags[0..machine.tags.count]) |tag| {
if (tag.component == component) return true;
}
return component == dte.Trigger.whole_object;
}
/// A command's work for each ship `forEachShip` runs it for: the command's call, with its
/// arguments after the first, and the ship.
pub const ShipImplementation = *const fn (call: Call, ship: Ship) void;
/// A ship `forEachShip` runs a command for: the game, the ship by its index among the mission's
/// ships, and its object's slot.
pub const Ship = struct {
game: aigeneric.Context,
index: u16,
slot: *create.Slot,
};
/// `for_each_ship` (`0x0045D460`): runs `each` for each ship of the ship, flight group or squad
/// the command's first argument names, with its arguments after the first. A flight group's
/// ships run in the mission's order, and a squad's members in theirs, a member that is a flight
/// group or a squad for each of its ships, one that names a component of a ship with the
/// component tagged on the first argument (`argumentComponent`). While the command's flag is
/// set (`skips_players`), the players' ships in a flight group are passed over. Each ship's
/// object names the first ship the walk ran for (`GameObject._unknown_698`), or none for the
/// first. Nothing runs without a game.
pub fn forEachShip(call: Call, each: ShipImplementation) void {
const machine = call.machine;
const game = machine.game orelse return;
if (call.args.len == 0) return;
machine.walk_first = null;
machine.walk_count = 0;
const rest: Call = .{ .machine = machine, .thread = call.thread, .args = call.args[1..] };
machine.walkEntity(rest, game, call.args[0], each) catch |fault| {
log.warn("a command's ships are walked no further: {s}", .{@errorName(fault)});
};
}
/// `for_each_ship`'s walk (`for_each_ship_walk`, `0x0045D480`) of `entity`, in `game`: a ship,
/// a flight group's ships, or a squad's members (`walkSquad`).
fn walkEntity(machine: *Machine, call: Call, game: aigeneric.Context, entity: u32, each: ShipImplementation) Fault!void {
if (entity == bind.Mission.no_place) return;
if (machine.mission.holds(.ships, entity)) return machine.walkShip(call, game, entity, each);
if (machine.mission.holds(.flight_groups, entity)) return machine.walkGroup(call, game, try machine.groupAt(entity), each);
if (!machine.mission.holds(.squads, entity)) return;
var walk: SquadPath.Walk = .{};
return machine.walkSquad(call, game, entity, each, &walk.start(machine.mission.squadIndex(entity) orelse bind.Mission.no_record));
}
/// `for_each_ship_walk`'s walk of the squad at `place`, which `path` stands in. Its members run
/// from the first its record at `place` names (`bind.Mission.squadMembersFrom`), and the walk
/// goes down into a squad among them where the path goes into it (`SquadPath.into`).
///
/// **Fix:** the game walks a member of the object table no record stands for from address zero;
/// OpenReliant passes over the member.
fn walkSquad(machine: *Machine, call: Call, game: aigeneric.Context, place: u32, each: ShipImplementation, path: *const SquadPath) Fault!void {
// The game takes a squad whose first member's low byte is `no_member_low` for one with
// none.
const first_member = place + @offsetOf(dte.Squad, "first_member");
if (try machine.mission.byte(first_member) == no_member_low) return;
const first = try machine.mission.halfword(first_member);
var members = machine.mission.squadMembersFrom(path.squad, first);
while (members.next()) |member| switch (member) {
.ship => |ship| {
if (ship.component) |component| machine.tags.add(component, machine.threads[call.thread].top);
try machine.walkShip(call, game, machine.mission.recordPlace(.ships, ship.index), each);
if (ship.component != null) machine.tags.pop();
},
.flight_group => |group| try machine.walkGroup(call, game, group, each),
.squad => |inner| if (path.into(inner)) |deeper| try machine.walkSquad(call, game, machine.mission.recordPlace(.squads, inner), each, &deeper),
};
}
/// The low byte of a squad's `first_member` that `for_each_ship` takes for a squad with no
/// members (`0x0045D594`).
const no_member_low: u8 = 0xFF;
/// The flight group at `place`, as far as `for_each_ship` reads it, wherever `place` lies among
/// the flight groups (`0x0045D4F8`): its count of ships and where the first lies in the list
/// binding the mission made.
fn groupAt(machine: *Machine, place: u32) Fault!dte.FlightGroup {
var group = std.mem.zeroes(dte.FlightGroup);
group.ship_count = try machine.mission.byte(place + @offsetOf(dte.FlightGroup, "ship_count"));
group.first_ship = try machine.mission.word(place + @offsetOf(dte.FlightGroup, "first_ship"));
return group;
}
/// Each ship of flight group `group`, as binding the mission listed them
/// (`bind.Mission.groupShips`), the players' ones passed over while the command's flag says
/// so (`skips_players`).
fn walkGroup(machine: *Machine, call: Call, game: aigeneric.Context, group: dte.FlightGroup, each: ShipImplementation) Fault!void {
const players = game.world.objects.players;
for (machine.mission.groupShips(group)) |ship| {
if (machine.skips_players and ship < players) continue;
try machine.walkShip(call, game, machine.mission.recordPlace(.ships, ship), each);
}
}
/// `for_each_ship_run` (`0x0045D700`), `for_each_ship`'s work for one ship: its object names
/// the first ship of the walk (`for_each_ship_note`, `0x0045D720`, `bind.recordReference`),
/// then the command runs for it, where the ship's object is one of the game's
/// (`mission.shipSlot`).
fn walkShip(machine: *Machine, call: Call, game: aigeneric.Context, ship: u32, each: ShipImplementation) Fault!void {
const all = game.world.objects;
const index = mission.shipSlot(machine.mission, all, ship) orelse return;
const slot = &all.slots[index];
slot.object._unknown_698 = bind.recordReference(.ship, machine.walk_first);
if (machine.walk_first == null) machine.walk_first = index;
machine.walk_count +%= 1;
each(call, .{ .game = game, .index = index, .slot = slot });
}
/// `vm_run` (`0x0045C980`): runs the thread from its instruction pointer, an opcode at a time,
/// until a handler returns zero. True once the thread has finished, which a `return` at call
/// depth zero does.
///
/// **Improvement:** jumps only go forward and calls nest only as deep as the thread's stack
/// holds, but a part can call another many times, which calls another many times, and so on.
/// Such a script runs for ages without waiting, and the game hangs. OpenReliant stops a run
/// after `most_steps` opcodes, as it stops a thread that faults: the log says where, the
/// script ends, and the game goes on.
///
/// Before each opcode, the editor link may stop the thread (`stopsBefore`): the script is held,
/// the editor told where, and the thread stays at that byte. A run that ends as its thread
/// yields while the editor steps through or over statements releases the hold again
/// (`0x0045CAD3`), so that the next thread to run carries the step on. A thread that finishes
/// ends the step.
fn run(machine: *Machine, index: u8) bool {
if (machine.stopped == index) machine.stopped = null;
var previous: u32 = 1;
var steps: usize = 0;
while (previous != 0) : (steps += 1) {
if (machine.stopsBefore(index)) |offset| {
machine.stopped = index;
machine.editor.stop(offset);
return machine.runEnds(index);
}
const stepped = if (steps < most_steps) machine.step(index, previous) else error.RunsTooLong;
previous = stepped catch |fault| {
log.warn("a script thread ends at {d}: {s}", .{ machine.threads[index].ip orelse 0, @errorName(fault) });
machine.finished = true;
machine.threads[index].record.call_depth = 0;
return true;
};
}
const stepping = machine.editor.step != .none and machine.editor.step != .run_on;
if (!machine.finished and stepping) machine.editor.hold = .released;
return machine.runEnds(index);
}
/// The end of `vm_run` (`0x0045CAE1`): a thread with calls still open hasn't finished. One that
/// has finished ends the editor's step, and the pool's first thread sets `first_finished`.
fn runEnds(machine: *Machine, index: u8) bool {
if (machine.threads[index].record.call_depth != 0) return false;
if (machine.finished) {
if (index == 0) machine.first_finished = true;
machine.editor.step = .none;
}
return machine.finished;
}
/// Whether the thread stops before its next instruction for the editor, as `vm_run` checks
/// before each opcode (`0x0045C995` to `0x0045CA52`), and the offset in the script of the byte
/// it stops before. With an editor there, it stops before a byte the editor flagged
/// (`flaggedAt`), except where the editor released the script with a run on, which goes past
/// it. The first instruction after a release takes the hold off and starts the step: a step
/// over notes the running block's end. A step stops before the next instruction that starts a
/// statement (`opcodes.Info.starts_statement`); a step over only once the running block's end
/// is the one noted again, or a part has returned.
fn stopsBefore(machine: *Machine, index: u8) ?u32 {
const editor = &machine.editor;
if (!editor.present) return null;
const thread = &machine.threads[index];
const at = thread.ip orelse return null;
const offset = at -% machine.mission.file.entry(.script).offset;
if (machine.flaggedAt(offset)) {
if (editor.hold != .released) return offset;
if (editor.step == .run_on) {
editor.hold = .none;
editor.step = .none;
return null;
}
}
if (editor.step == .none) return null;
if (editor.hold == .released) {
editor.hold = .none;
switch (editor.step) {
.run_on => editor.step = .none,
.over => {
thread.step_block_end = thread.block_end;
editor.step_returned = false;
},
else => {},
}
return null;
}
const opcode = machine.mission.byte(at) catch return null;
const info = vm.opcodes.find(@fromBackingInt(opcode)) orelse return null;
if (!info.starts_statement) return null;
if (editor.step == .over and thread.block_end != thread.step_block_end and !editor.step_returned) return null;
return offset;
}
/// Whether the byte `offset` bytes into the script (section 6) is one the editor flagged to
/// stop before: bit 0 of its flag among the script's flags (section 10), which the editor sends
/// (tag `0x09`).
///
/// **Fix:** the game counts a byte of `script_b` from the script's start too, and reads its
/// flag from past the flags' end; OpenReliant takes a byte outside the script, or past the
/// flags, as unflagged.
fn flaggedAt(machine: *const Machine, offset: u32) bool {
const script = machine.mission.file.entry(.script);
if (offset >= @as(u32, script.count) * @sizeOf(u16)) return false;
const flags = machine.mission.file.entry(.script_flags);
if (offset >= flags.count) return false;
const flag = machine.mission.byte(flags.offset + offset) catch return false;
return flag & stop_flag != 0;
}
/// One opcode's handler (`vm_dispatch_table`, `0x004F6350`): what it does, with the handler's
/// return value, `previous` to carry on or zero to end the run.
fn step(machine: *Machine, index: u8, previous: u32) Fault!u32 {
const thread = &machine.threads[index];
const opcode: dte.Opcode = @fromBackingInt(try machine.operand(thread));
switch (opcode) {
// The comparisons take the values as unsigned (`CMP`, `SBB`), and the float ones load
// each as a whole number (`FILD`), exactly, so they compare as the others do.
.equal => try compare(thread, .eq),
.not_equal => try compare(thread, .neq),
.greater, .greater_f => try compare(thread, .gt),
.greater_equal, .greater_equal_f => try compare(thread, .gte),
.less, .less_f => try compare(thread, .lt),
.less_equal, .less_equal_f => try compare(thread, .lte),
.in_flight_group, .not_in_flight_group => {
const values = try thread.pair();
const in = try machine.inFlightGroup(values.a.*, values.b);
values.a.* = @intFromBool(in == (opcode == .in_flight_group));
},
.in_squad, .not_in_squad => {
const values = try thread.pair();
const in = try machine.inSquad(values.b, values.a.*, dte.Trigger.whole_object);
values.a.* = @intFromBool(in == (opcode == .in_squad));
},
inline .assign, .add_assign, .sub_assign, .mul_assign, .div_assign, .add_assign_f, .sub_assign_f, .mul_assign_f, .div_assign_f => |store| {
const value = (try thread.below(1)).*;
const target = try machine.stored();
target.* = switch (store) {
.assign => value,
.add_assign => target.* +% value,
.sub_assign => target.* -% value,
.mul_assign => target.* *% value,
.div_assign => try divide(target.*, value),
// `FILD` the value, then the operation on the float stored, rounded.
.add_assign_f => @bitCast(single(float(target.*) + unsigned(value))),
.sub_assign_f => @bitCast(single(float(target.*) - unsigned(value))),
.mul_assign_f => @bitCast(single(unsigned(value) * float(target.*))),
.div_assign_f => @bitCast(single(float(target.*) / unsigned(value))),
else => comptime unreachable,
};
try thread.drop(2);
},
inline .add, .sub, .mul, .div, .logical_and, .logical_or, .add_f, .sub_f, .mul_f, .div_f => |operation| {
const values = try thread.pair();
const a = values.a.*;
const b = values.b;
values.a.* = switch (operation) {
.add => a +% b,
.sub => a -% b,
.mul => a *% b,
.div => try divide(a, b),
.logical_and => @intFromBool(a != 0 and b != 0),
.logical_or => @intFromBool(a != 0 or b != 0),