nightshade 0.8.0

A cross-platform data-oriented 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
//! Mesh component definitions.

mod instanced;
mod primitives;

pub use instanced::*;
pub use primitives::*;

use crate::ecs::asset_id::MeshId;
use nalgebra_glm::Vec3;
use serde::{Deserialize, Serialize};

/// Component referencing a mesh by name in the mesh cache.
///
/// The `id` field is populated by the rendering system when the mesh is uploaded
/// to the GPU. The name is used to look up the mesh data in the cache.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RenderMesh {
    /// Name of the mesh in the mesh cache.
    pub name: String,
    /// GPU mesh identifier, set by the renderer after upload.
    #[serde(skip)]
    pub id: Option<MeshId>,
}

impl RenderMesh {
    /// Creates a new mesh reference by name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            id: None,
        }
    }

    /// Creates a mesh reference with a pre-assigned GPU identifier.
    pub fn with_id(name: impl Into<String>, id: MeshId) -> Self {
        Self {
            name: name.into(),
            id: Some(id),
        }
    }
}

impl Default for RenderMesh {
    fn default() -> Self {
        Self {
            name: "Cube".to_string(),
            id: None,
        }
    }
}

impl From<String> for RenderMesh {
    fn from(name: String) -> Self {
        Self { name, id: None }
    }
}

impl From<&str> for RenderMesh {
    fn from(name: &str) -> Self {
        Self {
            name: name.to_string(),
            id: None,
        }
    }
}

/// Built-in geometry primitive types.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GeometryPrimitive {
    Torus,
    Cube,
    Sphere,
    Plane,
    Cone,
    Cylinder,
}

impl std::fmt::Display for GeometryPrimitive {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GeometryPrimitive::Torus => write!(f, "Torus"),
            GeometryPrimitive::Cube => write!(f, "Cube"),
            GeometryPrimitive::Sphere => write!(f, "Sphere"),
            GeometryPrimitive::Plane => write!(f, "Plane"),
            GeometryPrimitive::Cone => write!(f, "Cone"),
            GeometryPrimitive::Cylinder => write!(f, "Cylinder"),
        }
    }
}

/// Standard vertex format for static meshes.
///
/// Layout matches the GPU vertex buffer format. Supports two UV sets,
/// tangent space for normal mapping, and per-vertex color.
#[repr(C)]
#[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable, Serialize, Deserialize)]
pub struct Vertex {
    /// Vertex position in local space.
    pub position: [f32; 3],
    /// Surface normal (should be normalized).
    pub normal: [f32; 3],
    /// Primary texture coordinates (UV0).
    pub tex_coords: [f32; 2],
    /// Secondary texture coordinates (UV1) for lightmaps or detail textures.
    pub tex_coords_1: [f32; 2],
    /// Tangent vector with handedness in W component (±1).
    pub tangent: [f32; 4],
    /// Per-vertex RGBA color.
    pub color: [f32; 4],
}

impl Vertex {
    /// Creates a vertex with position and normal, using default values for other attributes.
    pub fn new(position: Vec3, normal: Vec3) -> Self {
        Self {
            position: [position.x, position.y, position.z],
            normal: [normal.x, normal.y, normal.z],
            tex_coords: [0.0, 0.0],
            tex_coords_1: [0.0, 0.0],
            tangent: [1.0, 0.0, 0.0, 1.0],
            color: [1.0, 1.0, 1.0, 1.0],
        }
    }

    /// Creates a vertex with position, normal, and primary texture coordinates.
    pub fn with_tex_coords(position: Vec3, normal: Vec3, tex_coords: [f32; 2]) -> Self {
        Self {
            position: [position.x, position.y, position.z],
            normal: [normal.x, normal.y, normal.z],
            tex_coords,
            tex_coords_1: [0.0, 0.0],
            tangent: [1.0, 0.0, 0.0, 1.0],
            color: [1.0, 1.0, 1.0, 1.0],
        }
    }

    /// Creates a vertex with position, normal, texture coordinates, and tangent.
    pub fn with_tangent(
        position: Vec3,
        normal: Vec3,
        tex_coords: [f32; 2],
        tangent: [f32; 4],
    ) -> Self {
        Self {
            position: [position.x, position.y, position.z],
            normal: [normal.x, normal.y, normal.z],
            tex_coords,
            tex_coords_1: [0.0, 0.0],
            tangent,
            color: [1.0, 1.0, 1.0, 1.0],
        }
    }

    /// Creates a vertex with all attributes explicitly specified.
    pub fn with_all(
        position: Vec3,
        normal: Vec3,
        tex_coords: [f32; 2],
        tex_coords_1: [f32; 2],
        tangent: [f32; 4],
        color: [f32; 4],
    ) -> Self {
        Self {
            position: [position.x, position.y, position.z],
            normal: [normal.x, normal.y, normal.z],
            tex_coords,
            tex_coords_1,
            tangent,
            color,
        }
    }
}

/// Vertex format for skeletal animation with joint influences.
///
/// Extends [`Vertex`] with joint indices and weights for GPU skinning.
/// Each vertex can be influenced by up to 4 joints.
#[repr(C)]
#[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable, Serialize, Deserialize)]
pub struct SkinnedVertex {
    /// Vertex position in local space.
    pub position: [f32; 3],
    /// Surface normal (should be normalized).
    pub normal: [f32; 3],
    /// Primary texture coordinates (UV0).
    pub tex_coords: [f32; 2],
    /// Secondary texture coordinates (UV1).
    pub tex_coords_1: [f32; 2],
    /// Tangent vector with handedness in W component.
    pub tangent: [f32; 4],
    /// Per-vertex RGBA color.
    pub color: [f32; 4],
    /// Indices of influencing joints (up to 4).
    pub joint_indices: [u32; 4],
    /// Blend weights for each joint (should sum to 1.0).
    pub joint_weights: [f32; 4],
}

impl SkinnedVertex {
    /// Creates a skinned vertex with position, normal, UVs, and joint data.
    pub fn new(
        position: Vec3,
        normal: Vec3,
        tex_coords: [f32; 2],
        joint_indices: [u32; 4],
        joint_weights: [f32; 4],
    ) -> Self {
        Self {
            position: [position.x, position.y, position.z],
            normal: [normal.x, normal.y, normal.z],
            tex_coords,
            tex_coords_1: [0.0, 0.0],
            tangent: [1.0, 0.0, 0.0, 1.0],
            color: [1.0, 1.0, 1.0, 1.0],
            joint_indices,
            joint_weights,
        }
    }

    /// Creates a skinned vertex with all attributes explicitly specified.
    pub fn with_all(
        position: Vec3,
        normal: Vec3,
        tex_coords: [f32; 2],
        tex_coords_1: [f32; 2],
        tangent: [f32; 4],
        color: [f32; 4],
        joints: ([u32; 4], [f32; 4]),
    ) -> Self {
        Self {
            position: [position.x, position.y, position.z],
            normal: [normal.x, normal.y, normal.z],
            tex_coords,
            tex_coords_1,
            tangent,
            color,
            joint_indices: joints.0,
            joint_weights: joints.1,
        }
    }
}

impl Default for SkinnedVertex {
    fn default() -> Self {
        Self {
            position: [0.0, 0.0, 0.0],
            normal: [0.0, 1.0, 0.0],
            tex_coords: [0.0, 0.0],
            tex_coords_1: [0.0, 0.0],
            tangent: [1.0, 0.0, 0.0, 1.0],
            color: [1.0, 1.0, 1.0, 1.0],
            joint_indices: [0, 0, 0, 0],
            joint_weights: [1.0, 0.0, 0.0, 0.0],
        }
    }
}

/// A single morph target (blend shape) with vertex displacements.
///
/// Morph targets deform the base mesh by adding weighted displacements
/// to vertex positions, normals, and/or tangents.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MorphTarget {
    /// Position offsets for each vertex.
    pub position_displacements: Vec<[f32; 3]>,
    /// Normal offsets for each vertex (optional).
    pub normal_displacements: Option<Vec<[f32; 3]>>,
    /// Tangent offsets for each vertex (optional).
    pub tangent_displacements: Option<Vec<[f32; 3]>>,
}

impl MorphTarget {
    /// Creates a morph target with position displacements only.
    pub fn new(position_displacements: Vec<[f32; 3]>) -> Self {
        Self {
            position_displacements,
            normal_displacements: None,
            tangent_displacements: None,
        }
    }

    /// Adds normal displacements to the morph target.
    pub fn with_normals(mut self, normal_displacements: Vec<[f32; 3]>) -> Self {
        self.normal_displacements = Some(normal_displacements);
        self
    }

    /// Adds tangent displacements to the morph target.
    pub fn with_tangents(mut self, tangent_displacements: Vec<[f32; 3]>) -> Self {
        self.tangent_displacements = Some(tangent_displacements);
        self
    }
}

/// Collection of morph targets for a mesh.
///
/// Contains all morph targets plus base mesh data needed for blending.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MorphTargetData {
    /// All morph targets for this mesh.
    pub targets: Vec<MorphTarget>,
    /// Default blend weights from the source asset.
    pub default_weights: Vec<f32>,
    /// Base mesh positions (before any morph deformation).
    pub base_positions: Vec<[f32; 3]>,
    /// Base mesh normals (before any morph deformation).
    pub base_normals: Vec<[f32; 3]>,
}

impl MorphTargetData {
    /// Creates morph target data with the given targets and default weights of 1.0.
    pub fn new(targets: Vec<MorphTarget>) -> Self {
        let default_weights = vec![1.0; targets.len()];
        Self {
            targets,
            default_weights,
            base_positions: Vec::new(),
            base_normals: Vec::new(),
        }
    }

    /// Sets the default blend weights for all targets.
    pub fn with_default_weights(mut self, weights: Vec<f32>) -> Self {
        self.default_weights = weights;
        self
    }

    /// Sets the base mesh positions and normals for CPU blending.
    pub fn with_base_data(mut self, positions: Vec<[f32; 3]>, normals: Vec<[f32; 3]>) -> Self {
        self.base_positions = positions;
        self.base_normals = normals;
        self
    }

    /// Returns the number of morph targets.
    pub fn target_count(&self) -> usize {
        self.targets.len()
    }
}

/// Skinning data for skeletal animation.
///
/// Contains the skinned vertex data and optionally references a skin definition
/// (joint hierarchy) by index.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkinData {
    /// Vertices with joint indices and weights.
    pub skinned_vertices: Vec<SkinnedVertex>,
    /// Index into the skin definitions array (from glTF or other source).
    pub skin_index: Option<usize>,
}

impl SkinData {
    /// Creates skin data with the given vertices.
    pub fn new(skinned_vertices: Vec<SkinnedVertex>) -> Self {
        Self {
            skinned_vertices,
            skin_index: None,
        }
    }

    /// Associates this skin data with a skin definition by index.
    pub fn with_skin_index(mut self, skin_index: usize) -> Self {
        self.skin_index = Some(skin_index);
        self
    }
}

/// CPU-side mesh data ready for GPU upload.
///
/// Contains geometry data (vertices and indices), optional bounding volume,
/// optional skinning data for skeletal animation, and optional morph targets.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Mesh {
    /// Vertex array with positions, normals, UVs, tangents, and colors.
    pub vertices: Vec<Vertex>,
    /// Triangle indices (3 per triangle).
    pub indices: Vec<u32>,
    /// Precomputed bounding volume for culling.
    pub bounding_volume: Option<crate::ecs::bounding_volume::components::BoundingVolume>,
    /// Skinning data for skeletal animation.
    pub skin_data: Option<SkinData>,
    /// Morph target data for blend shapes.
    pub morph_targets: Option<MorphTargetData>,
}

impl Mesh {
    /// Creates a mesh from vertices and indices.
    pub fn new(vertices: Vec<Vertex>, indices: Vec<u32>) -> Self {
        Self {
            vertices,
            indices,
            bounding_volume: None,
            skin_data: None,
            morph_targets: None,
        }
    }

    /// Creates a mesh with a precomputed bounding volume.
    pub fn with_bounding_volume(
        vertices: Vec<Vertex>,
        indices: Vec<u32>,
        bounding_volume: crate::ecs::bounding_volume::components::BoundingVolume,
    ) -> Self {
        Self {
            vertices,
            indices,
            bounding_volume: Some(bounding_volume),
            skin_data: None,
            morph_targets: None,
        }
    }

    /// Adds skinning data for skeletal animation.
    pub fn with_skin_data(mut self, skin_data: SkinData) -> Self {
        self.skin_data = Some(skin_data);
        self
    }

    /// Adds morph target data for blend shapes.
    pub fn with_morph_targets(mut self, morph_targets: MorphTargetData) -> Self {
        self.morph_targets = Some(morph_targets);
        self
    }

    /// Returns `true` if this mesh has skinning data.
    pub fn is_skinned(&self) -> bool {
        self.skin_data.is_some()
    }

    /// Returns `true` if this mesh has morph targets.
    pub fn has_morph_targets(&self) -> bool {
        self.morph_targets.is_some()
    }

    /// Returns the number of morph targets, or 0 if none.
    pub fn morph_target_count(&self) -> usize {
        self.morph_targets
            .as_ref()
            .map(|m| m.target_count())
            .unwrap_or(0)
    }
}