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
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
//! Retained scene content: primitives, models, hierarchy, and the [`Object`]
//! descriptor for spawning shape, color, and physics in one call.

use crate::palette::WHITE;
use crate::runner::MATERIAL_PREFIX;
use nightshade::prelude::nalgebra_glm::Mat4;
use nightshade::prelude::*;
use serde::{Deserialize, Serialize};

pub use nightshade::prelude::despawn_recursive_immediate as despawn;
pub use nightshade::prelude::spawn_cone_at as spawn_cone;
pub use nightshade::prelude::spawn_cube_at as spawn_cube;
pub use nightshade::prelude::spawn_cylinder_at as spawn_cylinder;
pub use nightshade::prelude::spawn_plane_at as spawn_plane;
pub use nightshade::prelude::spawn_sphere_at as spawn_sphere;
pub use nightshade::prelude::spawn_torus_at as spawn_torus;

/// The primitive shapes [`spawn_object`] can produce.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, enum2schema::Schema,
)]
pub enum Shape {
    #[default]
    Cube,
    Sphere,
    Cylinder,
    Cone,
    Torus,
    Plane,
}

/// Physics participation for [`spawn_object`]. Requires the `physics`
/// feature, which is on by default.
///
/// Dynamic cubes, spheres, cylinders, and cones get exact colliders. A
/// dynamic torus gets a convex hull of its mesh, which fills the hole. Static
/// toruses and planes collide against the exact triangle mesh.
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize, enum2schema::Schema)]
pub enum Body {
    #[default]
    None,
    Static,
    Dynamic {
        mass: f32,
    },
}

/// Everything about one object in a single struct literal.
///
/// ```ignore
/// let ball = spawn_object(world, Object {
///     shape: Shape::Sphere,
///     position: vec3(0.0, 4.0, 0.0),
///     color: RED,
///     body: Body::Dynamic { mass: 2.0 },
///     ..Object::default()
/// });
/// ```
pub struct Object {
    pub shape: Shape,
    pub position: Vec3,
    pub scale: Vec3,
    pub color: [f32; 4],
    pub body: Body,
}

impl Default for Object {
    fn default() -> Self {
        Self {
            shape: Shape::Cube,
            position: Vec3::zeros(),
            scale: Vec3::new(1.0, 1.0, 1.0),
            color: WHITE,
            body: Body::None,
        }
    }
}

/// Spawns an [`Object`]: mesh, color, and optional physics body in one call.
pub fn spawn_object(world: &mut World, object: Object) -> Entity {
    let entity = spawn_mesh_at(
        world,
        mesh_name(object.shape),
        object.position,
        object.scale,
    );
    crate::appearance::set_color(world, entity, object.color);
    match object.body {
        Body::None => {}
        #[cfg(feature = "physics")]
        Body::Static => {
            let collider = static_collider(world, object.shape, object.scale)
                .with_friction(0.8)
                .with_restitution(0.1);
            attach_body(
                world,
                entity,
                RigidBodyComponent::new_static().with_translation(
                    object.position.x,
                    object.position.y,
                    object.position.z,
                ),
                collider,
                false,
            );
        }
        #[cfg(feature = "physics")]
        Body::Dynamic { mass } => {
            let collider = dynamic_collider(world, object.shape, object.scale)
                .with_friction(0.7)
                .with_restitution(0.2);
            attach_body(
                world,
                entity,
                RigidBodyComponent::new_dynamic()
                    .with_translation(object.position.x, object.position.y, object.position.z)
                    .with_mass(mass),
                collider,
                true,
            );
        }
        #[cfg(not(feature = "physics"))]
        Body::Static | Body::Dynamic { .. } => {}
    }
    entity
}

/// Spawns a dynamic capsule physics body at `position`: a `radius` pill with a
/// `half_height` cylindrical section, `mass`, and a linear RGBA `color`. The
/// capsule is the upright character shape. The visual is a cylinder, the
/// collider is the true capsule. Capsule is not a [`Shape`], so it has its own
/// spawn rather than coming through [`spawn_object`].
#[cfg(feature = "physics")]
pub fn spawn_capsule_body(
    world: &mut World,
    position: Vec3,
    half_height: f32,
    radius: f32,
    mass: f32,
    color: [f32; 4],
) -> Entity {
    let scale = Vec3::new(radius * 2.0, (half_height + radius) * 2.0, radius * 2.0);
    let entity = spawn_mesh_at(world, mesh_name(Shape::Cylinder), position, scale);
    crate::appearance::set_color(world, entity, color);
    let collider = ColliderComponent::new_capsule(half_height, radius)
        .with_friction(0.7)
        .with_restitution(0.2);
    attach_body(
        world,
        entity,
        RigidBodyComponent::new_dynamic()
            .with_translation(position.x, position.y, position.z)
            .with_mass(mass),
        collider,
        true,
    );
    entity
}

/// Spawns a static, collidable mesh from raw geometry at `position`: it renders
/// the mesh and gives it an exact triangle collider, so dynamic bodies collide
/// with arbitrary level geometry. Each vertex is a (position, normal, uv) triple
/// and `indices` lists triangle corners three at a time. Heavy, so use it for
/// static level geometry, not movers.
#[cfg(feature = "physics")]
pub fn spawn_collidable_mesh(
    world: &mut World,
    name: &str,
    vertices: &[([f32; 3], [f32; 3], [f32; 2])],
    indices: &[u32],
    position: Vec3,
) -> Entity {
    let entity = crate::mesh::spawn_custom_mesh(world, name, vertices, indices, position);
    let positions: Vec<[f32; 3]> = vertices.iter().map(|(point, _, _)| *point).collect();
    let triangles: Vec<[u32; 3]> = indices
        .chunks_exact(3)
        .map(|chunk| [chunk[0], chunk[1], chunk[2]])
        .collect();
    let collider = ColliderComponent {
        shape: nightshade::ecs::physics::components::ColliderShape::TriMesh {
            vertices: positions,
            indices: triangles,
        },
        ..Default::default()
    };
    attach_body(
        world,
        entity,
        RigidBodyComponent::new_static().with_translation(position.x, position.y, position.z),
        collider,
        false,
    );
    entity
}

/// Spawns one [`Object`] at each position, all sharing a single registered
/// material, which is what writing it longhand for a crowd looks like. A
/// thousand entities through this hold one material entry, not a thousand.
pub fn spawn_objects(world: &mut World, object: Object, positions: &[Vec3]) -> Vec<Entity> {
    let mut entities = Vec::with_capacity(positions.len());
    let mut shared_material: Option<String> = None;
    #[cfg(feature = "physics")]
    let mut collider_template: Option<ColliderComponent> = None;

    for &position in positions {
        let entity = spawn_mesh_at(world, mesh_name(object.shape), position, object.scale);
        match shared_material.as_deref() {
            None => {
                crate::appearance::set_color(world, entity, object.color);
                shared_material = world
                    .core
                    .get_material_ref(entity)
                    .map(|material_ref| material_ref.name.clone());
            }
            Some(name) => {
                let name = name.to_string();
                adopt_shared_material(world, entity, &name);
            }
        }

        #[cfg(feature = "physics")]
        match object.body {
            Body::None => {}
            Body::Static => {
                let collider = collider_template
                    .get_or_insert_with(|| {
                        static_collider(world, object.shape, object.scale)
                            .with_friction(0.8)
                            .with_restitution(0.1)
                    })
                    .clone();
                attach_body(
                    world,
                    entity,
                    RigidBodyComponent::new_static()
                        .with_translation(position.x, position.y, position.z),
                    collider,
                    false,
                );
            }
            Body::Dynamic { mass } => {
                let collider = collider_template
                    .get_or_insert_with(|| {
                        dynamic_collider(world, object.shape, object.scale)
                            .with_friction(0.7)
                            .with_restitution(0.2)
                    })
                    .clone();
                attach_body(
                    world,
                    entity,
                    RigidBodyComponent::new_dynamic()
                        .with_translation(position.x, position.y, position.z)
                        .with_mass(mass),
                    collider,
                    true,
                );
            }
        }

        entities.push(entity);
    }
    entities
}

/// Spawns one entity that renders `transforms.len()` copies of the shape in a
/// single draw call, the cheapest way to put thousands of identical things on
/// screen. Per copy control afterward goes through the entity's
/// `InstancedMesh` component.
pub fn spawn_instanced(
    world: &mut World,
    shape: Shape,
    transforms: Vec<InstanceTransform>,
    color: [f32; 4],
) -> Entity {
    let shape_mesh_name = mesh_name(shape);
    ensure_primitive_mesh(world, shape_mesh_name);
    let fallback = format!(
        "api::material::instanced::{:.4}_{:.4}_{:.4}_{:.4}",
        color[0], color[1], color[2], color[3]
    );
    let material_name = nightshade::ecs::material::resources::material_registry_find_or_insert(
        &mut world.resources.assets.material_registry,
        fallback,
        Material {
            base_color: color,
            ..Default::default()
        },
    );
    spawn_instanced_mesh_with_material(world, shape_mesh_name, transforms, &material_name)
}

fn adopt_shared_material(world: &mut World, entity: Entity, name: &str) {
    let previous = world
        .core
        .get_material_ref(entity)
        .map(|material_ref| material_ref.name.clone());
    if let Some(previous_name) = previous
        && let Some((index, _)) = registry_lookup_index(
            &world.resources.assets.material_registry.registry,
            &previous_name,
        )
    {
        registry_remove_reference(
            &mut world.resources.assets.material_registry.registry,
            index,
        );
    }
    if let Some((index, _)) =
        registry_lookup_index(&world.resources.assets.material_registry.registry, name)
    {
        registry_add_reference(
            &mut world.resources.assets.material_registry.registry,
            index,
        );
    }
    world
        .core
        .set_material_ref(entity, MaterialRef::new(name.to_string()));
    world.resources.mesh_render_state.mark_entity_added(entity);
}

pub(crate) fn ensure_primitive_mesh(world: &mut World, mesh_name: &str) {
    use nightshade::ecs::mesh::components::{
        create_cone_mesh, create_cube_mesh, create_cylinder_mesh, create_plane_mesh,
        create_sphere_mesh, create_torus_mesh,
    };
    if !world
        .resources
        .assets
        .mesh_cache
        .registry
        .name_to_index
        .contains_key(mesh_name)
    {
        let mesh = match mesh_name {
            "Cube" => create_cube_mesh(),
            "Sphere" => create_sphere_mesh(1.0, 16),
            "Plane" => create_plane_mesh(2.0),
            "Torus" => create_torus_mesh(1.0, 0.3, 32, 16),
            "Cylinder" => create_cylinder_mesh(0.5, 1.0, 16),
            _ => create_cone_mesh(0.5, 1.0, 16),
        };
        mesh_cache_insert(
            &mut world.resources.assets.mesh_cache,
            mesh_name.to_string(),
            mesh,
        );
    }
    if let Some((index, _)) =
        registry_lookup_index(&world.resources.assets.mesh_cache.registry, mesh_name)
    {
        registry_add_reference(&mut world.resources.assets.mesh_cache.registry, index);
    }
}

/// Spawns a simulated cloth sheet hanging from `position`, pinned along its
/// top row. It drapes, collides with the ground, and responds to
/// `world.resources.wind`. Color it like anything else with
/// [`set_color`](crate::prelude::set_color).
pub fn spawn_cloth_sheet(world: &mut World, position: Vec3, width: f32, height: f32) -> Entity {
    spawn_cloth(
        world,
        Cloth {
            width,
            height,
            ..Default::default()
        },
        position,
        "Cloth".to_string(),
    )
}

/// Shows or hides the entity without despawning it.
pub fn set_visible(world: &mut World, entity: Entity, visible: bool) {
    if let Some(visibility) = world.core.get_visibility_mut(entity) {
        visibility.visible = visible;
    }
}

/// Spawns a flat ground plane reaching `half_extent` in each direction. With
/// the `physics` feature it carries a static collider so dynamic objects land
/// on it.
pub fn spawn_floor(world: &mut World, half_extent: f32) -> Entity {
    let entity = spawn_mesh_at(
        world,
        "Plane",
        Vec3::zeros(),
        Vec3::new(half_extent, 1.0, half_extent),
    );
    #[cfg(feature = "physics")]
    attach_body(
        world,
        entity,
        RigidBodyComponent::new_static().with_translation(0.0, -0.05, 0.0),
        ColliderComponent::new_cuboid(half_extent, 0.05, half_extent)
            .with_friction(0.8)
            .with_restitution(0.1),
        false,
    );
    entity
}

/// Spawns a glb model with its textures, materials, skins, and animations.
/// Panics with the import error when the bytes are not a valid glb.
pub fn spawn_model(world: &mut World, glb_bytes: &[u8], position: Vec3) -> Entity {
    let mut result =
        import_gltf_from_bytes(glb_bytes).expect("failed to import the glb model bytes");
    nightshade::ecs::loading::queue_gltf_load(world, &mut result);
    let prefab = &result.prefabs[0];
    nightshade::ecs::prefab::commands::spawn_prefab_with_skins(
        world,
        prefab,
        &result.animations,
        &result.skins,
        position,
    )
}

/// Starts playing the model's animation clip at `clip_index`.
pub fn play_animation(world: &mut World, entity: Entity, clip_index: usize) {
    if let Some(player) = world.core.get_animation_player_mut(entity) {
        player.play(clip_index);
    }
}

/// Sets whether the entity's current animation repeats.
pub fn set_animation_looping(world: &mut World, entity: Entity, looping: bool) {
    if let Some(player) = world.core.get_animation_player_mut(entity) {
        player.looping = looping;
    }
}

/// Plays the animation clip named `clip_name`. Returns whether a clip with that
/// name exists on the model.
pub fn play_animation_named(world: &mut World, entity: Entity, clip_name: &str) -> bool {
    if let Some(player) = world.core.get_animation_player_mut(entity)
        && let Some(index) = player.clips.iter().position(|clip| clip.name == clip_name)
    {
        player.play(index);
        return true;
    }
    false
}

/// Sets the playback speed of the entity's animation. 1.0 is normal, 2.0 doubles
/// it, a negative value plays backward.
pub fn set_animation_speed(world: &mut World, entity: Entity, speed: f32) {
    if let Some(player) = world.core.get_animation_player_mut(entity) {
        player.speed = speed;
    }
}

/// Cross-fades from the current clip to `clip_index` over `seconds`, a smooth
/// transition rather than a hard cut.
pub fn blend_to_animation(world: &mut World, entity: Entity, clip_index: usize, seconds: f32) {
    if let Some(player) = world.core.get_animation_player_mut(entity) {
        player.blend_to(clip_index, seconds);
    }
}

/// Cross-fades to the clip named `clip_name` over `seconds`. Returns whether a
/// clip with that name exists.
pub fn blend_to_animation_named(
    world: &mut World,
    entity: Entity,
    clip_name: &str,
    seconds: f32,
) -> bool {
    if let Some(player) = world.core.get_animation_player_mut(entity)
        && let Some(index) = player.clips.iter().position(|clip| clip.name == clip_name)
    {
        player.blend_to(index, seconds);
        return true;
    }
    false
}

/// Pauses the entity's animation at the current frame.
pub fn pause_animation(world: &mut World, entity: Entity) {
    if let Some(player) = world.core.get_animation_player_mut(entity) {
        player.pause();
    }
}

/// Resumes a paused animation from where it left off.
pub fn resume_animation(world: &mut World, entity: Entity) {
    if let Some(player) = world.core.get_animation_player_mut(entity) {
        player.resume();
    }
}

/// Stops the entity's animation and resets it to the first frame.
pub fn stop_animation(world: &mut World, entity: Entity) {
    if let Some(player) = world.core.get_animation_player_mut(entity) {
        player.stop();
    }
}

/// The names of the entity's animation clips, in clip-index order.
pub fn animation_clips(world: &World, entity: Entity) -> Vec<String> {
    world
        .core
        .get_animation_player(entity)
        .map(|player| player.clips.iter().map(|clip| clip.name.clone()).collect())
        .unwrap_or_default()
}

/// Adds a named marker at `time` seconds on the clip at `clip_index`. While that
/// clip plays, crossing the marker publishes an `Event::AnimationEvent` carrying
/// `name`, the cue to spawn a footstep, land a hit, or trigger an effect. Read
/// it with [`drain_events`](crate::prelude::drain_events). Returns false if the
/// entity has no animation player or the clip index is out of range.
pub fn add_animation_event(
    world: &mut World,
    entity: Entity,
    clip_index: usize,
    time: f32,
    name: &str,
) -> bool {
    if let Some(player) = world.core.get_animation_player_mut(entity)
        && let Some(clip) = player.clips.get_mut(clip_index)
    {
        clip.events
            .push(nightshade::ecs::animation::components::AnimationEvent {
                time,
                name: name.to_string(),
            });
        return true;
    }
    false
}

/// Adds a named marker at `time` seconds on the clip named `clip_name`, the
/// by-name form of [`add_animation_event`].
pub fn add_animation_event_named(
    world: &mut World,
    entity: Entity,
    clip_name: &str,
    time: f32,
    name: &str,
) -> bool {
    if let Some(player) = world.core.get_animation_player_mut(entity)
        && let Some(clip) = player.clips.iter_mut().find(|clip| clip.name == clip_name)
    {
        clip.events
            .push(nightshade::ecs::animation::components::AnimationEvent {
                time,
                name: name.to_string(),
            });
        return true;
    }
    false
}

/// Plays an extra clip on top of the base animation at `weight` (0.0 to 1.0),
/// blended over the bones the clip targets. Returns the layer's index for
/// [`set_animation_layer_weight`], or `None` if the entity has no animation
/// player. A reload, a hit reaction, anything composited over a walk or idle.
pub fn add_animation_layer(
    world: &mut World,
    entity: Entity,
    clip_index: usize,
    weight: f32,
) -> Option<usize> {
    let player = world.core.get_animation_player_mut(entity)?;
    let index = player.layers.len();
    player.layers.push(
        nightshade::ecs::animation::components::AnimationLayer::new(clip_index).with_weight(weight),
    );
    Some(index)
}

/// Plays an extra clip limited to the named bones, the per-bone mask form of
/// [`add_animation_layer`]. Pass the bone names the layer should drive, like the
/// spine and arms for an upper-body wave over a full-body walk.
pub fn add_animation_layer_masked(
    world: &mut World,
    entity: Entity,
    clip_index: usize,
    weight: f32,
    bones: &[&str],
) -> Option<usize> {
    let player = world.core.get_animation_player_mut(entity)?;
    let index = player.layers.len();
    let mask = bones.iter().map(|bone| bone.to_string()).collect();
    player.layers.push(
        nightshade::ecs::animation::components::AnimationLayer::new(clip_index)
            .with_weight(weight)
            .with_mask(mask),
    );
    Some(index)
}

/// Sets the blend weight of a layer added by [`add_animation_layer`], for fading
/// a composited animation in and out. 0.0 disables it without removing it.
pub fn set_animation_layer_weight(
    world: &mut World,
    entity: Entity,
    layer_index: usize,
    weight: f32,
) {
    if let Some(player) = world.core.get_animation_player_mut(entity)
        && let Some(layer) = player.layers.get_mut(layer_index)
    {
        layer.weight = weight;
    }
}

/// Removes every animation layer, leaving only the base animation.
pub fn clear_animation_layers(world: &mut World, entity: Entity) {
    if let Some(player) = world.core.get_animation_player_mut(entity) {
        player.layers.clear();
    }
}

/// Registers `entity` under `name` so it can be looked up by name, including
/// through the `named` map a rhai script reads. Use it to hand specific entities
/// (a HUD label, a player) to scripts that drive them.
pub fn name_entity(world: &mut World, name: &str, entity: Entity) {
    world
        .resources
        .entities
        .names
        .insert(name.to_string(), entity);
}

/// Spawns an invisible group at `position` for building hierarchies. Parent
/// things to it and move, rotate, or animate the group to drive them all.
pub fn spawn_group(world: &mut World, position: Vec3) -> Entity {
    let entity = spawn_entities(
        world,
        NAME | LOCAL_TRANSFORM | LOCAL_TRANSFORM_DIRTY | GLOBAL_TRANSFORM,
        1,
    )[0];
    world.core.set_name(entity, Name("Group".to_string()));
    assign_local_transform(
        world,
        entity,
        LocalTransform {
            translation: position,
            ..Default::default()
        },
    );
    entity
}

/// Parents `child` to `parent`, or unparents it with `None`, keeping the
/// child exactly where it is in world space.
pub fn set_parent(world: &mut World, child: Entity, parent: Option<Entity>) {
    let child_world = crate::placement::world_matrix(world, child);
    let parent_world = parent
        .map(|parent_entity| crate::placement::world_matrix(world, parent_entity))
        .unwrap_or_else(Mat4::identity);
    let local = nalgebra_glm::inverse(&parent_world) * child_world;

    let translation = nalgebra_glm::vec3(local[(0, 3)], local[(1, 3)], local[(2, 3)]);
    let basis_x = nalgebra_glm::vec3(local[(0, 0)], local[(1, 0)], local[(2, 0)]);
    let basis_y = nalgebra_glm::vec3(local[(0, 1)], local[(1, 1)], local[(2, 1)]);
    let basis_z = nalgebra_glm::vec3(local[(0, 2)], local[(1, 2)], local[(2, 2)]);
    let scale = nalgebra_glm::vec3(
        basis_x.magnitude(),
        basis_y.magnitude(),
        basis_z.magnitude(),
    );
    let rotation_matrix = nalgebra_glm::Mat3::from_columns(&[
        basis_x / scale.x.max(f32::EPSILON),
        basis_y / scale.y.max(f32::EPSILON),
        basis_z / scale.z.max(f32::EPSILON),
    ]);
    let rotation = nalgebra_glm::mat3_to_quat(&rotation_matrix);

    if parent.is_some() {
        world.core.add_components(child, PARENT);
    }
    update_parent(
        world,
        child,
        parent.map(|parent_entity| Parent(Some(parent_entity))),
    );
    assign_local_transform(
        world,
        child,
        LocalTransform {
            translation,
            rotation,
            scale,
        },
    );
}

#[cfg(feature = "picking")]
pub(crate) fn is_reserved(world: &World, entity: Entity) -> bool {
    world
        .core
        .get_name(entity)
        .is_some_and(|name| name.0.starts_with(crate::runner::RESERVED_PREFIX))
}

pub(crate) fn api_material_name(entity: Entity) -> String {
    format!("{MATERIAL_PREFIX}{}", entity.id)
}

fn mesh_name(shape: Shape) -> &'static str {
    match shape {
        Shape::Cube => "Cube",
        Shape::Sphere => "Sphere",
        Shape::Cylinder => "Cylinder",
        Shape::Cone => "Cone",
        Shape::Torus => "Torus",
        Shape::Plane => "Plane",
    }
}

#[cfg(feature = "physics")]
fn dynamic_collider(world: &World, shape: Shape, scale: Vec3) -> ColliderComponent {
    match shape {
        Shape::Cube => ColliderComponent::new_cuboid(scale.x * 0.5, scale.y * 0.5, scale.z * 0.5),
        Shape::Sphere => ColliderComponent::new_ball(scale.x),
        Shape::Cylinder => ColliderComponent::new_cylinder(scale.y * 0.5, scale.x * 0.5),
        Shape::Cone => ColliderComponent::new_cone(scale.y * 0.5, scale.x * 0.5),
        Shape::Torus => ColliderComponent {
            shape: ColliderShape::ConvexMesh {
                vertices: scaled_mesh_points(world, "Torus", scale),
            },
            ..Default::default()
        },
        Shape::Plane => ColliderComponent::new_cuboid(scale.x, 0.05, scale.z),
    }
}

#[cfg(feature = "physics")]
fn static_collider(world: &World, shape: Shape, scale: Vec3) -> ColliderComponent {
    match shape {
        Shape::Torus | Shape::Plane => {
            let shape_mesh_name = mesh_name(shape);
            ColliderComponent {
                shape: ColliderShape::TriMesh {
                    vertices: scaled_mesh_points(world, shape_mesh_name, scale),
                    indices: mesh_triangles(world, shape_mesh_name),
                },
                ..Default::default()
            }
        }
        _ => dynamic_collider(world, shape, scale),
    }
}

#[cfg(feature = "physics")]
fn scaled_mesh_points(world: &World, mesh_name: &str, scale: Vec3) -> Vec<[f32; 3]> {
    registry_entry_by_name(&world.resources.assets.mesh_cache.registry, mesh_name)
        .map(|mesh| {
            mesh.vertices
                .iter()
                .map(|vertex| {
                    [
                        vertex.position[0] * scale.x,
                        vertex.position[1] * scale.y,
                        vertex.position[2] * scale.z,
                    ]
                })
                .collect()
        })
        .unwrap_or_default()
}

#[cfg(feature = "physics")]
fn mesh_triangles(world: &World, mesh_name: &str) -> Vec<[u32; 3]> {
    registry_entry_by_name(&world.resources.assets.mesh_cache.registry, mesh_name)
        .map(|mesh| {
            mesh.indices
                .chunks_exact(3)
                .map(|triangle| [triangle[0], triangle[1], triangle[2]])
                .collect()
        })
        .unwrap_or_default()
}

#[cfg(feature = "physics")]
fn attach_body(
    world: &mut World,
    entity: Entity,
    body: RigidBodyComponent,
    collider: ColliderComponent,
    dynamic: bool,
) {
    let mut flags = RIGID_BODY | COLLIDER;
    if dynamic {
        flags |= COLLISION_LISTENER | PHYSICS_INTERPOLATION;
    }
    world.core.add_components(entity, flags);
    world.core.set_rigid_body(entity, body);
    world.core.set_collider(entity, collider);
    if dynamic {
        reset_physics_interpolation(world, entity);
        if let Some(interpolation) = world.core.get_physics_interpolation_mut(entity) {
            interpolation.enabled = true;
        }
    }
}