gizmo-scripting 0.10.0

A custom ECS and physics engine aimed for realistic simulations.
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
//! Physics API — Lua'ya sunulan fizik sistemi fonksiyonları
//!
//! Kuvvet uygulama, raycast ve yerçekimi ayarı gibi işlemler için kullanılır.

use crate::commands::{CommandQueue, ScriptCommand};
use gizmo_math::Vec3;
use mlua::prelude::*;
use std::sync::Arc;
use tracing::trace;

/// Bir collider boyutunun alt sınırı. Script'ten gelen negatif/NaN/sonsuz/sıfır değerler
/// (yazım hatası) bu değere kelepçelenir — dejenere AABB veya GJK'da NaN üretmesinler.
const MIN_COLLIDER_DIM: f32 = 1e-4;

/// Collider boyutunu güvene al: sonlu ve pozitif değilse küçük pozitif bir extent'e çek.
/// `NaN`/`-inf`/`inf`/negatif/sıfır hepsi tek dalda `MIN_COLLIDER_DIM`'e düşer.
fn sanitize_dim(v: f32) -> f32 {
    if v.is_finite() && v > MIN_COLLIDER_DIM {
        v
    } else {
        MIN_COLLIDER_DIM
    }
}

/// Physics API fonksiyonlarını Lua'ya kaydeder
pub fn register_physics_api(lua: &Lua, command_queue: Arc<CommandQueue>) -> Result<(), LuaError> {
    crate::api_table::register_protected(lua, "physics", |physics_table| {

    // === KUVVET UYGULA ===
    {
        let cq = command_queue.clone();
        physics_table.raw_set(
            "apply_force",
            lua.create_function(move |_, (id, fx, fy, fz): (u32, f32, f32, f32)| {
                cq.push(ScriptCommand::ApplyForce(id, Vec3::new(fx, fy, fz)));
                Ok(())
            })?,
        )?;
    }

    // === İMPULS UYGULA ===
    {
        let cq = command_queue.clone();
        physics_table.raw_set(
            "apply_impulse",
            lua.create_function(move |_, (id, ix, iy, iz): (u32, f32, f32, f32)| {
                cq.push(ScriptCommand::ApplyImpulse(id, Vec3::new(ix, iy, iz)));
                Ok(())
            })?,
        )?;
    }

    // === RIGIDBODY EKLE ===
    {
        let cq = command_queue.clone();
        physics_table.raw_set(
            "add_rigidbody",
            lua.create_function(
                // Contact friction/restitution live on the collider material, not
                // the body, so `add_rigidbody` no longer takes them.
                move |_, (id, mass, use_gravity): (u32, f32, bool)| {
                    cq.push(ScriptCommand::AddRigidBody {
                        id,
                        mass,
                        use_gravity,
                    });
                    Ok(())
                },
            )?,
        )?;
    }

    // === COLLIDER EKLE ===
    {
        let cq = command_queue.clone();
        physics_table.raw_set(
            "add_box_collider",
            lua.create_function(move |_, (id, hx, hy, hz): (u32, f32, f32, f32)| {
                cq.push(ScriptCommand::AddBoxCollider {
                    id,
                    hx: sanitize_dim(hx),
                    hy: sanitize_dim(hy),
                    hz: sanitize_dim(hz),
                });
                Ok(())
            })?,
        )?;
    }

    {
        let cq = command_queue.clone();
        physics_table.raw_set(
            "add_sphere_collider",
            lua.create_function(move |_, (id, radius): (u32, f32)| {
                cq.push(ScriptCommand::AddSphereCollider {
                    id,
                    radius: sanitize_dim(radius),
                });
                Ok(())
            })?,
        )?;
    }

        Ok(())
    })
}

/// Install the **call-time** physics queries for the duration of one frame's script run.
///
/// # Why a scope
///
/// Everything else in this API is a per-frame *snapshot*: Rust copies what it has into a table and
/// Lua reads it. That works for "what collided this frame" and cannot work for a parameterised
/// question — "what is the ground height at (x, z)" has no answer to precompute, because the
/// engine does not know which (x, z) the script will ask about. Answering it means running a
/// raycast **while the script is calling**, from a closure that holds the world.
///
/// The record said that was blocked: with mlua's `send` feature, `Lua::create_function` demands
/// `Fn(..) + Send + 'static`, and `&World` is neither. That is true of `Lua::create_function` and
/// **not** of `Scope::create_function`, whose bound is `F: Fn(..) + 'scope` — no `Send`, no
/// `'static`. A scoped closure may borrow the world, and mlua invalidates it when the scope ends,
/// which is exactly the lifetime the borrow has.
///
/// So the frame looks like this: enter a scope, hand Lua a function that borrows the world, run
/// the scripts, leave. Outside that window the function is gone rather than dangling — removed
/// below, so a script that squirrelled the name away and called it later gets a plain "nil value"
/// instead of an mlua error about a destructed callback.
pub fn with_call_time_queries<R>(
    lua: &Lua,
    world: &gizmo_core::World,
    run: impl FnOnce() -> Result<R, LuaError>,
) -> Result<R, LuaError> {
    let physics_table = crate::api_table::raw(lua, "physics")?;

    let out = lua.scope(|scope| {
        let ground_at = scope.create_function(|_, (x, z): (f32, f32)| {
            // Straight down from well above the world; the height is where it lands.
            let Ok(pw) = world.try_get_resource::<gizmo_physics_rigid::world::PhysicsWorld>()
            else {
                return Ok(LuaValue::Nil);
            };
            let ray = gizmo_physics_core::raycast::Ray::new(
                gizmo_math::Vec3::new(x, GROUND_PROBE_HEIGHT, z),
                gizmo_math::Vec3::new(0.0, -1.0, 0.0),
            );
            Ok(match pw.raycast(&ray, GROUND_PROBE_HEIGHT * 2.0) {
                Some(hit) => LuaValue::Number(f64::from(hit.point.y)),
                // Nothing under that point. `nil` rather than 0.0: a floor at height zero and no
                // floor at all are different answers, and a script that cannot tell them apart
                // will happily place something on a floor that is not there.
                None => LuaValue::Nil,
            })
        })?;
        physics_table.raw_set("ground_at", ground_at)?;
        run()
    });

    // Whatever happened, the borrow is over — take the name with it.
    physics_table.raw_set("ground_at", LuaValue::Nil)?;
    out
}

/// How far above the query point the ground probe starts. High enough to clear any level geometry
/// the engine is used for, and finite so the raycast has a bound.
const GROUND_PROBE_HEIGHT: f32 = 10_000.0;

/// Her frame güncel fizik olaylarını (Tetikleyiciler, Çarpışmalar) Lua'ya aktarır
#[tracing::instrument(skip_all, name = "script_physics_read")]
pub fn update_physics_api(
    lua: &Lua,
    world: &gizmo_core::World,
) -> Result<(), LuaError> {
    // The real table, not the global: the global is a read-only proxy so a script cannot
    // rewrite the API (see `api_table`), and the engine's per-frame writes go behind it.
    let physics_table = crate::api_table::raw(lua, "physics")?;
    
    let triggers = lua.create_table()?;
    let collisions = lua.create_table()?;
    
    if let Ok(physics_world) = world.try_get_resource::<gizmo_physics_rigid::world::PhysicsWorld>() {
        // Trigger (Tetikleyici) Olayları
        for (i, t_event) in physics_world.trigger_events().iter().enumerate() {
            let ev = lua.create_table()?;
            ev.set("trigger_id", t_event.trigger_entity.id())?;
            ev.set("other_id", t_event.other_entity.id())?;
            let status = match t_event.event_type {
                gizmo_physics_core::collision::CollisionEventType::Started => "enter",
                gizmo_physics_core::collision::CollisionEventType::Persisting => "stay",
                gizmo_physics_core::collision::CollisionEventType::Ended => "exit",
            };
            ev.set("status", status)?;
            triggers.set(i + 1, ev)?;
        }
        
        // Fiziksel Çarpışma Olayları
        for (i, c_event) in physics_world.collision_events().iter().enumerate() {
            let ev = lua.create_table()?;
            ev.set("entity_a", c_event.entity_a.id())?;
            ev.set("entity_b", c_event.entity_b.id())?;
            let status = match c_event.event_type {
                gizmo_physics_core::collision::CollisionEventType::Started => "enter",
                gizmo_physics_core::collision::CollisionEventType::Persisting => "stay",
                gizmo_physics_core::collision::CollisionEventType::Ended => "exit",
            };
            ev.set("status", status)?;
            collisions.set(i + 1, ev)?;
        }

        trace!(
            trigger_count = physics_world.trigger_events().len(),
            collision_count = physics_world.collision_events().len(),
            "[Scripting] fizik olayları Lua'ya aktarıldı"
        );
    } else {
        // PhysicsWorld kaynağı yoksa listeler sessizce boş kalır; olay bekleyen bir
        // script'in neden hiçbir şey almadığını anlamak için görünür kıl.
        trace!("[Scripting] PhysicsWorld kaynağı yok — trigger/collision listeleri boş");
    }

    // Her frame listeleri güncelle
    physics_table.raw_set("triggers", triggers)?;
    physics_table.raw_set("collisions", collisions)?;
    
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use gizmo_core::World;
    use gizmo_physics_rigid::world::PhysicsWorld;
    use gizmo_physics_core::collision::{TriggerEvent, CollisionEvent, CollisionEventType};
    use mlua::Lua;

    #[test]
    fn test_update_physics_api() {
        let lua = Lua::new();
        // Register the API the way the engine does: the update path reads the real table from the
        // registry, and a hand-built global is a different table that nothing writes to.
        register_physics_api(&lua, Arc::new(CommandQueue::new())).unwrap();

        let mut world = World::new();
        let ent1 = world.spawn();
        let ent2 = world.spawn();

        let mut physics_world = PhysicsWorld::new();
        physics_world.trigger_events.push(TriggerEvent {
            trigger_entity: gizmo_physics_core::BodyHandle::from_id(ent1.id()),
            other_entity: gizmo_physics_core::BodyHandle::from_id(ent2.id()),
            event_type: CollisionEventType::Started,
        });

        physics_world.collision_events.push(CollisionEvent {
            entity_a: gizmo_physics_core::BodyHandle::from_id(ent1.id()),
            entity_b: gizmo_physics_core::BodyHandle::from_id(ent2.id()),
            event_type: CollisionEventType::Started,
            contact_points: Default::default(),
        });

        world.insert_resource(physics_world);

        update_physics_api(&lua, &world).unwrap();

        let script = r#"
            local triggers = physics.triggers
            local collisions = physics.collisions
            assert(#triggers == 1)
            assert(triggers[1].status == "enter")
            assert(#collisions == 1)
            assert(collisions[1].status == "enter")
        "#;

        lua.load(script).exec().unwrap();
    }

    #[test]
    fn sanitize_dim_rejects_bad_values() {
        assert_eq!(sanitize_dim(f32::NAN), MIN_COLLIDER_DIM);
        assert_eq!(sanitize_dim(f32::INFINITY), MIN_COLLIDER_DIM);
        assert_eq!(sanitize_dim(f32::NEG_INFINITY), MIN_COLLIDER_DIM);
        assert_eq!(sanitize_dim(-5.0), MIN_COLLIDER_DIM);
        assert_eq!(sanitize_dim(0.0), MIN_COLLIDER_DIM);
        assert_eq!(sanitize_dim(2.5), 2.5); // valid values pass through
    }

    #[test]
    fn box_collider_dims_are_sanitized_from_lua() {
        let lua = Lua::new();
        let cq = Arc::new(CommandQueue::new());
        register_physics_api(&lua, cq.clone()).unwrap();
        // hx negative, hy NaN (0/0), hz valid — script typo hardening.
        lua.load("physics.add_box_collider(1, -5.0, 0/0, 2.0)").exec().unwrap();

        let cmds = cq.drain();
        assert_eq!(cmds.len(), 1);
        match &cmds[0] {
            ScriptCommand::AddBoxCollider { hx, hy, hz, .. } => {
                assert!(hx.is_finite() && *hx > 0.0, "negative hx must be clamped, got {hx}");
                assert!(hy.is_finite() && *hy > 0.0, "NaN hy must be clamped, got {hy}");
                assert_eq!(*hz, 2.0, "valid hz must pass through untouched");
            }
            other => panic!("expected AddBoxCollider, got {other:?}"),
        }
    }

    #[test]
    fn sphere_collider_radius_is_sanitized_from_lua() {
        let lua = Lua::new();
        let cq = Arc::new(CommandQueue::new());
        register_physics_api(&lua, cq.clone()).unwrap();
        lua.load("physics.add_sphere_collider(7, -3.0)").exec().unwrap();

        let cmds = cq.drain();
        assert_eq!(cmds.len(), 1);
        match &cmds[0] {
            ScriptCommand::AddSphereCollider { radius, .. } => {
                assert!(radius.is_finite() && *radius > 0.0, "radius clamped, got {radius}");
            }
            other => panic!("expected AddSphereCollider, got {other:?}"),
        }
    }

    /// apply_force / apply_impulse / add_rigidbody Lua argümanlarını doğru komutlara çevirmeli.
    #[test]
    fn force_impulse_rigidbody_calls_push_expected_commands() {
        let lua = Lua::new();
        let cq = Arc::new(CommandQueue::new());
        register_physics_api(&lua, cq.clone()).unwrap();

        lua.load(
            r#"
            physics.apply_force(1, 0.0, -9.8, 0.0)
            physics.apply_impulse(1, 10.0, 0.0, 0.0)
            physics.add_rigidbody(1, 2.5, true)
            "#,
        )
        .exec()
        .unwrap();

        let cmds = cq.drain();
        assert_eq!(cmds.len(), 3);
        assert!(matches!(cmds[0], ScriptCommand::ApplyForce(1, f) if f == Vec3::new(0.0, -9.8, 0.0)));
        assert!(matches!(cmds[1], ScriptCommand::ApplyImpulse(1, i) if i == Vec3::new(10.0, 0.0, 0.0)));
        match cmds[2] {
            ScriptCommand::AddRigidBody { id, mass, use_gravity } => {
                assert_eq!(id, 1);
                assert!((mass - 2.5).abs() < 1e-6);
                assert!(use_gravity);
            }
            ref other => panic!("beklenen AddRigidBody, gelen {other:?}"),
        }
    }

    /// Geçerli (sonlu, pozitif) box boyutları dokunulmadan geçmeli.
    #[test]
    fn valid_box_dims_pass_through() {
        let lua = Lua::new();
        let cq = Arc::new(CommandQueue::new());
        register_physics_api(&lua, cq.clone()).unwrap();
        lua.load("physics.add_box_collider(1, 0.5, 1.0, 2.0)").exec().unwrap();

        let cmds = cq.drain();
        match &cmds[0] {
            ScriptCommand::AddBoxCollider { hx, hy, hz, .. } => {
                assert_eq!((*hx, *hy, *hz), (0.5, 1.0, 2.0));
            }
            other => panic!("beklenen AddBoxCollider, gelen {other:?}"),
        }
    }

    /// PhysicsWorld kaynağı hiç yoksa update_physics_api panik etmemeli ve
    /// triggers/collisions BOŞ tablolar olarak ayarlanmalı (belirsiz değil).
    #[test]
    fn update_without_physics_world_yields_empty_lists() {
        let lua = Lua::new();
        register_physics_api(&lua, Arc::new(CommandQueue::new())).unwrap();

        let world = World::new(); // PhysicsWorld kaynağı eklenmedi
        update_physics_api(&lua, &world).unwrap();

        lua.load(
            r#"
            assert(type(physics.triggers) == "table", "triggers tablo olmalı")
            assert(#physics.triggers == 0, "triggers boş olmalı")
            assert(#physics.collisions == 0, "collisions boş olmalı")
            "#,
        )
        .exec()
        .unwrap();
    }

    /// Çarpışma olay tipi → durum string eşlemesi: Persisting="stay", Ended="exit".
    #[test]
    fn collision_event_status_maps_stay_and_exit() {
        let lua = Lua::new();
        register_physics_api(&lua, Arc::new(CommandQueue::new())).unwrap();

        let mut world = World::new();
        let a = world.spawn();
        let b = world.spawn();
        let mut pw = PhysicsWorld::new();
        pw.collision_events.push(CollisionEvent {
            entity_a: gizmo_physics_core::BodyHandle::from_id(a.id()),
            entity_b: gizmo_physics_core::BodyHandle::from_id(b.id()),
            event_type: CollisionEventType::Persisting,
            contact_points: Default::default(),
        });
        pw.trigger_events.push(TriggerEvent {
            trigger_entity: gizmo_physics_core::BodyHandle::from_id(a.id()),
            other_entity: gizmo_physics_core::BodyHandle::from_id(b.id()),
            event_type: CollisionEventType::Ended,
        });
        world.insert_resource(pw);

        update_physics_api(&lua, &world).unwrap();

        lua.load(
            r#"
            assert(physics.collisions[1].status == "stay", "Persisting -> stay")
            assert(physics.triggers[1].status == "exit", "Ended -> exit")
            "#,
        )
        .exec()
        .unwrap();
    }
}