nightshade-api 0.44.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
//! 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, deserialized from the rhai value through a small json step that
//! coerces rhai's f64 numbers into the command's f32 fields. Each tick the runner
//! reads the engine's frozen events, runs every enabled script, and submits the
//! commands they produced as one deferred batch.
//!
//! 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, submit_commands};

/// 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>>,
}

impl Default for ScriptRuntime {
    fn default() -> Self {
        let mut engine = Engine::new();
        engine.set_max_operations(200_000);
        engine.set_max_call_levels(32);
        engine.set_max_string_size(8 * 1024);
        engine.set_max_array_size(4096);
        register_api(&mut engine);
        Self {
            enabled: false,
            policy: CommandPolicy::AllowAll,
            engine,
            compiled: HashMap::new(),
            scopes: HashMap::new(),
            global_scopes: HashMap::new(),
        }
    }
}

/// Registers the read-only helpers a script always has. The command vocabulary
/// is not here: a script targets the full [`Command`] surface by pushing each
/// command's shape, and `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}"));
    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)
    });
}

/// 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) -> 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}");
                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);
}

/// Clears every compiled script and scope, so a re-entry starts fresh.
pub fn script_runtime_reset(runtime: &mut ScriptRuntime) {
    runtime.compiled.clear();
    runtime.scopes.clear();
    runtime.global_scopes.clear();
}

/// 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) -> Vec<Command> {
    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 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 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).cloned() else {
            continue;
        };
        let scope = runtime.global_scopes.entry(name.clone()).or_default();
        if !scope.contains("state") {
            scope.set_value("state", Map::new());
        }
        scope.set_value("dt", dt);
        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 let Err(error) = runtime.engine.call_fn::<()>(scope, &ast, "on_tick", ()) {
            tracing::warn!("global script '{name}' on_tick error: {error}");
            continue;
        }
        collect_commands(scope, &mut produced, &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).cloned() else {
            continue;
        };
        let scope = runtime.scopes.entry(*entity).or_default();
        if !scope.contains("state") {
            scope.set_value("state", Map::new());
        }
        scope.set_value("self", entity_to_script(*entity));
        scope.set_value("dt", dt);
        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 let Err(error) = runtime.engine.call_fn::<()>(scope, &ast, "on_tick", ()) {
            tracing::warn!("script on_tick error: {error}");
            continue;
        }
        collect_commands(scope, &mut produced, &policy);
    }

    submit_commands(world, &produced);
    produced
}

/// 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>, policy: &CommandPolicy) {
    if let Some(commands) = scope.get_value::<Array>("commands") {
        for command in &commands {
            let value = match serde_json::to_value(command) {
                Ok(value) => value,
                Err(error) => {
                    tracing::warn!("dropped unserializable script command: {error}");
                    continue;
                }
            };
            match serde_json::from_value::<Command>(value) {
                Ok(parsed) if policy.allows(parsed.name()) => produced.push(parsed),
                Ok(parsed) => {
                    tracing::warn!("script command '{}' blocked by write policy", parsed.name())
                }
                Err(error) => tracing::warn!("dropped malformed script 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)
}