nightshade-api 0.48.0

Procedural high level API for the nightshade game engine
Documentation
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
//! Rhai scripting as an api-layer binding to the command and event surface.
//!
//! The runtime lives here, next to the [`Command`](crate::Command) enum and the
//! other language bindings, not in the engine. A script produces typed `Command`
//! values, read straight from the rhai value with no json step. Each tick the
//! runner reads the engine's frozen events, runs every enabled script, and
//! submits the commands they produced as one deferred batch.
//!
//! A script can ask for a command's result back: `commands.tag("id")` after a
//! command marks it, and next tick the script reads the reply (a spawned entity,
//! a raycast hit, a query value) from the `replies` map. This keeps the boundary
//! pure data, results flow back as values the script reads, never a live world.
//!
//! The driver, an app or the editor worker, owns the [`ScriptRuntime`] and calls
//! [`run_scripts`] once a tick after the event swap.

use std::collections::{HashMap, HashSet};

use rhai::{AST, Array, Dynamic, Engine, Map, Scope};

use nightshade::ecs::event::{Event, events};
use nightshade::ecs::script::components::ScriptSource;
use nightshade::ecs::world::SCRIPT;
use nightshade::prelude::{Entity, KeyCode, MouseState, Vec3, World, tracing};

use crate::command::{Command, CommandReply, submit_commands};

/// The reserved keys a `commands.tag(id)` wrapper uses, so the collector can tell
/// a tagged request from a plain command map. A command variant is PascalCase,
/// so these never collide.
const TAG_ID_KEY: &str = "$id";
const TAG_COMMAND_KEY: &str = "$cmd";

/// The write policy gating which commands a script may produce. The default
/// allows every command. Restrict it to a named subset to sandbox an untrusted
/// or agent-authored script to part of the command surface, enforced at the
/// command boundary where the script's whole effect already passes.
#[derive(Clone, Default)]
pub enum CommandPolicy {
    #[default]
    AllowAll,
    Allow(HashSet<String>),
}

impl CommandPolicy {
    fn allows(&self, name: &str) -> bool {
        match self {
            CommandPolicy::AllowAll => true,
            CommandPolicy::Allow(allowed) => allowed.contains(name),
        }
    }
}

/// The scripting runtime: one rhai engine, a compiled-AST cache keyed by source
/// so identical scripts compile once, a persistent scope per entity so script
/// state survives across ticks, and a write policy bounding the command surface.
pub struct ScriptRuntime {
    pub enabled: bool,
    pub policy: CommandPolicy,
    engine: Engine,
    compiled: HashMap<u64, AST>,
    scopes: HashMap<Entity, Scope<'static>>,
    global_scopes: HashMap<String, Scope<'static>>,
    started_globals: HashSet<String>,
    started_entities: HashSet<Entity>,
    next_replies: Map,
    assets: HashMap<String, Vec<u8>>,
    random_state: u64,
}

/// The starting seed for a runtime's random sequence, reset on
/// [`script_runtime_reset`] so reloading a script replays the same rolls.
const RANDOM_SEED: u64 = 0x853c_49e6_748f_ea9b;

/// Builds the scripting engine with the playground's limits and the full command
/// vocabulary registered. Shared so [`script_check`] validates against the exact
/// engine the runtime runs, not a bare default with a tighter expression depth.
fn new_engine() -> Engine {
    let mut engine = Engine::new();
    engine.set_max_operations(200_000);
    engine.set_max_call_levels(64);
    engine.set_max_string_size(8 * 1024);
    engine.set_max_array_size(4096);
    engine.set_max_expr_depths(0, 0);
    register_api(&mut engine);
    engine
}

impl Default for ScriptRuntime {
    fn default() -> Self {
        let engine = new_engine();
        Self {
            enabled: false,
            policy: CommandPolicy::AllowAll,
            engine,
            compiled: HashMap::new(),
            scopes: HashMap::new(),
            global_scopes: HashMap::new(),
            started_globals: HashSet::new(),
            started_entities: HashSet::new(),
            next_replies: Map::new(),
            assets: HashMap::new(),
            random_state: RANDOM_SEED,
        }
    }
}

/// What one tick of scripting produced: the commands submitted this tick, so a
/// tool can show the traffic, and any warnings, so a driver can surface compile
/// errors, `on_tick` failures, and dropped or blocked commands to the user.
#[derive(Default)]
pub struct ScriptReport {
    pub commands: Vec<Command>,
    pub errors: Vec<String>,
}

thread_local! {
    /// Per-tick scratch register for the random generator. The canonical seed
    /// lives in [`ScriptRuntime::random_state`]; [`run_scripts`] loads it here
    /// before a tick and reads it back after, so the registered `random` helpers
    /// (which the engine builds once and cannot reach the runtime) advance the
    /// runtime's own state rather than a hidden global.
    static SCRIPT_RNG: std::cell::Cell<u64> = const { std::cell::Cell::new(RANDOM_SEED) };
}

/// The next pseudo-random float in `[0, 1)` from the script runtime's xorshift
/// generator, so scripts get randomness without hand-rolling a generator.
fn next_unit_random() -> f64 {
    SCRIPT_RNG.with(|cell| {
        let mut state = cell.get();
        state ^= state << 13;
        state ^= state >> 7;
        state ^= state << 17;
        cell.set(state);
        ((state >> 11) as f64) / ((1u64 << 53) as f64)
    })
}

/// Registers the read-only helpers a script always has, then every command as a
/// method on the `commands` array. A script targets the whole [`Command`]
/// surface two equivalent ways: a terse method, `commands.spawn_cube([x, y,
/// z])`, or the map shape, `commands.push(#{ SpawnCube: #{ position: [...] }
/// })`. `entity_ref` turns a script's packed entity handle into a
/// `Ref::Existing` so a command can name a live entity by id.
fn register_api(engine: &mut Engine) {
    engine.register_fn("log", |message: &str| tracing::info!("[script] {message}"));
    // Randomness without a hand-rolled generator: `random()` in [0, 1),
    // `random_range(lo, hi)` for a float, `random_int(lo, hi)` inclusive.
    engine.register_fn("random", next_unit_random);
    engine.register_fn("random_range", |low: f64, high: f64| {
        low + next_unit_random() * (high - low)
    });
    engine.register_fn("random_int", |low: i64, high: i64| {
        if high <= low {
            low
        } else {
            low + (next_unit_random() * ((high - low + 1) as f64)) as i64
        }
    });
    register_mixed_number_ops(engine);
    register_color_helpers(engine);
    engine.register_fn("entity_ref", |packed: i64| {
        let entity = script_to_entity(packed);
        let mut map = Map::new();
        map.insert("Existing".into(), Dynamic::from(entity.id as i64));
        Dynamic::from_map(map)
    });
    // References the entity made by an earlier command in this frame's batch by
    // its position, so `commands.set_color(result(0), ...)` configures the
    // entity command 0 spawned. Sugar for the `#{ Result: index }` shape.
    engine.register_fn("result", |index: i64| {
        let mut map = Map::new();
        map.insert("Result".into(), Dynamic::from(index));
        Dynamic::from_map(map)
    });
    // References whatever the most recent command produced, for the common
    // spawn-then-configure pattern inside a loop: `commands.spawn_cube(p);
    // commands.set_color(commands.last(), c)`.
    engine.register_fn("last", |commands: &mut Array| {
        let index = commands.len().saturating_sub(1) as i64;
        let mut map = Map::new();
        map.insert("Result".into(), Dynamic::from(index));
        Dynamic::from_map(map)
    });
    // Marks the command just pushed so its result is reported back next frame
    // under `id` in `replies`. This is how a script reads a query (a raycast hit,
    // a spawned entity, a bounds box): `commands.raycast(...); commands.tag("hit")`
    // this frame, then `replies.hit` next frame.
    engine.register_fn("tag", |commands: &mut Array, id: rhai::ImmutableString| {
        if let Some(last) = commands.last_mut() {
            let command = std::mem::take(last);
            let mut request = Map::new();
            request.insert(TAG_ID_KEY.into(), Dynamic::from(id));
            request.insert(TAG_COMMAND_KEY.into(), command);
            *last = Dynamic::from_map(request);
        }
    });
    crate::command::register_command_methods(engine);
}

/// Registers mixed integer and float arithmetic and comparison operators. rhai
/// has no built-in operator for an integer and a float together, so a loop index
/// times a float, or a comparison between the two, would need `.to_float()` on
/// every term. These overloads let a script write `index * 1.5` and `time < 2`
/// directly. Same-type arithmetic is untouched, so integer division stays integer.
fn register_mixed_number_ops(engine: &mut Engine) {
    engine.register_fn("+", |a: i64, b: f64| a as f64 + b);
    engine.register_fn("+", |a: f64, b: i64| a + b as f64);
    engine.register_fn("-", |a: i64, b: f64| a as f64 - b);
    engine.register_fn("-", |a: f64, b: i64| a - b as f64);
    engine.register_fn("*", |a: i64, b: f64| a as f64 * b);
    engine.register_fn("*", |a: f64, b: i64| a * b as f64);
    engine.register_fn("/", |a: i64, b: f64| a as f64 / b);
    engine.register_fn("/", |a: f64, b: i64| a / b as f64);
    engine.register_fn("%", |a: i64, b: f64| a as f64 % b);
    engine.register_fn("%", |a: f64, b: i64| a % b as f64);
    engine.register_fn("<", |a: i64, b: f64| (a as f64) < b);
    engine.register_fn("<", |a: f64, b: i64| a < b as f64);
    engine.register_fn(">", |a: i64, b: f64| a as f64 > b);
    engine.register_fn(">", |a: f64, b: i64| a > b as f64);
    engine.register_fn("<=", |a: i64, b: f64| a as f64 <= b);
    engine.register_fn("<=", |a: f64, b: i64| a <= b as f64);
    engine.register_fn(">=", |a: i64, b: f64| a as f64 >= b);
    engine.register_fn(">=", |a: f64, b: i64| a >= b as f64);
}

/// Registers `rgb`, `rgba`, and `hsv`, which build the `[r, g, b, a]` color array
/// commands take, so a script asks for a color by intent instead of writing the
/// channels out, and gets a hue gradient from `hsv` without hand-rolling the math.
fn register_color_helpers(engine: &mut Engine) {
    engine.register_fn("rgb", |r: f64, g: f64, b: f64| -> Array {
        vec![
            Dynamic::from(r),
            Dynamic::from(g),
            Dynamic::from(b),
            Dynamic::from(1.0_f64),
        ]
    });
    engine.register_fn("rgba", |r: f64, g: f64, b: f64, a: f64| -> Array {
        vec![
            Dynamic::from(r),
            Dynamic::from(g),
            Dynamic::from(b),
            Dynamic::from(a),
        ]
    });
    engine.register_fn("hsv", |h: f64, s: f64, v: f64| -> Array {
        let (r, g, b) = hsv_to_rgb(h, s, v);
        vec![
            Dynamic::from(r),
            Dynamic::from(g),
            Dynamic::from(b),
            Dynamic::from(1.0_f64),
        ]
    });
}

/// Converts hue, saturation, value (each in `0..=1`, hue wrapping) to red, green,
/// blue. The standard piecewise conversion, used by the `hsv` color helper.
fn hsv_to_rgb(hue: f64, saturation: f64, value: f64) -> (f64, f64, f64) {
    let sector = hue.rem_euclid(1.0) * 6.0;
    let chroma = value * saturation;
    let secondary = chroma * (1.0 - (sector % 2.0 - 1.0).abs());
    let base = value - chroma;
    let (red, green, blue) = match sector as i64 {
        0 => (chroma, secondary, 0.0),
        1 => (secondary, chroma, 0.0),
        2 => (0.0, chroma, secondary),
        3 => (0.0, secondary, chroma),
        4 => (secondary, 0.0, chroma),
        _ => (chroma, 0.0, secondary),
    };
    (red + base, green + base, blue + base)
}

/// True if the script defines a zero-argument function with this name, so a
/// lifecycle hook is only called when the script actually has it.
fn ast_defines_hook(ast: &AST, name: &str) -> bool {
    ast.iter_functions()
        .any(|function| function.name == name && function.params.is_empty())
}

/// Turns a command's reply into a rhai value a script can read out of `replies`.
/// Entities become the packed handle `entity_ref` accepts, scalars become their
/// rhai counterparts, vectors and lists become arrays, and a json result becomes
/// the equivalent rhai map or array.
fn reply_to_dynamic(reply: &CommandReply) -> Dynamic {
    match reply {
        CommandReply::None => Dynamic::UNIT,
        CommandReply::Entity(entity) => Dynamic::from(entity_to_script(*entity)),
        CommandReply::Bool(value) => Dynamic::from(*value),
        CommandReply::Float(value) => Dynamic::from(*value as f64),
        CommandReply::Int(value) => Dynamic::from(*value),
        CommandReply::Text(value) => Dynamic::from(value.clone()),
        CommandReply::Vector(value) => {
            Dynamic::from_array(array3(Vec3::new(value[0], value[1], value[2])))
        }
        CommandReply::Entities(entities) => Dynamic::from_array(
            entities
                .iter()
                .map(|entity| Dynamic::from(entity_to_script(*entity)))
                .collect(),
        ),
        CommandReply::Strings(strings) => Dynamic::from_array(
            strings
                .iter()
                .map(|value| Dynamic::from(value.clone()))
                .collect(),
        ),
        CommandReply::Bytes(bytes) => Dynamic::from_blob(bytes.clone()),
        CommandReply::Json(value) => rhai::serde::to_dynamic(value).unwrap_or(Dynamic::UNIT),
        CommandReply::Error(message) => {
            let mut map = Map::new();
            map.insert("error".into(), Dynamic::from(message.clone()));
            Dynamic::from_map(map)
        }
    }
}

/// Packs an entity into the `i64` a script holds. Generational, so a stale id
/// resolves to nothing rather than the new occupant of a reused slot.
fn entity_to_script(entity: Entity) -> i64 {
    (((entity.id as u64) << 32) | entity.generation as u64) as i64
}

/// Unpacks the `i64` a script passed back into an entity.
fn script_to_entity(value: i64) -> Entity {
    let bits = value as u64;
    Entity {
        id: (bits >> 32) as u32,
        generation: bits as u32,
    }
}

fn hash_source(source: &str) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    source.hash(&mut hasher);
    hasher.finish()
}

fn compiled_ast<'a>(
    runtime: &'a mut ScriptRuntime,
    source: &str,
    errors: &mut Vec<String>,
) -> Option<&'a AST> {
    let key = hash_source(source);
    if !runtime.compiled.contains_key(&key) {
        match runtime.engine.compile(source) {
            Ok(ast) => {
                runtime.compiled.insert(key, ast);
            }
            Err(error) => {
                tracing::error!("script compile error: {error}");
                errors.push(format!("compile error: {error}"));
                return None;
            }
        }
    }
    runtime.compiled.get(&key)
}

/// Drops a despawned entity's scope so the runtime does not leak.
pub fn script_runtime_forget_entity(runtime: &mut ScriptRuntime, entity: Entity) {
    runtime.scopes.remove(&entity);
    runtime.started_entities.remove(&entity);
}

/// Compiles a script source and returns any syntax error, without running it,
/// so a tool can validate scripts ahead of time. Compilation checks syntax, not
/// whether a called command exists, which is resolved when the script runs.
pub fn script_check(source: &str) -> Result<(), String> {
    new_engine()
        .compile(source)
        .map(|_| ())
        .map_err(|error| error.to_string())
}

/// Sets the rhai operation budget per script call. The default is conservative
/// to bound an untrusted script; a trusted creative driver, where a script may
/// draw thousands of shapes a frame, raises it. 0 removes the limit.
pub fn script_runtime_set_max_operations(runtime: &mut ScriptRuntime, max: u64) {
    runtime.engine.set_max_operations(max);
}

/// Sets the largest array a script may build, which also bounds how many
/// commands one tick may produce. 0 removes the limit.
pub fn script_runtime_set_max_array_size(runtime: &mut ScriptRuntime, max: usize) {
    runtime.engine.set_max_array_size(max);
}

/// Registers asset bytes a script can reach as a blob under `assets.name`, for
/// passing to a command like spawn_model. The driver supplies them, bundled or
/// fetched, so a script can spawn a glb without any file access of its own.
pub fn script_runtime_set_asset(runtime: &mut ScriptRuntime, name: &str, bytes: Vec<u8>) {
    runtime.assets.insert(name.to_string(), bytes);
}

/// Clears every compiled script and scope, so a re-entry starts fresh and each
/// script's `on_start` runs again.
pub fn script_runtime_reset(runtime: &mut ScriptRuntime) {
    runtime.compiled.clear();
    runtime.scopes.clear();
    runtime.global_scopes.clear();
    runtime.started_globals.clear();
    runtime.started_entities.clear();
    runtime.next_replies.clear();
    runtime.random_state = RANDOM_SEED;
}

/// Runs every enabled script once against this tick's frozen events, submits the
/// commands they produced as one deferred batch, and returns those commands so a
/// tool can show the traffic. A script that produces a malformed command has it
/// dropped.
pub fn run_scripts(world: &mut World, runtime: &mut ScriptRuntime) -> ScriptReport {
    SCRIPT_RNG.with(|cell| cell.set(runtime.random_state));

    let frame_events: Vec<Event> = events(world).to_vec();

    for event in &frame_events {
        if let Event::Despawned { entity } = event {
            script_runtime_forget_entity(runtime, *entity);
        }
    }

    let policy = runtime.policy.clone();
    let dt = world.resources.window.timing.delta_time as f64;
    let time = world.resources.window.timing.uptime_milliseconds as f64 / 1000.0;
    let keyboard = &world.resources.input.keyboard;
    let move_left =
        keyboard.is_key_pressed(KeyCode::ArrowLeft) || keyboard.is_key_pressed(KeyCode::KeyA);
    let move_right =
        keyboard.is_key_pressed(KeyCode::ArrowRight) || keyboard.is_key_pressed(KeyCode::KeyD);
    let launch = keyboard.is_key_pressed(KeyCode::Space);

    // General input: every held key in `keys`, every key that went down this
    // frame in `pressed`, keyed by their KeyCode name (e.g. "KeyW", "ArrowLeft",
    // "Space"). Scripts test membership with `"KeyW" in keys`. The paddle bools
    // above stay for existing scripts.
    let mut keys = Map::new();
    for keycode in keyboard.keystates.keys() {
        if keyboard.is_key_pressed(*keycode) {
            keys.insert(format!("{keycode:?}").into(), Dynamic::from(true));
        }
    }
    let mut pressed = Map::new();
    for keycode in &keyboard.just_pressed_keys {
        pressed.insert(format!("{keycode:?}").into(), Dynamic::from(true));
    }
    let mouse = &world.resources.input.mouse;
    let mut mouse_map = Map::new();
    mouse_map.insert("x".into(), Dynamic::from(mouse.position.x as f64));
    mouse_map.insert("y".into(), Dynamic::from(mouse.position.y as f64));
    mouse_map.insert(
        "left".into(),
        Dynamic::from(mouse.state.contains(MouseState::LEFT_CLICKED)),
    );
    mouse_map.insert(
        "right".into(),
        Dynamic::from(mouse.state.contains(MouseState::RIGHT_CLICKED)),
    );
    mouse_map.insert(
        "middle".into(),
        Dynamic::from(mouse.state.contains(MouseState::MIDDLE_CLICKED)),
    );
    mouse_map.insert(
        "left_pressed".into(),
        Dynamic::from(mouse.state.contains(MouseState::LEFT_JUST_PRESSED)),
    );
    mouse_map.insert(
        "right_pressed".into(),
        Dynamic::from(mouse.state.contains(MouseState::RIGHT_JUST_PRESSED)),
    );
    mouse_map.insert("scroll".into(), Dynamic::from(mouse.wheel_delta.y as f64));

    // Where the cursor ray meets the ground plane (y = 0), as [x, y, z], or an
    // empty array when it misses or picking is unavailable. For world placement.
    #[cfg(feature = "picking")]
    let ground_hit = nightshade::prelude::get_ground_position_from_screen(
        world,
        world.resources.input.mouse.position,
        0.0,
    );
    #[cfg(not(feature = "picking"))]
    let ground_hit: Option<Vec3> = None;
    let ground = match ground_hit {
        Some(point) => array3(point),
        None => Array::new(),
    };
    let pointer_over_ui = world
        .resources
        .retained_ui
        .interaction
        .hovered_entity
        .is_some();

    let mut named = Map::new();
    let mut positions = Map::new();
    let mut velocities = Map::new();
    for (name, entity) in &world.resources.entities.names {
        named.insert(
            name.as_str().into(),
            Dynamic::from(entity_to_script(*entity)),
        );
        let (position, velocity) = entity_pos_vel(world, *entity);
        positions.insert(name.as_str().into(), Dynamic::from(position));
        velocities.insert(name.as_str().into(), Dynamic::from(velocity));
    }

    // Entities grouped by tag, each as { entity, pos, vel }, so a script can find
    // and react to a whole class of entities, not just named ones.
    let mut tag_lists: HashMap<String, Array> = HashMap::new();
    for (entity, tags) in &world.resources.entities.tags {
        let (position, velocity) = entity_pos_vel(world, *entity);
        let mut record = Map::new();
        record.insert("entity".into(), Dynamic::from(entity_to_script(*entity)));
        record.insert("pos".into(), Dynamic::from(position));
        record.insert("vel".into(), Dynamic::from(velocity));
        let record = Dynamic::from_map(record);
        for tag in tags {
            tag_lists
                .entry(tag.clone())
                .or_default()
                .push(record.clone());
        }
    }
    let mut tagged = Map::new();
    for (tag, list) in tag_lists {
        tagged.insert(tag.as_str().into(), Dynamic::from(list));
    }

    let mut produced: Vec<Command> = Vec::new();
    let mut result_tags: Vec<(usize, String)> = Vec::new();
    let mut errors: Vec<String> = Vec::new();
    let replies = std::mem::take(&mut runtime.next_replies);

    let global_scripts: Vec<(String, String)> = world
        .resources
        .global_scripts
        .entries
        .iter()
        .filter(|script| script.enabled && !script.source.trim().is_empty())
        .map(|script| (script.name.clone(), script.source.clone()))
        .collect();

    for (name, source) in &global_scripts {
        let Some(ast) = compiled_ast(runtime, source, &mut errors).cloned() else {
            continue;
        };
        let run_start =
            !runtime.started_globals.contains(name) && ast_defines_hook(&ast, "on_start");
        runtime.started_globals.insert(name.clone());
        let scope = runtime.global_scopes.entry(name.clone()).or_default();
        if !scope.contains("state") {
            scope.set_value("state", Map::new());
        }
        if !scope.contains("assets") {
            let mut assets = Map::new();
            for (name, bytes) in &runtime.assets {
                assets.insert(name.as_str().into(), Dynamic::from_blob(bytes.clone()));
            }
            scope.set_value("assets", assets);
        }
        scope.set_value("dt", dt);
        scope.set_value("time", time);
        scope.set_value("tau", std::f64::consts::TAU);
        scope.set_value("pi", std::f64::consts::PI);
        scope.set_value("replies", replies.clone());
        scope.set_value("move_left", move_left);
        scope.set_value("move_right", move_right);
        scope.set_value("launch", launch);
        scope.set_value("keys", keys.clone());
        scope.set_value("pressed", pressed.clone());
        scope.set_value("mouse", mouse_map.clone());
        scope.set_value("named", named.clone());
        scope.set_value("positions", positions.clone());
        scope.set_value("velocities", velocities.clone());
        scope.set_value("tagged", tagged.clone());
        scope.set_value("ground", ground.clone());
        scope.set_value("pointer_over_ui", pointer_over_ui);
        scope.set_value("events", events_array(&frame_events));
        scope.set_value("commands", Array::new());

        if run_start {
            if let Err(error) = runtime.engine.call_fn::<()>(scope, &ast, "on_start", ()) {
                tracing::warn!("global script '{name}' on_start error: {error}");
                errors.push(format!("on_start error: {error}"));
            } else {
                collect_commands(scope, &mut produced, &mut result_tags, &mut errors, &policy);
            }
            scope.set_value("commands", Array::new());
        }

        if ast_defines_hook(&ast, "on_tick") {
            if let Err(error) = runtime.engine.call_fn::<()>(scope, &ast, "on_tick", ()) {
                tracing::warn!("global script '{name}' on_tick error: {error}");
                errors.push(format!("on_tick error: {error}"));
                continue;
            }
            collect_commands(scope, &mut produced, &mut result_tags, &mut errors, &policy);
        }
    }

    let mut scripted: Vec<(Entity, String)> = Vec::new();
    for entity in world.core.query_entities(SCRIPT).collect::<Vec<_>>() {
        if let Some(script) = world.core.get_script(entity)
            && script.enabled
            && let ScriptSource::Embedded { source } = &script.source
        {
            scripted.push((entity, source.clone()));
        }
    }

    for (entity, source) in &scripted {
        let position = world
            .core
            .get_local_transform(*entity)
            .map(|transform| transform.translation)
            .unwrap_or_else(Vec3::zeros);
        let velocity = nightshade::ecs::physics::resources::physics_world_linear_velocity(
            &world.resources.physics,
            *entity,
        )
        .unwrap_or_else(Vec3::zeros);
        let entity_events = relevant_events(&frame_events, *entity);

        let Some(ast) = compiled_ast(runtime, source, &mut errors).cloned() else {
            continue;
        };
        let run_start =
            !runtime.started_entities.contains(entity) && ast_defines_hook(&ast, "on_start");
        runtime.started_entities.insert(*entity);
        let scope = runtime.scopes.entry(*entity).or_default();
        if !scope.contains("state") {
            scope.set_value("state", Map::new());
        }
        if !scope.contains("assets") {
            let mut assets = Map::new();
            for (name, bytes) in &runtime.assets {
                assets.insert(name.as_str().into(), Dynamic::from_blob(bytes.clone()));
            }
            scope.set_value("assets", assets);
        }
        scope.set_value("self", entity_to_script(*entity));
        scope.set_value("dt", dt);
        scope.set_value("time", time);
        scope.set_value("tau", std::f64::consts::TAU);
        scope.set_value("pi", std::f64::consts::PI);
        scope.set_value("replies", replies.clone());
        scope.set_value("move_left", move_left);
        scope.set_value("move_right", move_right);
        scope.set_value("launch", launch);
        scope.set_value("keys", keys.clone());
        scope.set_value("pressed", pressed.clone());
        scope.set_value("mouse", mouse_map.clone());
        scope.set_value("pos", array3(position));
        scope.set_value("vel", array3(velocity));
        scope.set_value("named", named.clone());
        scope.set_value("positions", positions.clone());
        scope.set_value("velocities", velocities.clone());
        scope.set_value("tagged", tagged.clone());
        scope.set_value("ground", ground.clone());
        scope.set_value("pointer_over_ui", pointer_over_ui);
        scope.set_value("events", events_array(&entity_events));
        scope.set_value("commands", Array::new());

        if run_start {
            if let Err(error) = runtime.engine.call_fn::<()>(scope, &ast, "on_start", ()) {
                tracing::warn!("script on_start error: {error}");
                errors.push(format!("on_start error: {error}"));
            } else {
                collect_commands(scope, &mut produced, &mut result_tags, &mut errors, &policy);
            }
            scope.set_value("commands", Array::new());
        }

        if ast_defines_hook(&ast, "on_tick") {
            if let Err(error) = runtime.engine.call_fn::<()>(scope, &ast, "on_tick", ()) {
                tracing::warn!("script on_tick error: {error}");
                errors.push(format!("on_tick error: {error}"));
                continue;
            }
            collect_commands(scope, &mut produced, &mut result_tags, &mut errors, &policy);
        }
    }

    let replies_out = submit_commands(world, &produced);
    let mut next_replies = Map::new();
    for (index, id) in &result_tags {
        if let Some(reply) = replies_out.get(*index) {
            next_replies.insert(id.as_str().into(), reply_to_dynamic(reply));
        }
    }
    runtime.next_replies = next_replies;
    runtime.random_state = SCRIPT_RNG.with(|cell| cell.get());
    ScriptReport {
        commands: produced,
        errors,
    }
}

/// Reads the script's `commands` array and deserializes each entry into a typed
/// [`Command`] through a small json value, which coerces rhai's f64 numbers into
/// the command's f32 fields. A command the write policy forbids is dropped with a
/// warning rather than applied.
fn collect_commands(
    scope: &Scope<'static>,
    produced: &mut Vec<Command>,
    tags: &mut Vec<(usize, String)>,
    errors: &mut Vec<String>,
    policy: &CommandPolicy,
) {
    let Some(commands) = scope
        .get("commands")
        .and_then(|value| value.read_lock::<Array>())
    else {
        return;
    };
    for entry in commands.iter() {
        let is_tagged = entry
            .read_lock::<Map>()
            .is_some_and(|map| map.contains_key(TAG_COMMAND_KEY));
        let parsed = if is_tagged {
            let request = entry.read_lock::<Map>().unwrap();
            let id = request
                .get(TAG_ID_KEY)
                .and_then(|value| value.clone().into_string().ok());
            match request.get(TAG_COMMAND_KEY) {
                Some(command) => {
                    crate::dynamic_de::from_dynamic::<Command>(command).map(|c| (c, id))
                }
                None => continue,
            }
        } else {
            crate::dynamic_de::from_dynamic::<Command>(entry).map(|c| (c, None))
        };
        match parsed {
            Ok((command, id)) if policy.allows(command.name()) => {
                if let Some(id) = id {
                    tags.push((produced.len(), id));
                }
                produced.push(command);
            }
            Ok((command, _)) => {
                tracing::warn!(
                    "script command '{}' blocked by write policy",
                    command.name()
                );
                errors.push(format!(
                    "command '{}' blocked by write policy",
                    command.name()
                ));
            }
            Err(error) => {
                tracing::warn!("dropped malformed script command: {error}");
                errors.push(format!("dropped command: {error}"));
            }
        }
    }
}

/// An entity's position and velocity as rhai `[x, y, z]` arrays, for exposing
/// other entities to a script. Missing transform or body reads as zero.
fn entity_pos_vel(world: &World, entity: Entity) -> (Array, Array) {
    let position = world
        .core
        .get_local_transform(entity)
        .map(|transform| transform.translation)
        .unwrap_or_else(Vec3::zeros);
    let velocity = nightshade::ecs::physics::resources::physics_world_linear_velocity(
        &world.resources.physics,
        entity,
    )
    .unwrap_or_else(Vec3::zeros);
    (array3(position), array3(velocity))
}

fn array3(value: Vec3) -> Array {
    vec![
        Dynamic::from(value.x as f64),
        Dynamic::from(value.y as f64),
        Dynamic::from(value.z as f64),
    ]
}

/// The events that name `entity`: a collision it took part in, or an entity
/// scoped fact about it.
fn relevant_events(frame_events: &[Event], entity: Entity) -> Vec<Event> {
    frame_events
        .iter()
        .filter(|event| match event {
            Event::Collision { a, b, .. } => *a == entity || *b == entity,
            Event::Despawned { entity: target }
            | Event::AnimationFinished { entity: target }
            | Event::AnimationEvent { entity: target, .. }
            | Event::NavigationArrived { entity: target } => *target == entity,
        })
        .cloned()
        .collect()
}

fn events_array(frame_events: &[Event]) -> Array {
    frame_events.iter().map(event_to_map).collect()
}

fn event_to_map(event: &Event) -> Dynamic {
    let mut map = Map::new();
    match event {
        Event::Collision {
            a,
            b,
            sensor,
            started,
        } => {
            map.insert("kind".into(), Dynamic::from("collision".to_string()));
            map.insert("a".into(), Dynamic::from(entity_to_script(*a)));
            map.insert("b".into(), Dynamic::from(entity_to_script(*b)));
            map.insert("sensor".into(), Dynamic::from(*sensor));
            map.insert("started".into(), Dynamic::from(*started));
        }
        Event::Despawned { entity } => {
            map.insert("kind".into(), Dynamic::from("despawned".to_string()));
            map.insert("entity".into(), Dynamic::from(entity_to_script(*entity)));
        }
        Event::AnimationFinished { entity } => {
            map.insert(
                "kind".into(),
                Dynamic::from("animation_finished".to_string()),
            );
            map.insert("entity".into(), Dynamic::from(entity_to_script(*entity)));
        }
        Event::AnimationEvent { entity, name } => {
            map.insert("kind".into(), Dynamic::from("animation_event".to_string()));
            map.insert("entity".into(), Dynamic::from(entity_to_script(*entity)));
            map.insert("name".into(), Dynamic::from(name.clone()));
        }
        Event::NavigationArrived { entity } => {
            map.insert(
                "kind".into(),
                Dynamic::from("navigation_arrived".to_string()),
            );
            map.insert("entity".into(), Dynamic::from(entity_to_script(*entity)));
        }
    }
    Dynamic::from_map(map)
}

#[cfg(test)]
mod tests {
    use super::new_engine;

    #[test]
    fn mixed_integer_and_float_arithmetic_works() {
        let engine = new_engine();
        assert_eq!(engine.eval::<f64>("3 * 1.5").unwrap(), 4.5);
        assert_eq!(engine.eval::<f64>("2.0 + 3").unwrap(), 5.0);
        assert_eq!(engine.eval::<f64>("7 / 2.0").unwrap(), 3.5);
        assert!(engine.eval::<bool>("2 < 2.5").unwrap());
        assert!(engine.eval::<bool>("3.0 >= 3").unwrap());
    }

    #[test]
    fn same_type_integer_division_stays_integer() {
        let engine = new_engine();
        assert_eq!(engine.eval::<i64>("7 / 2").unwrap(), 3);
    }

    #[test]
    fn closures_capture_and_mutate_outer_state() {
        let engine = new_engine();
        let result = engine
            .eval::<i64>(
                r#"
                let state = #{ n: 0 };
                let bump = || { state.n += 1; };
                bump.call();
                bump.call();
                state.n
            "#,
            )
            .unwrap();
        assert_eq!(result, 2);
    }

    #[test]
    fn color_helpers_build_four_channel_arrays() {
        let engine = new_engine();
        assert_eq!(
            engine
                .eval::<rhai::Array>("rgb(0.5, 0.25, 0.1)")
                .unwrap()
                .len(),
            4
        );
        assert_eq!(
            engine
                .eval::<rhai::Array>("rgba(0.1, 0.2, 0.3, 0.4)")
                .unwrap()
                .len(),
            4
        );
        assert_eq!(
            engine
                .eval::<rhai::Array>("hsv(0.0, 1.0, 1.0)")
                .unwrap()
                .len(),
            4
        );
    }
}