Repository navigation
Expand file tree
/
Copy pathgame.zig
More file actions
2016 lines (1921 loc) · 93.5 KB
/
Copy pathgame.zig
File metadata and controls
2016 lines (1921 loc) · 93.5 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 game side of mods' scripts ([#498](https://github.com/OpenReliant/openreliant/issues/498)):
//! the scripts that decide what happens in the game, while a game runs. A game runs from the moment
//! the front end starts a campaign, loads a saved game or flies a mission on its own (or
//! `--mission` starts one), until the front end's main menu comes back, or OpenReliant quits.
//!
//! - A mod's `Global` scripts start as the game starts, in load order, and each mod's in the order
//! its manifest lists them. They run for the whole game.
//! - Its `[Missions]` scripts start as their mission begins, before the mission's ships are made,
//! and stop once it ends; each attempt at a mission starts them afresh. A key of `[Missions]` is
//! a mission's file name, such as `mission40.dte`, in any case.
//! - Its object scripts start on each object of a class (`Fighter=`) or a type
//! (`Type.predator=`) as the object is added to the mission, and on one object when a global
//! script adds them (`object:add_script`). They stop as their object leaves the mission, or as
//! the mission ends. Each object a mod's scripts run on has the mod opened for it on its own, so
//! its scripts have their own globals.
//! - Its missile scripts (`Missile=`) start on each missile as it's launched, and stop as its
//! flight ends, or as the mission ends. Each missile has the mod opened for it on its own, as an
//! object has.
//! - Its turret scripts (`Turret=`) start on each turret of an object as the object is added, after
//! the object's own scripts, and stop with them. Each turret has the mod opened for it on its own.
//! - The engine calls the scripts' handlers in the order the scripts started: the global and
//! mission scripts', then each object's, by slot, then each missile's, by record. Events sent between scripts wait for the next
//! update (`events.zig`).
//! - `math.random` starts again at each mission's start, from the game's random numbers, so it
//! gives the same numbers on every machine for the same game.
//!
//! An engine handler that raises an error is logged and isn't called again. If no mod has global,
//! mission or object scripts, no Luau state is created.
const std = @import("std");
const Allocator = std.mem.Allocator;
const Io = std.Io;
const log = std.log.scoped(.scripts);
const openreliant = @import("openreliant");
const mods = openreliant.engine.game.bigfile.mods;
const Mod = mods.Mod;
const create = openreliant.engine.game.create;
const engine_missiles = openreliant.engine.game.missiles;
const gameobj = openreliant.engine.game.gameobj;
const aigeneric = openreliant.engine.game.aigeneric;
const winmain = openreliant.engine.game.winmain;
const engine_hooks = openreliant.engine.hooks;
const Object = engine_hooks.Object;
const script = @import("script.zig");
const runtime = @import("runtime.zig");
const Runtime = runtime.Runtime;
const Context = runtime.Context;
const records = @import("records.zig");
const packages = @import("packages.zig");
const hooks = @import("hooks.zig");
const objects = @import("objects.zig");
const missiles = @import("missiles.zig");
const turrets = @import("turrets.zig");
const values = @import("values.zig");
const load = @import("load.zig");
const data = @import("data.zig");
const api = @import("api.zig");
const Call = api.Call;
const running = @import("running.zig");
const interfaces = @import("interfaces.zig");
const world = @import("world.zig");
/// Limits for game scripts: 100 milliseconds per call, since they run as the game plays, and
/// 64 MiB per mod.
pub const limits: runtime.Limits = .{ .time = .fromMilliseconds(100), .memory = runtime.memory_per_mod };
/// The game side of mods' scripts while a game runs.
pub const Game = struct {
gpa: Allocator,
runtime: *Runtime,
/// The scripts that run, with their events and interfaces.
runner: running.Runner,
/// The global and mission scripts that run, then each object's, by slot, then each missile's,
/// by record (`global`, `onObject`, `onMissile`).
lists: [1 + gameobj.max_objects + engine_missiles.max_missiles]running.List = @splat(.empty),
/// The handlers the scripts add to hooks.
hooks: hooks.Hooks,
/// What the engine calls (`create.Objects.scripts`).
scripts: engine_hooks.Scripts,
/// The objects of the game, which handles stand for.
objects: *create.Objects,
/// The mods opened for the mission's scripts, which close as it ends.
mission_mods: std.ArrayList(*Context) = .empty,
/// The mission that runs, if any.
mission: ?MissionHeld = null,
/// The mission that runs, kept from its start.
const MissionHeld = struct {
number: u16,
file: [winmain.mission_path_size]u8,
file_len: u8,
fn of(mission: engine_hooks.Mission) MissionHeld {
var held: MissionHeld = .{ .number = mission.number, .file = undefined, .file_len = @intCast(mission.file.len) };
@memcpy(held.file[0..mission.file.len], mission.file);
return held;
}
pub fn view(held: *const MissionHeld) engine_hooks.Mission {
return .{ .number = held.number, .file = held.file[0..held.file_len] };
}
};
/// Starts a game's scripts for `all`, the game's objects: the `Global` scripts of `opened`,
/// which can read `held`, the records. `version` is OpenReliant's version. Returns null if no
/// mod has global, mission or object scripts.
/// Where `loading`, the scripts start for a saved game, whose state `snapshot.restore` puts
/// back, so they don't get `on_init` yet.
pub fn start(gpa: Allocator, io: Io, opened: []const Mod, held: *records.Records, version: []const u8, all: *create.Objects, shared: runtime.Shared, loading: bool) Allocator.Error!?*Game {
const any = for (opened) |*mod| {
var listed = globalScripts(mod);
if (listed.next() != null) break true;
var keys = mod.manifest.keys(script.missions_section);
if (keys.next() != null) break true;
if (attachesScripts(mod)) break true;
var missile_scripts = missileScripts(mod);
if (missile_scripts.next() != null) break true;
} else false;
if (!any) return null;
const game = try gpa.create(Game);
const scripts = Runtime.create(gpa, io, opened, .{ .side = .game, .limits = limits, .seed = load.seed, .version = version, .shared = shared }) catch |err| {
gpa.destroy(game);
return err;
};
game.* = .{
.gpa = gpa,
.runtime = scripts,
.runner = undefined,
.hooks = undefined,
.scripts = .{ .context = game, .vtable = &vtable },
.objects = all,
};
game.runner = .init(gpa, scripts, &game.lists);
game.hooks = .init(gpa, scripts, &game.scripts);
game.runner.hooks = &game.hooks;
errdefer game.stop();
const state = scripts.state;
records.register(state);
records.push(state, held, false);
scripts.setPackage(.records);
packages.push(scripts);
hooks.Hooks.register(state);
game.hooks.push(state);
scripts.setPackage(.hooks);
objects.register(scripts);
missiles.register(scripts);
turrets.register(scripts);
interfaces.Interfaces.register(state);
game.runner.interfaces.push(state);
scripts.setPackage(.interfaces);
scripts.objects = all;
scripts.game = game;
scripts.runner = &game.runner;
all.scripts = &game.scripts;
// An object's scripts stop as it leaves the mission, so the engine tells the scripts of
// every object that leaves, and of every object added where manifests attach scripts.
game.hooks.want(.object_removed);
for (opened) |*mod| if (attachesScripts(mod)) game.hooks.want(.object_added);
// A missile's scripts start as it's launched, and stop as its flight ends.
for (opened) |*mod| {
var listed = missileScripts(mod);
if (listed.next() == null) continue;
game.hooks.want(.missile_added);
game.hooks.want(.missile_removed);
}
for (opened, 0..) |*mod, at| {
var listed = globalScripts(mod);
if (listed.next() == null) continue;
listed = globalScripts(mod);
const context = try scripts.open(@intCast(at), .global, null);
while (listed.next()) |name| _ = try game.startScript(game.global(), context, name, false, null, loading);
}
return game;
}
/// Stops the game's scripts, as the game ends.
pub fn stop(game: *Game) void {
game.runtime.custom_orders.endMission(game.runtime);
game.objects.scripts = null;
game.stopMissionScripts();
game.runner.deinit();
game.mission_mods.deinit(game.gpa);
game.hooks.deinit();
game.runtime.destroy();
game.gpa.destroy(game);
}
/// The game whose scripts make `call`. Raises an error where no game runs.
pub fn of(call: Call) *Game {
return call.runtime().game orelse call.raise("can only be used while a game runs", .{});
}
/// The global and mission scripts that run.
pub fn global(game: *Game) *running.List {
return &game.lists[0];
}
/// The scripts that run on the object in slot `index`.
pub fn onObject(game: *Game, index: u16) *running.List {
return &game.lists[1 + @as(usize, index)];
}
/// The scripts that run on the missile in record `record`.
pub fn onMissile(game: *Game, record: u8) *running.List {
return &game.lists[1 + gameobj.max_objects + @as(usize, record)];
}
/// `Runner.start`, which also has the engine tell the scripts of each object added where the
/// script handles that.
fn startScript(game: *Game, list: *running.List, context: *Context, name: []const u8, mission: bool, payload: ?data.Data, loading: bool) Allocator.Error!?usize {
const at = try game.runner.start(list, context, name, mission, payload, loading) orelse return null;
if (list.items[at].offered.handlers.get(.on_object_added) != null) game.hooks.want(.object_added);
return at;
}
/// Stops the scripts of the mission, and closes the mods opened for them.
fn stopMissionScripts(game: *Game) void {
game.runner.walking += 1;
defer game.runner.leave();
const list = game.global();
for (list.items, 0..) |held, at| {
if (held.mission) game.runner.stopScript(list, at);
}
for (game.mission_mods.items) |context| {
if (!context.closed) game.runner.closeContext(context);
}
game.mission_mods.clearRetainingCapacity();
}
/// Stops every object's and every missile's scripts, as a mission ends.
fn stopObjectScripts(game: *Game) void {
for (game.lists[1..]) |*list| game.runner.stopAll(list);
}
/// Starts the scripts that mods' manifests attach to the object in slot `index`, as it's added
/// to the mission.
fn objectAdded(game: *Game, index: u16) void {
const slot = &game.objects.slots[index];
const class = if (slot.combat) |combat| combat.class else null;
for (game.runtime.mods, 0..) |*mod, at| {
var keys = mod.manifest.keys(script.section);
var context: ?*Context = null;
while (keys.next()) |key| {
const attachment = script.Attachment.parse(key, mod.name) orelse continue;
const matches = switch (attachment) {
.kind => |kind| kind.class() != null and kind.class() == class,
.object_type => |object_type| object_type == slot.object.type,
};
if (!matches) continue;
var listed: script.List = .of(mod.manifest.value(script.section, key) orelse "");
while (listed.next()) |name| {
const opened = context orelse game.runtime.open(@intCast(at), .object, .{ .object = .of(game.objects, index) }) catch |err| {
log.warn("{s}: the scripts of object {d} can't start: {s}", .{ mod.name, index, @errorName(err) });
return;
};
context = opened;
_ = game.startScript(game.onObject(index), opened, name, false, null, false) catch |err| {
log.warn("{s}: {s} can't start on object {d}: {s}", .{ mod.name, name, index, @errorName(err) });
};
}
}
if (context) |opened| game.runner.closeUnused(game.onObject(index), opened);
}
game.turretsAdded(index);
}
/// Starts the turret scripts of mods' manifests on each turret of the object in slot `index`, as
/// it's added to the mission.
fn turretsAdded(game: *Game, index: u16) void {
const listed = turrets.on(game.objects, index);
if (listed.len == 0) return;
for (game.runtime.mods, 0..) |*mod, at| {
var names = turretScripts(mod);
if (names.next() == null) continue;
for (listed.slice()) |turret| {
var each = turretScripts(mod);
const opened = game.runtime.open(@intCast(at), .object, .{ .turret = .of(game.objects, turret) }) catch |err| {
log.warn("{s}: the scripts of turret {d} of object {d} can't start: {s}", .{ mod.name, turret.gun, index, @errorName(err) });
return;
};
while (each.next()) |name| _ = game.startScript(game.onObject(index), opened, name, false, null, false) catch |err| {
log.warn("{s}: {s} can't start on turret {d} of object {d}: {s}", .{ mod.name, name, turret.gun, index, @errorName(err) });
};
game.runner.closeUnused(game.onObject(index), opened);
}
}
}
/// Calls the `on_removed` of the scripts of the object in slot `index`, and stops them, as it
/// leaves the mission.
fn objectRemoved(game: *Game, index: u16) void {
game.runner.callEach(game.onObject(index), .on_removed, .{});
game.runner.stopAll(game.onObject(index));
}
/// Starts the missile scripts of mods' manifests on the missile in record `record`, as it's
/// launched.
fn missileAdded(game: *Game, record: u8) void {
for (game.runtime.mods, 0..) |*mod, at| {
var listed = missileScripts(mod);
var context: ?*Context = null;
while (listed.next()) |name| {
const opened = context orelse game.runtime.open(@intCast(at), .object, .{ .missile = .of(game.objects, record) }) catch |err| {
log.warn("{s}: the scripts of missile {d} can't start: {s}", .{ mod.name, record, @errorName(err) });
return;
};
context = opened;
_ = game.startScript(game.onMissile(record), opened, name, false, null, false) catch |err| {
log.warn("{s}: {s} can't start on missile {d}: {s}", .{ mod.name, name, record, @errorName(err) });
};
}
if (context) |opened| game.runner.closeUnused(game.onMissile(record), opened);
}
}
/// Calls the `on_removed` of the scripts of the missile in record `record`, and stops them, as
/// its flight ends.
fn missileRemoved(game: *Game, record: u8) void {
game.runner.callEach(game.onMissile(record), .on_removed, .{});
game.runner.stopAll(game.onMissile(record));
}
/// Delivers the events sent since the last update (`events.zig`).
fn deliver(game: *Game) void {
var pending = game.runner.events.take();
defer pending.deinit(game.gpa);
for (pending.items) |*sent| {
defer game.runtime.release(sent.data.ref);
const list = switch (sent.to) {
.global => game.global(),
.object => |handle| if (handle.valid(game.objects)) game.onObject(handle.slot) else continue,
};
game.runner.deliverTo(list, sent);
}
}
fn ofScripts(context: *anyopaque) *Game {
return @ptrCast(@alignCast(context));
}
const vtable: engine_hooks.Scripts.VTable = .{
.call = hookCall,
.begin = begin,
.frame = frame,
.started = started,
.ended = ended,
.update = update,
.step = step,
.order_info = orderInfo,
.order_run = orderRun,
};
fn orderInfo(context: *anyopaque, order: openreliant.engine.game.ai.orders.Order) ?openreliant.engine.game.ai.orders.Info {
return ofScripts(context).runtime.custom_orders.info(order);
}
fn orderRun(context: *anyopaque, ctx: aigeneric.Context, index: u16, order: openreliant.engine.game.ai.orders.Order, role: openreliant.engine.game.ai.routines.Role) bool {
const game = ofScripts(context);
return game.runtime.custom_orders.run(game.runtime, ctx, index, order, role);
}
fn hookCall(context: *anyopaque, hook_call: *engine_hooks.Call) void {
const game = ofScripts(context);
switch (hook_call.hook) {
.object_added => {
const index = objectOf(hook_call);
game.objectAdded(index);
game.runner.callEach(game.global(), .on_object_added, .{ .object = .of(index) });
},
.object_removed => {
const index = objectOf(hook_call);
if (game.runtime.orders) |ctx| aigeneric.forgetCustom(ctx, index);
game.runner.callEach(game.global(), .on_object_removed, .{ .object = .of(index) });
game.objectRemoved(index);
},
.missile_added => game.missileAdded(missileOf(hook_call)),
.missile_removed => game.missileRemoved(missileOf(hook_call)),
else => {},
}
game.hooks.run(hook_call);
}
/// The missile of a `missile_added` or `missile_removed` call.
fn missileOf(hook_call: *engine_hooks.Call) u8 {
const fields: *const engine_hooks.Fields(.missile_added) = @ptrCast(@alignCast(hook_call.fields));
return fields.missile.record();
}
/// The object of an `object_added` or `object_removed` call.
fn objectOf(hook_call: *engine_hooks.Call) u16 {
const fields: *const engine_hooks.Fields(.object_added) = @ptrCast(@alignCast(hook_call.fields));
return fields.object.slot();
}
fn begin(context: *anyopaque, orders: aigeneric.Context, mission: engine_hooks.Mission, seed: u64) void {
const game = ofScripts(context);
game.stopObjectScripts();
game.stopMissionScripts();
game.runtime.reseed(seed);
game.runtime.orders = orders;
game.mission = .of(mission);
for (game.runtime.mods, 0..) |*mod, at| {
var listed = missionScripts(mod, mission.file) orelse continue;
game.startMissionScripts(@intCast(at), &listed) catch |err| log.warn("{s}: the scripts of {s} can't start: {s}", .{ mod.name, mission.file, @errorName(err) });
}
}
/// Starts the scripts of a mission that runs already, as the scripts are reloaded partway
/// through it: the mission's scripts, and the scripts manifests attach to each object in it,
/// as its start would have them (`begin`), but without `on_mission_start` or
/// `on_object_added`.
pub fn resumeMission(game: *Game, orders: aigeneric.Context, mission: engine_hooks.Mission, seed: u64) void {
begin(game, orders, mission, seed);
for (0..game.objects.slots.len) |index| {
if (world.inMission(game.objects, @intCast(index))) game.objectAdded(@intCast(index));
}
}
fn startMissionScripts(game: *Game, mod: u16, listed: *script.List) Allocator.Error!void {
try game.mission_mods.ensureUnusedCapacity(game.gpa, 1);
const context = try game.runtime.open(mod, .global, null);
game.mission_mods.appendAssumeCapacity(context);
while (listed.next()) |name| _ = try game.startScript(game.global(), context, name, true, null, false);
}
/// Keeps the world the frame has as what the scripts' orders run against, while a mission runs:
/// the copy `begin` kept holds pointers that can change between frames.
fn frame(context: *anyopaque, orders: aigeneric.Context) void {
const game = ofScripts(context);
if (game.runtime.orders != null) game.runtime.orders = orders;
}
fn started(context: *anyopaque, mission: engine_hooks.Mission) void {
const game = ofScripts(context);
game.runner.callEach(game.global(), .on_mission_start, .{ .mission = mission });
engine_hooks.tell(&game.scripts, .mission_started, mission);
}
fn ended(context: *anyopaque, outcome: engine_hooks.Outcome) void {
const game = ofScripts(context);
game.runner.callEach(game.global(), .on_mission_end, .{ .outcome = outcome });
engine_hooks.tell(&game.scripts, .mission_ended, outcome);
game.runtime.custom_orders.endMission(game.runtime);
game.stopObjectScripts();
game.stopMissionScripts();
game.runtime.orders = null;
game.mission = null;
}
fn update(context: *anyopaque, seconds: f32) void {
const game = ofScripts(context);
game.deliver();
game.runner.advance(seconds);
game.runner.callAll(.on_update, .{ .seconds = seconds });
}
fn step(context: *anyopaque) void {
ofScripts(context).runner.callAll(.on_step, .{});
}
};
/// The `Global` scripts `mod` lists, in order.
fn globalScripts(mod: *const Mod) script.List {
return .of(mod.manifest.value(script.section, script.Kind.global.key()) orelse "");
}
/// The scripts `mod` runs on each turret.
fn turretScripts(mod: *const Mod) script.List {
return .of(mod.manifest.value(script.section, script.Kind.turret.key()) orelse "");
}
/// The scripts `mod` runs on each missile in flight.
fn missileScripts(mod: *const Mod) script.List {
return .of(mod.manifest.value(script.section, script.Kind.missile.key()) orelse "");
}
/// Whether `mod`'s manifest attaches scripts to objects by their class or type, or to their turrets.
fn attachesScripts(mod: *const Mod) bool {
var keys = mod.manifest.keys(script.section);
while (keys.next()) |key| {
const attachment = script.Attachment.parse(key, mod.name) orelse continue;
switch (attachment) {
.kind => |kind| if (kind.class() != null or kind == .turret) return true,
.object_type => return true,
}
}
return false;
}
/// The scripts `mod` lists under `[Missions]` for the mission file `file`, if any.
fn missionScripts(mod: *const Mod, file: []const u8) ?script.List {
var keys = mod.manifest.keys(script.missions_section);
while (keys.next()) |key| {
if (!std.ascii.eqlIgnoreCase(key, file)) continue;
return .of(mod.manifest.value(script.missions_section, key) orelse "");
}
return null;
}
/// `object:add_script(name, data)`.
pub fn addScript(call: Call, object: Object, name: []const u8, payload: ?data.Data) bool {
// Luau's errors skip Zig's defers, so the payload is let go by hand before each.
const drop = struct {
fn drop(scripts: *Runtime, given: ?data.Data) void {
if (given) |held| scripts.release(held.ref);
}
}.drop;
const scripts = call.runtime();
if (call.context.family != .global) {
drop(scripts, payload);
call.raise("only global scripts can add scripts", .{});
}
const game = scripts.game orelse {
drop(scripts, payload);
call.raise("can only be used while a game runs", .{});
};
const mod = call.context.modOf();
const file = script.find(mod, name) orelse {
drop(scripts, payload);
call.raise("mod {s} has no script {s}", .{ mod.name, name });
};
const index = object.slot();
const list = game.onObject(index);
for (list.items) |held| {
if (held.stopped or held.context.mod != call.context.mod) continue;
if (std.ascii.eqlIgnoreCase(held.name, file)) {
drop(scripts, payload);
return false;
}
}
const context = for (list.items) |held| {
if (!held.stopped and held.context.mod == call.context.mod) break held.context;
} else scripts.open(call.context.mod, .object, .{ .object = .of(game.objects, index) }) catch {
drop(scripts, payload);
call.raise("out of memory", .{});
};
const started = game.startScript(list, context, file, false, payload, false) catch {
game.runner.closeUnused(list, context);
call.raise("out of memory", .{});
};
if (started == null) game.runner.closeUnused(list, context);
return started != null;
}
/// `object:remove_script(name)`.
pub fn removeScript(call: Call, object: Object, name: []const u8) bool {
const game = Game.of(call);
if (call.context.family != .global) call.raise("only global scripts can remove scripts", .{});
const list = game.onObject(object.slot());
for (list.items, 0..) |held, at| {
if (held.stopped or held.context.mod != call.context.mod) continue;
if (!script.isNamed(held.name, name)) continue;
game.runner.stopScript(list, at);
return true;
}
return false;
}
/// `object:send_event(name, data)`.
pub fn sendEvent(call: Call, object: Object, name: []const u8, payload: data.Data) void {
const game = call.runtime().game orelse {
call.runtime().release(payload.ref);
call.raise("events can only be sent while a game runs", .{});
};
game.runner.events.send(call, .{ .object = .of(game.objects, object.slot()) }, name, payload);
}
/// `core.send_global_event(name, data)`.
pub fn sendGlobalEvent(call: Call, name: []const u8, payload: data.Data) void {
if (call.runtime().presentation) |shown| return shown.sendToGame(call, name, payload);
const game = call.runtime().game orelse {
call.runtime().release(payload.ref);
call.raise("events can only be sent while a game runs", .{});
};
game.runner.events.send(call, .global, name, payload);
}
/// A game with the mods `made`, each a folder of files, over a mission that holds the player's
/// Predator and a Sabre.
const Fixture = struct {
tmp: std.testing.TmpDir,
mods: mods.Mods,
arena: std.heap.ArenaAllocator,
held: records.Records,
mission: gameobj.testing.Mission,
game: *Game,
sabre: u16,
const collision = openreliant.engine.game.collision;
fn init(fixture: *Fixture, made: []const struct { []const u8, []const struct { []const u8, []const u8 } }) !void {
return fixture.initShared(made, .{});
}
/// `init`, with what the mods share; where it has a registry of options, the load scripts run
/// first, to declare the pages the others read.
fn initShared(fixture: *Fixture, made: []const struct { []const u8, []const struct { []const u8, []const u8 } }, shared: runtime.Shared) !void {
const gpa = std.testing.allocator;
const io = std.testing.io;
fixture.tmp = std.testing.tmpDir(.{ .iterate = true });
errdefer fixture.tmp.cleanup();
try load.testing.makeMods(io, fixture.tmp.dir, made);
fixture.mods = try .open(gpa, io, fixture.tmp.dir, null);
errdefer fixture.mods.close(gpa);
fixture.arena = .init(gpa);
errdefer fixture.arena.deinit();
fixture.held = try load.testing.records3(fixture.arena.allocator());
try fixture.mission.init(gpa);
errdefer fixture.mission.deinit();
_ = try fixture.mission.add(.of(.predator), @splat(0));
if (shared.option_pages != null) try load.run(gpa, io, fixture.mods.list, &fixture.held, "0.7.0", shared);
fixture.game = (try Game.start(gpa, io, fixture.mods.list, &fixture.held, "0.7.0", fixture.mission.objects, shared, false)).?;
fixture.sabre = try fixture.mission.add(.of(.sabre), .{ 0, 0, 1000 });
}
fn deinit(fixture: *Fixture) void {
fixture.game.stop();
fixture.mission.deinit();
fixture.arena.deinit();
fixture.mods.close(std.testing.allocator);
fixture.tmp.cleanup();
}
/// What the game's difficulty makes of `value`, dealt to the object in slot `index` by a
/// missile, through the hooks.
fn scaled(fixture: *Fixture, index: u16, value: f32) f32 {
return collision.byDifficulty(fixture.mission.world(), index, .missile, value);
}
/// Begins mission 5, as the engine does before its ships are made.
fn begin(fixture: *Fixture) void {
fixture.game.scripts.begin(fixture.mission.orders(), .{ .number = 5, .file = "mission5.dte" }, 1);
}
};
test "custom orders use qualified names, lifecycle callbacks and the engine stack" {
var fixture: Fixture = undefined;
try fixture.init(&.{
.{
"a",
&.{
.{ "mod.ini", "[Scripts]\nGlobal=a.luau\n" },
.{
"a.luau",
\\local orders = require("openreliant.orders")
\\local world = require("openreliant.world")
\\local started, updated, exited = 0, 0, 0
\\local own
\\own = orders.register("hold", {
\\ priority = 2, flags = {avoidance = true},
\\ init = function(ship, target) started += 1; assert(target == world.objects()[1]) end,
\\ update = function(ship, target, seconds)
\\ updated += 1; ship.throttle = 0.25
\\ assert(ship.order == "a:hold" and orders.stack(ship)[1].order == own)
\\ return updated < 2
\\ end,
\\ exit = function(ship) exited += 1; ship.throttle = 0.5 end,
\\})
\\assert(own == "a:hold")
\\assert(not pcall(function() orders.register("hold", {update = function() end}) end))
\\return { engine_handlers = {on_mission_start = function()
\\ local ships = world.objects(); local ship = ships[2]
\\ assert(orders.info(own).priority == 2 and orders.info(own).flags.avoidance)
\\ assert(orders.info("b:hold") ~= nil and orders.info("hold").name == own)
\\ assert(not ships[1]:give_order(own))
\\ assert(ship:give_order("do_nothing") and ship:give_order(own, ships[1]))
\\end, on_update = function()
\\ assert(started == 1 and updated == 2 and exited == 1)
\\end} }
},
},
},
.{ "b", &.{ .{ "mod.ini", "[Scripts]\nGlobal=b.luau\n" }, .{ "b.luau", "assert(require('openreliant.orders').register('hold', {update = function() end}) == 'b:hold')" } } },
});
defer fixture.deinit();
fixture.begin();
fixture.game.scripts.started(.{ .number = 5, .file = "mission5.dte" });
const ctx = fixture.mission.orders();
aigeneric.objectOrders(ctx, fixture.sabre);
try std.testing.expectEqual(0.25, fixture.mission.slot(fixture.sabre).object.throttle);
try std.testing.expectError(error.OrderConflict, aigeneric.push(ctx, fixture.sabre, .fly_aimlessly, .none));
aigeneric.objectOrders(ctx, fixture.sabre);
try std.testing.expectEqual(0.5, fixture.mission.slot(fixture.sabre).object.throttle);
try std.testing.expect(fixture.game.runtime.custom_orders.entries.items[1].enabled);
try std.testing.expectEqual(.do_nothing, fixture.mission.slot(fixture.sabre).current().?.order);
fixture.game.scripts.update(0.04);
try std.testing.expect(fixture.game.runtime.custom_orders.entries.items[0].enabled);
}
test "a script launches a ship from a carrier's gate" {
var fixture: Fixture = undefined;
try fixture.init(&.{.{
"a",
&.{
.{ "mod.ini", "[Scripts]\nGlobal=a.luau\n" },
.{
"a.luau",
\\local world = require("openreliant.world")
\\return { engine_handlers = {on_mission_start = function()
\\ local carrier, ship = world.objects()[1], world.objects()[2]
\\ assert(not ship:start_launch())
\\ assert(not pcall(ship.give_order, ship, "launch", nil, 1))
\\ assert(not pcall(ship.give_order, ship, "launch", carrier, 256))
\\ assert(ship:give_order("launch", carrier, 1))
\\ assert(ship:start_launch())
\\end} }
},
},
}});
defer fixture.deinit();
fixture.begin();
fixture.game.scripts.started(.{ .number = 5, .file = "mission5.dte" });
const launch = fixture.mission.slot(fixture.sabre).firstOrder(.launch).?;
try std.testing.expectEqual(1, launch.target.part().?);
try std.testing.expect(launch.data.launch.go);
}
test "custom order failures disable callbacks and context closure removes stacked orders" {
var fixture: Fixture = undefined;
try fixture.init(&.{.{
"a",
&.{
.{ "mod.ini", "[Scripts]\nGlobal=a.luau\n" },
.{
"a.luau",
\\local orders = require("openreliant.orders")
\\local world = require("openreliant.world")
\\orders.register("broken", {update = function(ship) ship:give_order("do_nothing") end})
\\orders.register("hold", {priority = 3, update = function() end, exit = function(ship) ship.throttle = 0.75 end})
\\return {engine_handlers = {on_mission_start = function()
\\ local ship = world.objects()[2]
\\ assert(ship:give_order("do_nothing") and ship:give_order("a:broken"))
\\end}}
},
},
}});
defer fixture.deinit();
fixture.begin();
fixture.game.scripts.started(.{ .number = 5, .file = "mission5.dte" });
const ctx = fixture.mission.orders();
aigeneric.objectOrders(ctx, fixture.sabre);
try std.testing.expect(!fixture.game.runtime.custom_orders.entries.items[0].enabled);
try std.testing.expectEqual(.do_nothing, fixture.mission.slot(fixture.sabre).current().?.order);
const hold = fixture.game.runtime.custom_orders.find("a:hold").?;
try std.testing.expect(aigeneric.give(ctx, fixture.sabre, hold, .none));
aigeneric.objectOrders(ctx, fixture.sabre);
fixture.game.runtime.close(fixture.game.runtime.custom_orders.entries.items[1].context);
try std.testing.expectEqual(0.75, fixture.mission.slot(fixture.sabre).object.throttle);
try std.testing.expectEqual(.do_nothing, fixture.mission.slot(fixture.sabre).current().?.order);
try std.testing.expectEqual(null, fixture.game.runtime.custom_orders.find("a:hold"));
}
test "one-shot custom orders skip init and exit and mission end removes custom stacks" {
var fixture: Fixture = undefined;
try fixture.init(&.{.{
"a",
&.{
.{ "mod.ini", "[Scripts]\nGlobal=a.luau\n" },
.{
"a.luau",
\\local orders = require("openreliant.orders")
\\local world = require("openreliant.world")
\\orders.register("hold", {update = function() end, exit = function(ship) ship.throttle = 0.75 end})
\\orders.register("once", {flags = {one_shot = true, players = true},
\\ init = function() error("must not init") end,
\\ update = function(ship) ship.throttle = 0.5 end,
\\ exit = function() error("must not exit") end})
\\return {engine_handlers = {on_mission_start = function()
\\ local ship = world.objects()[2]
\\ assert(ship:give_order("do_nothing") and ship:give_order("a:hold") and ship:give_order("a:once"))
\\end}}
},
},
}});
defer fixture.deinit();
fixture.begin();
fixture.game.scripts.started(.{ .number = 5, .file = "mission5.dte" });
aigeneric.objectOrders(fixture.mission.orders(), fixture.sabre);
const hold = fixture.game.runtime.custom_orders.find("a:hold").?;
try std.testing.expectEqual(hold, fixture.mission.slot(fixture.sabre).current().?.order);
try std.testing.expectEqual(0.5, fixture.mission.slot(fixture.sabre).object.throttle);
fixture.game.scripts.ended(.{ .ending = .playing, .rating = .success });
try std.testing.expectEqual(0.75, fixture.mission.slot(fixture.sabre).object.throttle);
try std.testing.expectEqual(.do_nothing, fixture.mission.slot(fixture.sabre).current().?.order);
// Global registrations remain available in the next mission, with the same qualified names.
try std.testing.expectEqual(hold, fixture.game.runtime.custom_orders.find("a:hold").?);
}
test "mission order registrations close and register again without stale numeric IDs" {
var fixture: Fixture = undefined;
try fixture.init(&.{.{ "a", &.{
.{ "mod.ini", "[Missions]\nmission5.dte=a.luau\n" },
.{ "a.luau", "require('openreliant.orders').register('hold', {update = function() end})" },
} }});
defer fixture.deinit();
fixture.begin();
const old = fixture.game.runtime.custom_orders.find("a:hold").?;
try std.testing.expect(aigeneric.give(fixture.mission.orders(), fixture.sabre, old, .none));
aigeneric.objectOrders(fixture.mission.orders(), fixture.sabre);
// Starting the context again models the shutdown/restart path used on reload.
fixture.begin();
const new = fixture.game.runtime.custom_orders.find("a:hold").?;
try std.testing.expect(old != new);
try std.testing.expectEqual(0, fixture.mission.slot(fixture.sabre).object.order_count);
try std.testing.expect(aigeneric.give(fixture.mission.orders(), fixture.sabre, new, .none));
}
test "the custom order example runs and completes its throttle pulse" {
var fixture: Fixture = undefined;
try fixture.init(&.{.{ "custom-order", &.{
.{ "mod.ini", @embedFile("custom-order/mod.ini") },
.{ "pulse.luau", @embedFile("custom-order/pulse.luau") },
} }});
defer fixture.deinit();
fixture.begin();
fixture.game.scripts.started(.{ .number = 5, .file = "mission5.dte" });
const pulse = fixture.game.runtime.custom_orders.find("custom-order:pulse").?;
try std.testing.expectEqual(pulse, fixture.mission.slot(fixture.sabre).current().?.order);
fixture.mission.clock.frame_duration = 100;
aigeneric.objectOrders(fixture.mission.orders(), fixture.sabre);
try std.testing.expectEqual(0.25, fixture.mission.slot(fixture.sabre).object.throttle);
aigeneric.objectOrders(fixture.mission.orders(), fixture.sabre);
try std.testing.expectEqual(0, fixture.mission.slot(fixture.sabre).object.order_count);
try std.testing.expectEqual(0, fixture.mission.slot(fixture.sabre).object.throttle);
}
test "handlers run newest mod first, in the order each mod added them" {
var fixture: Fixture = undefined;
try fixture.init(&.{
.{ "a", &.{
.{ "mod.ini", "[Scripts]\nGlobal=a.luau\n" },
.{ "a.luau", "require('openreliant.hooks').add('damage_by_difficulty', function(e) e.value = e.value * 10 + 1 end)" },
} },
.{
"b",
&.{
.{ "mod.ini", "[Scripts]\nGlobal=b.luau\n" },
.{
"b.luau",
\\local hooks = require("openreliant.hooks")
\\hooks.add("damage_by_difficulty", function(e) e.value = e.value * 10 + 2 end)
\\hooks.add("damage_by_difficulty", function(e) e.value = e.value * 10 + 3 end)
\\hooks.after("damage_by_difficulty", function(e) e.result += 1000 end, { type = "sabre" })
\\-- A hit by the player on a Sabre does nothing.
\\hooks.add("object_damage", function(e)
\\ if e.attacker.is_player and e.object.type == "sabre" then return false end
\\end)
},
},
},
});
defer fixture.deinit();
// Mod b's two, in order, then mod a's; the handler after the function is only for the Sabre.
try std.testing.expectEqual(1231, fixture.scaled(fixture.sabre, 0));
// The player's ship takes half at medium difficulty.
try std.testing.expectEqual(115.5, fixture.scaled(0, 0));
const shields = &fixture.mission.objects.slots[fixture.sabre].object.shields;
shields.* = .all(100);
Fixture.collision.damage(fixture.mission.world(), fixture.sabre, .fore, 50, 1, 0, .bullet);
try std.testing.expectEqual(100, shields.get(.fore));
}
test "a script stops and retargets the orders given, and keeps one from ending" {
var fixture: Fixture = undefined;
try fixture.init(&.{.{
"a",
&.{
.{ "mod.ini", "[Scripts]\nGlobal=a.luau\n" },
.{
"a.luau",
\\local hooks = require("openreliant.hooks")
\\local orders = require("openreliant.orders")
\\hooks.add("order_push", function(e)
\\ -- No ship runs away, and an order aimed at the player is aimed at the ship itself.
\\ if e.order == "run_away" then return false end
\\ if e.target.object ~= nil and e.target.object.is_player then
\\ assert(e.target.component == nil and e.target.flight_group == nil)
\\ e.target = { object = e.object }
\\ end
\\end)
\\hooks.after("order_push", function(e) assert(e.result == "taken" or e.result == "refused") end)
\\-- An escort never ends.
\\hooks.add("order_pop", function(e)
\\ if orders.stack(e.object)[1].order == "escort" then return false end
\\end)
\\hooks.add("missile_launch", function(e) assert(e.target.object == nil) end)
},
},
}});
defer fixture.deinit();
const ctx = fixture.mission.orders();
const slot = fixture.mission.slot(fixture.sabre);
const pushed_before = slot.stack().len;
// Stopped, the order isn't pushed.
try std.testing.expect(!aigeneric.give(ctx, fixture.sabre, .run_away, .at(0, null)));
try std.testing.expectEqual(pushed_before, slot.stack().len);
// Aimed at the player, it is aimed at the Sabre itself.
try std.testing.expect(aigeneric.give(ctx, fixture.sabre, .escort, .at(0, null)));
try std.testing.expectEqual(aigeneric.Target.at(fixture.sabre, null), slot.current().?.target);
// A target the scripts don't change goes through as it was, a squad's too.
try std.testing.expect(aigeneric.give(ctx, fixture.sabre, .fly_aimlessly, .group(.squad, 3)));
try std.testing.expectEqual(aigeneric.Target.group(.squad, 3), slot.current().?.target);
// The order on top ends, and the escort under it doesn't.
try std.testing.expect(aigeneric.pop(ctx, fixture.sabre));
try std.testing.expect(!aigeneric.pop(ctx, fixture.sabre));
try std.testing.expectEqual(openreliant.engine.game.ai.orders.Order.escort, slot.current().?.order);
}
test "a script stops or changes the radio's lines" {
const radio_module = openreliant.engine.game.radio;
const hog_snd = openreliant.engine.game.hog_snd;
var fixture: Fixture = undefined;
try fixture.init(&.{.{
"a",
&.{
.{ "mod.ini", "[Scripts]\nGlobal=a.luau\n" },
.{
"a.luau",
\\local hooks = require("openreliant.hooks")
\\hooks.add("radio_say", function(e)
\\ if e.speech:find("ms_hudtr", 1, true) then return false end
\\ if e.speech == "plck_001.ut" then e.speech = "moolnd_001.ut" end
\\end)
},
},
}});
defer fixture.deinit();
const gpa = std.testing.allocator;
const io = std.testing.io;
var archives: radio_module.testing.Archives = undefined;
try archives.init(gpa, io, &.{}, &.{});
defer archives.deinit();
var speaker: hog_snd.testing.Speaker = undefined;
try speaker.init(2, null);
defer speaker.deinit();
var radio = archives.radio(gpa, io);
defer radio.deinit();
const ctx: radio_module.Context = .{ .sounds = &speaker.asked, .windows = null, .all = fixture.mission.objects, .frame_start = 0 };
var line: radio_module.Line = .{ .film = "pilots\\static.fm8", .speech = "ms_speech\\ms_hudtr_001.ut", .name = null, .object = radio_module.nobody };
// The simulator's line is stopped: nothing waits.
radio.say(ctx, line, .queued);
try std.testing.expectEqual(0, radio.count);
// Another is said in place of the one asked for, and the rest as they are.
line.speech = "plck_001.ut";
radio.say(ctx, line, .queued);
line.speech = "mphud_001.ut";
radio.say(ctx, line, .queued);
try std.testing.expectEqual(2, radio.count);
try std.testing.expectEqualStrings("moolnd_001.ut", radio.queue[0].speech.slice());
try std.testing.expectEqualStrings("pilots\\static.fm8", radio.queue[0].film.slice());
try std.testing.expectEqualStrings("mphud_001.ut", radio.queue[1].speech.slice());
}
test "a script says lines on the radio, as the comms commands do" {
const radio_module = openreliant.engine.game.radio;
const hog_snd = openreliant.engine.game.hog_snd;
var fixture: Fixture = undefined;
try fixture.init(&.{.{
"a",
&.{
.{ "mod.ini", "[Scripts]\nGlobal=a.luau\n" },
.{
"a.luau",
\\local radio = require("openreliant.radio")
\\local world = require("openreliant.world")
\\-- Between missions, nothing is said.
\\assert(not radio.say_pilot("diceman", "ms_dice22_001.ut"))
\\return {
\\ engine_handlers = {
\\ on_mission_start = function()
\\ assert(radio.say_pilot("diceman", "ms_dice22_001.ut", { mode = "queued" }))
\\ assert(radio.say(world.player, "ms_dice22_002.ut", { mode = "queued", face = "laughing", once = true }))
\\ end,
\\ },
\\}
},
},
}});
defer fixture.deinit();
const gpa = std.testing.allocator;
const io = std.testing.io;
var archives: radio_module.testing.Archives = undefined;
try archives.init(gpa, io, &.{}, &.{});
defer archives.deinit();
var speaker: hog_snd.testing.Speaker = undefined;
try speaker.init(2, null);
defer speaker.deinit();
var radio = archives.radio(gpa, io);
defer radio.deinit();
var heard = fixture.mission.world();
heard.radio = &radio;
speaker.hear(&heard);
fixture.game.scripts.begin(.of(heard), .{ .number = 22, .file = "mission22.dte" }, 1);
fixture.game.scripts.started(.{ .number = 22, .file = "mission22.dte" });