tirbofish/dropbear
main / crates / eucalyptus-core / src / ser / model.rs · 14362 bytes
crates/eucalyptus-core/src/ser/model.rs
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
use dropbear_engine::asset::{ASSET_REGISTRY, Handle};
use dropbear_engine::buffer::DynamicBuffer;
use dropbear_engine::graphics::SharedGraphicsContext;
use dropbear_engine::model::{
AlphaMode, Animation, Material, Mesh, Model, ModelVertex, Node, Skin,
};
use dropbear_engine::texture::{Texture, TextureWrapMode};
use dropbear_engine::utils::ResourceReference;
use dropbear_engine::wgpu;
use dropbear_engine::wgpu::util::DeviceExt;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use uuid::Uuid;
use crate::uuid::UuidV4;
/// How a texture is referenced inside a compiled model (`.eucmdl`).
///
/// `AssetUuid` is the canonical form for any texture that lives on disk and has
/// a `.eucmeta` sidecar. `Embedded` is used for textures that were packed
/// directly inside a source file (e.g. GLTF-embedded data) and have not yet
/// been extracted as standalone assets.
#[derive(
rkyv::Archive,
rkyv::Serialize,
rkyv::Deserialize,
Debug,
Clone,
serde::Serialize,
serde::Deserialize,
)]
pub enum EucalyptusTextureRef {
/// UUID of a file-backed texture tracked by a `.eucmeta` sidecar.
AssetUuid(UuidV4),
/// Raw image bytes embedded directly in the model file.
Embedded(Arc<[u8]>),
}
impl EucalyptusTextureRef {
/// Constructs from a `uuid::Uuid`.
pub fn from_uuid(uuid: Uuid) -> Self {
Self::AssetUuid(UuidV4::from(uuid))
}
}
/// The serialized format for a Model without all the buffers and stuff.
///
/// This is stored in the file system as `*.eucmdl`.
#[derive(
rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Debug, serde::Serialize, serde::Deserialize,
)]
pub struct EucalyptusModel {
pub label: String,
pub meshes: Vec<EucalyptusMesh>, // this needs to be custom type because of wgpu buffers
pub materials: Vec<EucalyptusMaterial>, // same here
pub skins: Vec<Skin>,
pub animations: Vec<Animation>,
pub nodes: Vec<Node>,
pub morph_deltas: Vec<f32>,
}
impl EucalyptusModel {
/// Loads the [`EucalyptusModel`] as a [`Model`] by loading the buffers.
pub fn load(&self, source: ResourceReference, graphics: Arc<SharedGraphicsContext>) -> Model {
let materials = self
.materials
.iter()
.map(|material| material.load(graphics.clone()))
.collect::<Vec<_>>();
let meshes = self
.meshes
.iter()
.map(|mesh| mesh.load(graphics.clone()))
.collect::<Vec<_>>();
let morph_deltas_buffer = if self.morph_deltas.is_empty() {
None
} else {
Some(
graphics
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("model morph deltas buffer"),
contents: bytemuck::cast_slice(&self.morph_deltas),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
}),
)
};
Model {
hash: self.runtime_hash(&source),
label: self.label.clone(),
path: source,
meshes,
materials,
skins: self.skins.clone(),
animations: self.animations.clone(),
nodes: self.nodes.clone(),
morph_deltas_buffer,
}
}
fn runtime_hash(&self, source: &ResourceReference) -> u64 {
let mut hasher = DefaultHasher::default();
source.hash(&mut hasher);
self.label.hash(&mut hasher);
self.meshes.len().hash(&mut hasher);
self.materials.len().hash(&mut hasher);
self.nodes.len().hash(&mut hasher);
for mesh in &self.meshes {
mesh.name.hash(&mut hasher);
mesh.num_elements.hash(&mut hasher);
mesh.vertices.len().hash(&mut hasher);
mesh.material.hash(&mut hasher);
}
hasher.finish()
}
}
impl From<Model> for EucalyptusModel {
fn from(value: Model) -> Self {
Self {
label: value.label.clone(),
meshes: value.meshes.into_iter().map(EucalyptusMesh::from).collect(),
materials: value
.materials
.into_iter()
.map(EucalyptusMaterial::from)
.collect(),
skins: value.skins,
animations: value.animations,
nodes: value.nodes,
morph_deltas: Vec::new(),
}
}
}
#[derive(
rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Debug, serde::Serialize, serde::Deserialize,
)]
pub struct EucalyptusMesh {
pub name: String,
pub num_elements: u32,
pub material: usize,
pub vertices: Vec<ModelVertex>,
pub morph_deltas_offset: u32,
pub morph_target_count: u32,
pub morph_vertex_count: u32,
pub morph_default_weights: Vec<f32>,
}
impl From<Mesh> for EucalyptusMesh {
fn from(value: Mesh) -> Self {
Self {
name: value.name,
num_elements: value.num_elements,
material: value.material,
vertices: value.vertex_buffer.into_data(),
morph_deltas_offset: value.morph_deltas_offset,
morph_target_count: value.morph_target_count,
morph_vertex_count: value.morph_vertex_count,
morph_default_weights: value.morph_default_weights,
}
}
}
impl EucalyptusMesh {
fn load(&self, graphics: Arc<SharedGraphicsContext>) -> Mesh {
let vertex_buffer = DynamicBuffer::from_slice(
&graphics.device,
&self.vertices,
wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
&format!("{} Vertex Buffer", self.name),
);
let index_count = self.num_elements.min(self.vertices.len() as u32);
let indices = (0..index_count).collect::<Vec<u32>>();
let index_buffer = DynamicBuffer::from_slice(
&graphics.device,
&indices,
wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
&format!("{} Index Buffer", self.name),
);
Mesh {
name: self.name.clone(),
vertex_buffer,
index_buffer,
num_elements: index_count,
material: self.material,
morph_deltas_offset: self.morph_deltas_offset,
morph_target_count: self.morph_target_count,
morph_vertex_count: self.morph_vertex_count,
morph_default_weights: self.morph_default_weights.clone(),
}
}
}
#[derive(
rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Debug, serde::Serialize, serde::Deserialize,
)]
pub struct EucalyptusMaterial {
pub name: String,
pub diffuse_texture: Option<EucalyptusTextureRef>,
pub normal_texture: Option<EucalyptusTextureRef>,
pub emissive_texture: Option<EucalyptusTextureRef>,
pub metallic_roughness_texture: Option<EucalyptusTextureRef>,
pub occlusion_texture: Option<EucalyptusTextureRef>,
pub tint: [f32; 4],
pub emissive_factor: [f32; 3],
pub metallic_factor: f32,
pub roughness_factor: f32,
pub alpha_mode: AlphaMode,
pub alpha_cutoff: Option<f32>,
pub occlusion_strength: f32,
pub normal_scale: f32,
pub uv_tiling: [f32; 2],
pub texture_tag: Option<String>,
pub wrap_mode: TextureWrapMode,
}
impl From<Material> for EucalyptusMaterial {
fn from(value: Material) -> Self {
let project_root = crate::states::PROJECT.read().project_path.clone();
let get_texture = |tex: Option<Handle<Texture>>| -> Option<EucalyptusTextureRef> {
let tex = tex?;
let registry = ASSET_REGISTRY.read();
let t = registry.get_texture(tex)?;
match t.reference.clone()? {
ResourceReference::File(rel) if !rel.is_empty() => {
let abs = project_root.join("resources").join(&rel);
crate::metadata::generate_eucmeta(&abs, &project_root)
.ok()
.map(|entry| EucalyptusTextureRef::from_uuid(entry.uuid))
}
ResourceReference::Embedded(bytes) => Some(EucalyptusTextureRef::Embedded(bytes)),
_ => None,
}
};
Self {
name: value.name,
diffuse_texture: get_texture(Some(value.diffuse_texture)),
normal_texture: get_texture(value.normal_texture),
emissive_texture: get_texture(value.emissive_texture),
metallic_roughness_texture: get_texture(value.metallic_roughness_texture),
occlusion_texture: get_texture(value.occlusion_texture),
tint: value.base_colour,
emissive_factor: value.emissive_factor,
metallic_factor: value.metallic_factor,
roughness_factor: value.roughness_factor,
alpha_mode: value.alpha_mode,
alpha_cutoff: value.alpha_cutoff,
occlusion_strength: value.occlusion_strength,
normal_scale: value.normal_scale,
uv_tiling: value.uv_tiling,
texture_tag: value.texture_tag,
wrap_mode: value.wrap_mode,
}
}
}
impl EucalyptusMaterial {
fn load_texture(
&self,
graphics: Arc<SharedGraphicsContext>,
reference: &EucalyptusTextureRef,
suffix: &str,
) -> Option<Handle<Texture>> {
match reference {
EucalyptusTextureRef::AssetUuid(uuid_v4) => {
let uuid = uuid_v4.as_uuid();
let project_root = crate::states::PROJECT.read().project_path.clone();
let entry = crate::metadata::find_asset_by_uuid(&project_root, uuid)
.map_err(|e| log::warn!("load_texture: UUID {} not found: {}", uuid, e))
.ok()?;
if let crate::resource::ResourceReference::File(rel) = &entry.location {
let abs = project_root.join(rel);
// Dedup: return cached handle if already loaded.
if let Ok(engine_ref) = ResourceReference::from_path(&abs) {
let registry = ASSET_REGISTRY.read();
if let Some(h) = registry.get_texture_handle_by_reference(&engine_ref) {
return Some(h);
}
}
let bytes = std::fs::read(&abs)
.map_err(|e| {
log::warn!("load_texture: failed to read '{}': {}", abs.display(), e)
})
.ok()?;
let label = format!("{}_{}", self.name, suffix);
let engine_ref = ResourceReference::from_path(&abs).ok();
let mut texture =
dropbear_engine::texture::TextureBuilder::new(&graphics.device)
.with_bytes(graphics.clone(), bytes.as_slice())
.label(label.as_str())
.build();
texture.reference = engine_ref;
let mut registry = ASSET_REGISTRY.write();
Some(registry.add_texture_with_label(entry.name, texture))
} else {
log::warn!("load_texture: UUID {} has no file-backed location", uuid);
None
}
}
EucalyptusTextureRef::Embedded(bytes) => {
let label = format!("{}_{}", self.name, suffix);
let texture = dropbear_engine::texture::TextureBuilder::new(&graphics.device)
.with_bytes(graphics.clone(), bytes)
.label(label.as_str())
.build();
let mut registry = ASSET_REGISTRY.write();
Some(registry.add_texture(texture))
}
}
}
fn load(&self, graphics: Arc<SharedGraphicsContext>) -> Material {
let diffuse_texture = {
let maybe = self
.diffuse_texture
.as_ref()
.and_then(|r| self.load_texture(graphics.clone(), r, "diffuse"));
if let Some(handle) = maybe {
handle
} else {
ASSET_REGISTRY.write().solid_texture_rgba8(
graphics.clone(),
[255, 255, 255, 255],
Some(Texture::TEXTURE_FORMAT_BASE.add_srgb_suffix()),
)
}
};
let normal_texture = self
.normal_texture
.as_ref()
.and_then(|reference| self.load_texture(graphics.clone(), reference, "normal"));
let emissive_texture = self
.emissive_texture
.as_ref()
.and_then(|reference| self.load_texture(graphics.clone(), reference, "emissive"));
let metallic_roughness_texture =
self.metallic_roughness_texture
.as_ref()
.and_then(|reference| {
self.load_texture(graphics.clone(), reference, "metallic_roughness")
});
let occlusion_texture = self
.occlusion_texture
.as_ref()
.and_then(|reference| self.load_texture(graphics.clone(), reference, "occlusion"));
let mut registry = ASSET_REGISTRY.write();
let mut material = Material::new(
&mut registry,
graphics.clone(),
self.name.clone(),
diffuse_texture,
normal_texture,
emissive_texture,
metallic_roughness_texture,
occlusion_texture,
self.tint,
self.texture_tag.clone(),
);
material.emissive_factor = self.emissive_factor;
material.metallic_factor = self.metallic_factor;
material.roughness_factor = self.roughness_factor;
material.alpha_mode = self.alpha_mode;
material.alpha_cutoff = self.alpha_cutoff;
material.occlusion_strength = self.occlusion_strength;
material.normal_scale = self.normal_scale;
material.uv_tiling = self.uv_tiling;
material.wrap_mode = self.wrap_mode;
material.sync_uniform(&graphics);
material
}
}