use super::*;
impl Euv3dSectionKind {
#[must_use]
pub const fn from_u32(raw: u32) -> Option<Self> {
match raw {
1 => Some(Self::SceneMetadataJson),
2 => Some(Self::Vertices),
3 => Some(Self::Indices),
4 => Some(Self::SkinInfluences),
5 => Some(Self::MorphDeltas),
6 => Some(Self::Meshlets),
7 => Some(Self::LodTable),
8 => Some(Self::Bvh4Nodes),
9 => Some(Self::BvhTri4Packets),
10 => Some(Self::BvhTriangles),
11 => Some(Self::AnimationsBlob),
12 => Some(Self::TexturesBlob),
_ => None,
}
}
#[must_use]
pub const fn to_u32(&self) -> u32 {
*self as u32
}
}
impl Default for Euv3dBakeConfig {
fn default() -> Self {
Self {
lod_levels: EUV3D_DEFAULT_LOD_LEVELS,
build_meshlets: true,
bake_bvh4: true,
generate_mipmaps: true,
}
}
}
impl QemMatrix {
#[must_use]
pub(crate) fn from_plane(a: f64, b: f64, c: f64, d: f64) -> Self {
Self {
coeffs: [
a * a,
a * b,
a * c,
a * d,
b * b,
b * c,
b * d,
c * c,
c * d,
d * d,
],
}
}
#[must_use]
pub(crate) fn add(&self, other: Self) -> Self {
let Self { coeffs: a } = *self;
let Self { coeffs: b } = other;
Self {
coeffs: [
a[0] + b[0],
a[1] + b[1],
a[2] + b[2],
a[3] + b[3],
a[4] + b[4],
a[5] + b[5],
a[6] + b[6],
a[7] + b[7],
a[8] + b[8],
a[9] + b[9],
],
}
}
#[must_use]
pub(crate) fn scale(&self, factor: f64) -> Self {
let Self { coeffs: a } = *self;
Self {
coeffs: [
a[0] * factor,
a[1] * factor,
a[2] * factor,
a[3] * factor,
a[4] * factor,
a[5] * factor,
a[6] * factor,
a[7] * factor,
a[8] * factor,
a[9] * factor,
],
}
}
#[must_use]
pub(crate) fn evaluate(&self, pos: [f64; 3]) -> f64 {
let Self { coeffs: q } = *self;
let x: f64 = pos[0];
let y: f64 = pos[1];
let z: f64 = pos[2];
q[0] * x * x
+ 2.0 * q[1] * x * y
+ 2.0 * q[2] * x * z
+ 2.0 * q[3] * x
+ q[4] * y * y
+ 2.0 * q[5] * y * z
+ 2.0 * q[6] * y
+ q[7] * z * z
+ 2.0 * q[8] * z
+ q[9]
}
#[must_use]
pub(crate) fn solve_optimal(&self) -> Option<[f64; 3]> {
let Self { coeffs: q } = *self;
let a00: f64 = q[0];
let a01: f64 = q[1];
let a02: f64 = q[2];
let a11: f64 = q[4];
let a12: f64 = q[5];
let a22: f64 = q[7];
let c00: f64 = a11 * a22 - a12 * a12;
let c01: f64 = -(a01 * a22 - a12 * a02);
let c02: f64 = a01 * a12 - a11 * a02;
let det: f64 = a00 * c00 + a01 * c01 + a02 * c02;
if det.abs() <= EUV3D_QEM_EPSILON {
return None;
}
let c11: f64 = a00 * a22 - a02 * a02;
let c12: f64 = -(a00 * a12 - a01 * a02);
let c22: f64 = a00 * a11 - a01 * a01;
let bx: f64 = -q[3];
let by: f64 = -q[6];
let bz: f64 = -q[8];
let inv_det: f64 = 1.0 / det;
let rx: f64 = (c00 * bx + c01 * by + c02 * bz) * inv_det;
let ry: f64 = (c01 * bx + c11 * by + c12 * bz) * inv_det;
let rz: f64 = (c02 * bx + c12 * by + c22 * bz) * inv_det;
if rx.is_finite() && ry.is_finite() && rz.is_finite() {
Some([rx, ry, rz])
} else {
None
}
}
}
impl<'a> Euv3dPackageView<'a> {
pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, String> {
if bytes.len() < EUV3D_HEADER_BYTES {
return Err(ERR_EUV3D_TOO_SHORT.to_string());
}
if bytes[..8] != EUV3D_MAGIC {
return Err(ERR_EUV3D_BAD_MAGIC.to_string());
}
let version: u32 = read_u32_le(bytes, 8)?;
if version != EUV3D_FORMAT_VERSION {
return Err(ERR_EUV3D_BAD_VERSION.to_string());
}
let flags: u32 = read_u32_le(bytes, 12)?;
let section_count: u32 = read_u32_le(bytes, 16)?;
let table_offset: u64 = read_u64_le(bytes, 24)?;
let content_crc32: u32 = read_u32_le(bytes, 32)?;
let header_crc32: u32 = read_u32_le(bytes, 36)?;
let total_bytes: u64 = read_u64_le(bytes, 40)?;
let digest_fnv1a: u64 = read_u64_le(bytes, 48)?;
if (total_bytes as usize) != bytes.len() {
return Err(ERR_EUV3D_SIZE_MISMATCH.to_string());
}
if compute_crc32(&bytes[..36]) != header_crc32 {
return Err(ERR_EUV3D_CRC_MISMATCH.to_string());
}
if compute_crc32(&bytes[EUV3D_HEADER_BYTES..]) != content_crc32 {
return Err(ERR_EUV3D_CRC_MISMATCH.to_string());
}
let table_start: usize = table_offset as usize;
let table_bytes: usize = (section_count as usize)
.checked_mul(EUV3D_SECTION_ENTRY_BYTES)
.ok_or_else(|| ERR_EUV3D_TABLE_OOB.to_string())?;
let table_end: usize = table_start
.checked_add(table_bytes)
.ok_or_else(|| ERR_EUV3D_TABLE_OOB.to_string())?;
if table_start < EUV3D_HEADER_BYTES || table_end > bytes.len() {
return Err(ERR_EUV3D_TABLE_OOB.to_string());
}
let mut sections: Vec<Euv3dSectionEntry> = Vec::with_capacity(section_count as usize);
for idx in 0..(section_count as usize) {
let entry_off: usize = table_start + idx * EUV3D_SECTION_ENTRY_BYTES;
let raw_kind: u32 = read_u32_le(bytes, entry_off)?;
let kind: Euv3dSectionKind = Euv3dSectionKind::from_u32(raw_kind)
.ok_or_else(|| ERR_EUV3D_UNKNOWN_SECTION.to_string())?;
let sec_flags: u32 = read_u32_le(bytes, entry_off + 4)?;
let offset: u64 = read_u64_le(bytes, entry_off + 8)?;
let byte_length: u64 = read_u64_le(bytes, entry_off + 16)?;
let element_count: u32 = read_u32_le(bytes, entry_off + 24)?;
if !(offset as usize).is_multiple_of(EUV3D_SECTION_ALIGNMENT) {
return Err(ERR_EUV3D_UNALIGNED_SECTION.to_string());
}
let sec_end: usize = (offset as usize)
.checked_add(byte_length as usize)
.ok_or_else(|| ERR_EUV3D_SECTION_OOB.to_string())?;
if sec_end > bytes.len() {
return Err(ERR_EUV3D_SECTION_OOB.to_string());
}
sections.push(Euv3dSectionEntry {
kind,
offset,
byte_length,
element_count,
flags: sec_flags,
});
}
let header: Euv3dHeader = Euv3dHeader {
version,
flags,
section_count,
table_offset,
content_crc32,
total_bytes,
digest_fnv1a,
};
Ok(Self {
raw_bytes: bytes,
header,
sections,
})
}
#[must_use]
pub fn section_entry(&self, kind: Euv3dSectionKind) -> Option<Euv3dSectionEntry> {
for entry in self.get_sections().iter() {
if entry.get_kind() == kind {
return Some(*entry);
}
}
None
}
#[must_use]
pub fn section_bytes(&self, kind: Euv3dSectionKind) -> Option<&'a [u8]> {
let Self { raw_bytes, .. } = self;
let entry: Euv3dSectionEntry = self.section_entry(kind)?;
let start: usize = entry.get_offset() as usize;
let end: usize = start + (entry.get_byte_length() as usize);
raw_bytes.get(start..end)
}
}
impl Euv3dPackage {
pub fn bake_from_scene(
scene: &ImportedScene3D,
config: &Euv3dBakeConfig,
) -> Result<Vec<u8>, String> {
let mut vertices_blob: Vec<u8> = Vec::new();
let mut vertex_total: u32 = 0;
let mut indices_blob: Vec<u8> = Vec::new();
let mut tri_total: u32 = 0;
let mut skins_blob: Vec<u8> = Vec::new();
let mut skin_total: u32 = 0;
let mut morph_blob: Vec<u8> = Vec::new();
let mut morph_vec_total: u32 = 0;
let mut meshlets_blob: Vec<u8> = Vec::new();
let mut meshlet_total: u32 = 0;
let mut bvh4_blob: Vec<u8> = Vec::new();
let mut bvh4_total: u32 = 0;
let mut bvh_pkt_blob: Vec<u8> = Vec::new();
let mut bvh_pkt_total: u32 = 0;
let mut bvh_tri_blob: Vec<u8> = Vec::new();
let mut bvh_tri_total: u32 = 0;
let mut anim_blob: Vec<u8> = Vec::new();
let mut anim_float_total: u32 = 0;
let mut tex_blob: Vec<u8> = Vec::new();
let mut mesh_records: Vec<Euv3dMeshRecord> = Vec::with_capacity(scene.get_meshes().len());
let mut bvh_records: Vec<Euv3dBvhRecord> = Vec::with_capacity(scene.get_meshes().len());
let max_lods: usize = config.get_lod_levels().clamp(1, EUV3D_DEFAULT_LOD_LEVELS);
for mesh in scene.get_meshes().iter() {
let chain: MeshLodChain = if max_lods > 1 {
build_qem_lod_chain(mesh, max_lods)
} else {
let mut base: Mesh3D = mesh.clone();
if config.get_build_meshlets() && base.get_tri_materials().is_empty() {
let (reordered, clusters): (Vec<[u32; 3]>, Vec<Meshlet3D>) =
build_spatial_meshlets(base.get_vertices(), base.get_indices());
base.set_indices(reordered);
base.set_meshlets(clusters);
}
MeshLodChain { levels: vec![base] }
};
let mut lod_records: Vec<Euv3dLodRecord> = Vec::with_capacity(chain.get_levels().len());
for lod_mesh in chain.get_levels().iter() {
let first_vertex: u32 = vertex_total;
let vertex_count: u32 = lod_mesh.get_vertices().len() as u32;
for v in lod_mesh.get_vertices().iter() {
push_vertex_bytes(&mut vertices_blob, v);
}
vertex_total += vertex_count;
let first_tri: u32 = tri_total;
let tri_count: u32 = lod_mesh.get_indices().len() as u32;
for tri in lod_mesh.get_indices().iter() {
indices_blob.extend_from_slice(&tri[0].to_le_bytes());
indices_blob.extend_from_slice(&tri[1].to_le_bytes());
indices_blob.extend_from_slice(&tri[2].to_le_bytes());
}
tri_total += tri_count;
let first_meshlet: u32 = meshlet_total;
let meshlet_count: u32 = if config.get_build_meshlets() {
for mlet in lod_mesh.get_meshlets().iter() {
push_meshlet_bytes(&mut meshlets_blob, mlet);
}
lod_mesh.get_meshlets().len() as u32
} else {
0
};
meshlet_total += meshlet_count;
lod_records.push(Euv3dLodRecord {
first_vertex,
vertex_count,
first_tri,
tri_count,
first_meshlet,
meshlet_count,
bounds_min: lod_mesh.get_bounds().get_min().to_array(),
bounds_max: lod_mesh.get_bounds().get_max().to_array(),
});
}
let lod0_ref: &Mesh3D = &chain.get_levels()[0];
let first_skin: u32 = skin_total;
let skin_count: u32 = lod0_ref.get_skin_influences().len() as u32;
for skin in lod0_ref.get_skin_influences().iter() {
push_skin_bytes(&mut skins_blob, skin);
}
skin_total += skin_count;
let mut morph_records: Vec<Euv3dMorphRecord> =
Vec::with_capacity(lod0_ref.get_morph_targets().len());
for target in lod0_ref.get_morph_targets().iter() {
let first_pos: u32 = morph_vec_total;
let pos_count: u32 = target.get_delta_positions().len() as u32;
for d in target.get_delta_positions().iter() {
for lane in *d {
morph_blob.extend_from_slice(&lane.to_le_bytes());
}
}
morph_vec_total += pos_count;
let first_norm: u32 = morph_vec_total;
let norm_count: u32 = target.get_delta_normals().len() as u32;
for d in target.get_delta_normals().iter() {
for lane in *d {
morph_blob.extend_from_slice(&lane.to_le_bytes());
}
}
morph_vec_total += norm_count;
let first_tan: u32 = morph_vec_total;
let tan_count: u32 = target.get_delta_tangents().len() as u32;
for d in target.get_delta_tangents().iter() {
for lane in *d {
morph_blob.extend_from_slice(&lane.to_le_bytes());
}
}
morph_vec_total += tan_count;
morph_records.push(Euv3dMorphRecord {
name: target.get_name().clone(),
first_pos,
pos_count,
first_norm,
norm_count,
first_tan,
tan_count,
});
}
mesh_records.push(Euv3dMeshRecord {
name: lod0_ref.get_name().clone(),
material: pbr_to_record(lod0_ref.get_material()),
sub_materials: lod0_ref
.get_sub_materials()
.iter()
.copied()
.map(pbr_to_record)
.collect(),
tri_materials: lod0_ref.get_tri_materials().clone(),
material_index: lod0_ref.try_get_material_index(),
is_closed: lod0_ref.get_is_closed(),
lods: lod_records,
first_skin,
skin_count,
morphs: morph_records,
});
if config.get_bake_bvh4() {
let bvh: Bvh3D = build_local_mesh_bvh(lod0_ref);
let first_node: u32 = bvh4_total;
let node_count: u32 = bvh.bvh4_nodes.len() as u32;
for node in bvh.bvh4_nodes.iter() {
push_bvh4_node_bytes(&mut bvh4_blob, node);
}
bvh4_total += node_count;
let first_packet: u32 = bvh_pkt_total;
let packet_count: u32 = bvh.leaf_packets.len() as u32;
for pkt in bvh.leaf_packets.iter() {
push_bvh_tri4_bytes(&mut bvh_pkt_blob, pkt);
}
bvh_pkt_total += packet_count;
let first_tri: u32 = bvh_tri_total;
let tri_count: u32 = bvh.get_triangles().len() as u32;
for tri in bvh.get_triangles().iter() {
push_bvh_tri_bytes(&mut bvh_tri_blob, tri);
}
bvh_tri_total += tri_count;
bvh_records.push(Euv3dBvhRecord {
first_node,
node_count,
first_packet,
packet_count,
first_tri,
tri_count,
root_min: bvh.root_min,
root_max: bvh.root_max,
build_sah_cost: bvh.get_build_sah_cost(),
});
}
}
let collections: Vec<Euv3dCollectionRecord> = scene
.get_scene_graph()
.get_collections()
.get_entries()
.iter()
.map(|entry: &CollectionEntry3D| Euv3dCollectionRecord {
name: entry.get_name().clone(),
bit_index: entry.get_bit_index(),
visible_viewport: entry.get_visible_viewport(),
visible_render: entry.get_visible_render(),
})
.collect();
let all_morph_weights: &[f32] = scene.get_scene_graph().get_morph_weights();
let nodes: Vec<Euv3dNodeRecord> = scene
.get_scene_graph()
.get_nodes()
.iter()
.map(|node: &SceneNode3D| {
let w_start: usize = node.get_morph_weight_offset() as usize;
let w_end: usize = (w_start + usize::from(node.get_morph_weight_count()))
.min(all_morph_weights.len());
let morph_weights: Vec<f32> = if w_start < w_end {
all_morph_weights[w_start..w_end].to_vec()
} else {
Vec::new()
};
let extras: &BlenderExtrasTags3D = node.get_extras();
let collider_shape: u8 = match extras.get_collider() {
SceneColliderShape3D::None => 0,
SceneColliderShape3D::Box => 1,
SceneColliderShape3D::Sphere => 2,
SceneColliderShape3D::ConvexHull => 3,
SceneColliderShape3D::Mesh => 4,
};
Euv3dNodeRecord {
name: node.get_name().clone(),
parent: node.try_get_parent(),
translation: node.get_local_translation().to_array(),
rotation: node.get_local_rotation().to_array(),
scale: node.get_local_scale().to_array(),
mesh_id: node.try_get_mesh_id(),
skin_id: node.try_get_skin_id(),
camera_id: node.try_get_camera_id(),
light_id: node.try_get_light_id(),
collection_mask: node.get_collection_mask(),
visible: node.get_visible(),
morph_weights,
collider_shape,
buoyancy_density: extras.get_buoyancy_density(),
is_trigger: extras.get_is_trigger(),
cast_shadows: extras.get_cast_shadows(),
custom_json: extras.try_get_custom_json().clone(),
}
})
.collect();
let materials: Vec<Euv3dMaterialRecord> = scene
.get_materials()
.iter()
.map(material_to_record)
.collect();
let mut textures: Vec<Euv3dTextureRecord> = Vec::with_capacity(scene.get_textures().len());
for tex in scene.get_textures().iter() {
let color_space: u8 = match tex.get_color_space() {
TextureColorSpace::Srgb => 0,
TextureColorSpace::Linear => 1,
TextureColorSpace::NormalTangent => 2,
};
let sampler: TextureSampler3D = tex.get_sampler();
let encode_filter: fn(TextureFilterMode) -> u8 = |mode: TextureFilterMode| match mode {
TextureFilterMode::Nearest => 0,
TextureFilterMode::Linear => 1,
TextureFilterMode::NearestMipmapNearest => 2,
TextureFilterMode::LinearMipmapNearest => 3,
TextureFilterMode::NearestMipmapLinear => 4,
TextureFilterMode::LinearMipmapLinear => 5,
};
let min_filter: u8 = encode_filter(sampler.get_min_filter());
let mag_filter: u8 = encode_filter(sampler.get_mag_filter());
let wrap_s: u8 = match sampler.get_wrap_s() {
TextureWrapMode::Repeat => 0,
TextureWrapMode::MirroredRepeat => 1,
TextureWrapMode::ClampToEdge => 2,
};
let wrap_t: u8 = match sampler.get_wrap_t() {
TextureWrapMode::Repeat => 0,
TextureWrapMode::MirroredRepeat => 1,
TextureWrapMode::ClampToEdge => 2,
};
let mip_limit: usize = if config.get_generate_mipmaps() {
tex.get_mips().len()
} else {
tex.get_mips().len().min(1)
};
let mut mips: Vec<Euv3dTexMipRecord> = Vec::with_capacity(mip_limit);
for mip in tex.get_mips().iter().take(mip_limit) {
let byte_offset: u64 = tex_blob.len() as u64;
let pixels: &[u8] = mip.get_pixels();
tex_blob.extend_from_slice(pixels);
mips.push(Euv3dTexMipRecord {
width: mip.get_width(),
height: mip.get_height(),
byte_offset,
byte_length: pixels.len() as u64,
});
}
textures.push(Euv3dTextureRecord {
name: tex.get_name().clone(),
color_space,
min_filter,
mag_filter,
wrap_s,
wrap_t,
mips,
});
}
let skins: Vec<Euv3dSkinRecord> = scene
.get_skins()
.iter()
.map(|skin: &ImportedSkin3D| Euv3dSkinRecord {
name: skin.get_name().clone(),
joints: skin.get_joints().clone(),
skeleton_root: skin.try_get_skeleton_root(),
inverse_bind_matrices: skin
.get_inverse_bind_matrices()
.iter()
.map(|m: &Mat4| m.get_elements())
.collect(),
})
.collect();
let mut animations: Vec<Euv3dAnimClipRecord> =
Vec::with_capacity(scene.get_animations().len());
for clip in scene.get_animations().iter() {
let mut samplers: Vec<Euv3dAnimSamplerRecord> =
Vec::with_capacity(clip.get_samplers().len());
for samp in clip.get_samplers().iter() {
let first_time: u32 = anim_float_total;
let time_count: u32 = samp.get_timestamps().len() as u32;
for &t in samp.get_timestamps().iter() {
anim_blob.extend_from_slice(&t.to_le_bytes());
}
anim_float_total += time_count;
let first_value: u32 = anim_float_total;
let value_count: u32 = samp.get_values().len() as u32;
for &val in samp.get_values().iter() {
anim_blob.extend_from_slice(&val.to_le_bytes());
}
anim_float_total += value_count;
let interpolation: u8 = match samp.get_interpolation() {
GltfInterpolationMode::Step => 0,
GltfInterpolationMode::Linear => 1,
GltfInterpolationMode::CubicSpline => 2,
};
samplers.push(Euv3dAnimSamplerRecord {
first_time,
time_count,
first_value,
value_count,
value_stride: samp.get_value_stride() as u32,
interpolation,
});
}
let channels: Vec<Euv3dAnimChannelRecord> = clip
.get_channels()
.iter()
.map(|ch: &ImportedAnimationChannel3D| {
let path: u8 = match ch.get_path() {
GltfAnimationPath::Translation => 0,
GltfAnimationPath::Rotation => 1,
GltfAnimationPath::Scale => 2,
GltfAnimationPath::MorphWeights => 3,
};
Euv3dAnimChannelRecord {
target_node: ch.get_target_node(),
path,
sampler_index: ch.get_sampler_index() as u32,
}
})
.collect();
animations.push(Euv3dAnimClipRecord {
name: clip.get_name().clone(),
duration_secs: clip.get_duration_secs(),
samplers,
channels,
});
}
let cameras: Vec<Euv3dCameraRecord> = scene
.get_cameras()
.iter()
.map(|cam: &ImportedCamera3D| match cam.get_projection() {
GltfCameraProjection::Perspective {
yfov_rad,
aspect_ratio,
znear,
zfar,
} => Euv3dCameraRecord {
name: cam.get_name().clone(),
is_perspective: true,
param_a: yfov_rad,
param_b: aspect_ratio.unwrap_or(-1.0),
znear,
zfar,
},
GltfCameraProjection::Orthographic {
xmag,
ymag,
znear,
zfar,
} => Euv3dCameraRecord {
name: cam.get_name().clone(),
is_perspective: false,
param_a: xmag,
param_b: ymag,
znear,
zfar: Some(zfar),
},
})
.collect();
let lights: Vec<Euv3dLightRecord> = scene
.get_lights()
.iter()
.map(|light: &ImportedLight3D| match light.get_kind() {
GltfLightKind::Directional => Euv3dLightRecord {
name: light.get_name().clone(),
color: light.get_color().to_array(),
intensity: light.get_intensity(),
kind: 0,
range: None,
param_a: 0.0,
param_b: 0.0,
},
GltfLightKind::Point { range } => Euv3dLightRecord {
name: light.get_name().clone(),
color: light.get_color().to_array(),
intensity: light.get_intensity(),
kind: 1,
range,
param_a: 0.0,
param_b: 0.0,
},
GltfLightKind::Spot {
range,
inner_cone_angle,
outer_cone_angle,
} => Euv3dLightRecord {
name: light.get_name().clone(),
color: light.get_color().to_array(),
intensity: light.get_intensity(),
kind: 2,
range,
param_a: inner_cone_angle,
param_b: outer_cone_angle,
},
GltfLightKind::Area { width, height } => Euv3dLightRecord {
name: light.get_name().clone(),
color: light.get_color().to_array(),
intensity: light.get_intensity(),
kind: 3,
range: None,
param_a: width,
param_b: height,
},
})
.collect();
let metadata: Euv3dSceneMetadata = Euv3dSceneMetadata {
name: scene.get_name().clone(),
generator: scene.get_generator().clone(),
collections,
nodes,
meshes: mesh_records,
bvhs: bvh_records,
materials,
textures,
skins,
animations,
cameras,
lights,
};
let meta_json: String =
to_string(&metadata).map_err(|_| ERR_EUV3D_BAD_METADATA.to_string())?;
let meta_bytes: Vec<u8> = meta_json.into_bytes();
let mut payload_sections: Vec<(Euv3dSectionKind, u32, Vec<u8>)> = Vec::with_capacity(11);
payload_sections.push((Euv3dSectionKind::SceneMetadataJson, 1, meta_bytes));
if !vertices_blob.is_empty() {
payload_sections.push((Euv3dSectionKind::Vertices, vertex_total, vertices_blob));
}
if !indices_blob.is_empty() {
payload_sections.push((Euv3dSectionKind::Indices, tri_total, indices_blob));
}
if !skins_blob.is_empty() {
payload_sections.push((Euv3dSectionKind::SkinInfluences, skin_total, skins_blob));
}
if !morph_blob.is_empty() {
payload_sections.push((Euv3dSectionKind::MorphDeltas, morph_vec_total, morph_blob));
}
if !meshlets_blob.is_empty() {
payload_sections.push((Euv3dSectionKind::Meshlets, meshlet_total, meshlets_blob));
}
if !bvh4_blob.is_empty() {
payload_sections.push((Euv3dSectionKind::Bvh4Nodes, bvh4_total, bvh4_blob));
}
if !bvh_pkt_blob.is_empty() {
payload_sections.push((
Euv3dSectionKind::BvhTri4Packets,
bvh_pkt_total,
bvh_pkt_blob,
));
}
if !bvh_tri_blob.is_empty() {
payload_sections.push((Euv3dSectionKind::BvhTriangles, bvh_tri_total, bvh_tri_blob));
}
if !anim_blob.is_empty() {
payload_sections.push((
Euv3dSectionKind::AnimationsBlob,
anim_float_total,
anim_blob,
));
}
if !tex_blob.is_empty() {
payload_sections.push((
Euv3dSectionKind::TexturesBlob,
scene.get_textures().len() as u32,
tex_blob,
));
}
let section_count: usize = payload_sections.len();
let table_offset: usize = EUV3D_HEADER_BYTES;
let mut cursor: usize =
align_up_64(table_offset + section_count * EUV3D_SECTION_ENTRY_BYTES);
let mut entries: Vec<Euv3dSectionEntry> = Vec::with_capacity(section_count);
for &(kind, elem_count, ref data) in &payload_sections {
let sec_off: usize = align_up_64(cursor);
entries.push(Euv3dSectionEntry {
kind,
offset: sec_off as u64,
byte_length: data.len() as u64,
element_count: elem_count,
flags: 0,
});
cursor = align_up_64(sec_off + data.len());
}
let total_bytes: usize = cursor;
let mut out: Vec<u8> = vec![0u8; total_bytes];
for (idx, entry) in entries.iter().enumerate() {
let pos: usize = table_offset + idx * EUV3D_SECTION_ENTRY_BYTES;
out[pos..pos + 4].copy_from_slice(&entry.get_kind().to_u32().to_le_bytes());
out[pos + 4..pos + 8].copy_from_slice(&entry.get_flags().to_le_bytes());
out[pos + 8..pos + 16].copy_from_slice(&entry.get_offset().to_le_bytes());
out[pos + 16..pos + 24].copy_from_slice(&entry.get_byte_length().to_le_bytes());
out[pos + 24..pos + 28].copy_from_slice(&entry.get_element_count().to_le_bytes());
let data: &[u8] = &payload_sections[idx].2;
let dst_start: usize = entry.get_offset() as usize;
out[dst_start..dst_start + data.len()].copy_from_slice(data);
}
let mut flags: u32 = 0;
if config.get_bake_bvh4() && bvh4_total > 0 {
flags |= EUV3D_FLAG_HAS_BVH4;
}
if config.get_build_meshlets() && meshlet_total > 0 {
flags |= EUV3D_FLAG_HAS_MESHLETS;
}
if max_lods > 1 {
flags |= EUV3D_FLAG_HAS_LODS;
}
let content_crc32: u32 = compute_crc32(&out[EUV3D_HEADER_BYTES..]);
let digest_fnv1a: u64 = compute_fnv1a_64(&out[EUV3D_HEADER_BYTES..]);
out[0..8].copy_from_slice(&EUV3D_MAGIC);
out[8..12].copy_from_slice(&EUV3D_FORMAT_VERSION.to_le_bytes());
out[12..16].copy_from_slice(&flags.to_le_bytes());
out[16..20].copy_from_slice(&(section_count as u32).to_le_bytes());
out[24..32].copy_from_slice(&(table_offset as u64).to_le_bytes());
out[32..36].copy_from_slice(&content_crc32.to_le_bytes());
let header_crc32: u32 = compute_crc32(&out[..36]);
out[36..40].copy_from_slice(&header_crc32.to_le_bytes());
out[40..48].copy_from_slice(&(total_bytes as u64).to_le_bytes());
out[48..56].copy_from_slice(&digest_fnv1a.to_le_bytes());
Ok(out)
}
pub fn decode_bytes(bytes: &[u8]) -> Result<BakedAssetBundle3D, String> {
let view: Euv3dPackageView<'_> = Euv3dPackageView::from_bytes(bytes)?;
let meta_slice: &[u8] = view
.section_bytes(Euv3dSectionKind::SceneMetadataJson)
.ok_or_else(|| ERR_EUV3D_MISSING_METADATA.to_string())?;
let meta_str: &str =
from_utf8(meta_slice).map_err(|_| ERR_EUV3D_BAD_METADATA.to_string())?;
let meta: Euv3dSceneMetadata =
from_str(meta_str).map_err(|_| ERR_EUV3D_BAD_METADATA.to_string())?;
let verts_slice: &[u8] = view
.section_bytes(Euv3dSectionKind::Vertices)
.unwrap_or(&[]);
let idx_slice: &[u8] = view.section_bytes(Euv3dSectionKind::Indices).unwrap_or(&[]);
let skin_slice: &[u8] = view
.section_bytes(Euv3dSectionKind::SkinInfluences)
.unwrap_or(&[]);
let morph_slice: &[u8] = view
.section_bytes(Euv3dSectionKind::MorphDeltas)
.unwrap_or(&[]);
let mlet_slice: &[u8] = view
.section_bytes(Euv3dSectionKind::Meshlets)
.unwrap_or(&[]);
let bvh4_slice: &[u8] = view
.section_bytes(Euv3dSectionKind::Bvh4Nodes)
.unwrap_or(&[]);
let bvh_pkt_slice: &[u8] = view
.section_bytes(Euv3dSectionKind::BvhTri4Packets)
.unwrap_or(&[]);
let bvh_tri_slice: &[u8] = view
.section_bytes(Euv3dSectionKind::BvhTriangles)
.unwrap_or(&[]);
let anim_slice: &[u8] = view
.section_bytes(Euv3dSectionKind::AnimationsBlob)
.unwrap_or(&[]);
let tex_slice: &[u8] = view
.section_bytes(Euv3dSectionKind::TexturesBlob)
.unwrap_or(&[]);
let mut lod_chains: Vec<MeshLodChain> = Vec::with_capacity(meta.meshes.len());
let mut lod0_meshes: Vec<Mesh3D> = Vec::with_capacity(meta.meshes.len());
for mesh_rec in &meta.meshes {
let mut levels: Vec<Mesh3D> = Vec::with_capacity(mesh_rec.lods.len());
let base_mat: PbrMaterial = record_to_pbr(&mesh_rec.material);
let sub_mats: Vec<PbrMaterial> =
mesh_rec.sub_materials.iter().map(record_to_pbr).collect();
for (lod_idx, lod_rec) in mesh_rec.lods.iter().enumerate() {
let mut vertices: Vec<Vertex3D> = Vec::with_capacity(lod_rec.vertex_count as usize);
for v_i in 0..(lod_rec.vertex_count as usize) {
let off: usize =
((lod_rec.first_vertex as usize) + v_i) * EUV3D_VERTEX_STRIDE_BYTES;
vertices.push(read_vertex_bytes(verts_slice, off)?);
}
let mut indices: Vec<[u32; 3]> = Vec::with_capacity(lod_rec.tri_count as usize);
for t_i in 0..(lod_rec.tri_count as usize) {
let off: usize = ((lod_rec.first_tri as usize) + t_i) * EUV3D_INDEX_TRI_BYTES;
let i0: u32 = read_u32_le(idx_slice, off)?;
let i1: u32 = read_u32_le(idx_slice, off + 4)?;
let i2: u32 = read_u32_le(idx_slice, off + 8)?;
indices.push([i0, i1, i2]);
}
let mut meshlets: Vec<Meshlet3D> =
Vec::with_capacity(lod_rec.meshlet_count as usize);
for m_i in 0..(lod_rec.meshlet_count as usize) {
let off: usize =
((lod_rec.first_meshlet as usize) + m_i) * EUV3D_MESHLET_STRIDE_BYTES;
meshlets.push(read_meshlet_bytes(mlet_slice, off)?);
}
let bounds: AxisAlignedBox3D = AxisAlignedBox3D::new(
Vec3::from_array(lod_rec.bounds_min),
Vec3::from_array(lod_rec.bounds_max),
);
let mut skin_influences: Vec<MeshSkinInfluence3D> = Vec::new();
let mut morph_targets: Vec<MorphTarget3D> = Vec::new();
if lod_idx == 0 {
skin_influences.reserve(mesh_rec.skin_count as usize);
for s_i in 0..(mesh_rec.skin_count as usize) {
let off: usize =
((mesh_rec.first_skin as usize) + s_i) * EUV3D_SKIN_STRIDE_BYTES;
skin_influences.push(read_skin_bytes(skin_slice, off)?);
}
morph_targets.reserve(mesh_rec.morphs.len());
for m_rec in &mesh_rec.morphs {
let mut delta_positions: Vec<[f32; 3]> =
Vec::with_capacity(m_rec.pos_count as usize);
for p_i in 0..(m_rec.pos_count as usize) {
let off: usize = ((m_rec.first_pos as usize) + p_i) * 12;
delta_positions.push([
read_f32_le(morph_slice, off)?,
read_f32_le(morph_slice, off + 4)?,
read_f32_le(morph_slice, off + 8)?,
]);
}
let mut delta_normals: Vec<[f32; 3]> =
Vec::with_capacity(m_rec.norm_count as usize);
for n_i in 0..(m_rec.norm_count as usize) {
let off: usize = ((m_rec.first_norm as usize) + n_i) * 12;
delta_normals.push([
read_f32_le(morph_slice, off)?,
read_f32_le(morph_slice, off + 4)?,
read_f32_le(morph_slice, off + 8)?,
]);
}
let mut delta_tangents: Vec<[f32; 3]> =
Vec::with_capacity(m_rec.tan_count as usize);
for t_i in 0..(m_rec.tan_count as usize) {
let off: usize = ((m_rec.first_tan as usize) + t_i) * 12;
delta_tangents.push([
read_f32_le(morph_slice, off)?,
read_f32_le(morph_slice, off + 4)?,
read_f32_le(morph_slice, off + 8)?,
]);
}
morph_targets.push(MorphTarget3D {
name: m_rec.name.clone(),
delta_positions,
delta_normals,
delta_tangents,
});
}
}
let mesh_level: Mesh3D = Mesh3D {
name: mesh_rec.name.clone(),
vertices,
indices,
bounds,
material: base_mat,
sub_materials: if lod_idx == 0 {
sub_mats.clone()
} else {
Vec::new()
},
tri_materials: if lod_idx == 0 {
mesh_rec.tri_materials.clone()
} else {
Vec::new()
},
meshlets,
skin_influences,
morph_targets,
material_index: mesh_rec.material_index,
is_closed: mesh_rec.is_closed,
};
levels.push(mesh_level);
}
if let Some(first_level) = levels.first() {
lod0_meshes.push(first_level.clone());
}
lod_chains.push(MeshLodChain { levels });
}
let mut local_bvhs: Vec<Bvh3D> = Vec::with_capacity(meta.bvhs.len());
for bvh_rec in &meta.bvhs {
let mut bvh4_nodes: Vec<Bvh4Node> = Vec::with_capacity(bvh_rec.node_count as usize);
for n_i in 0..(bvh_rec.node_count as usize) {
let off: usize =
((bvh_rec.first_node as usize) + n_i) * EUV3D_BVH4_NODE_STRIDE_BYTES;
bvh4_nodes.push(read_bvh4_node_bytes(bvh4_slice, off)?);
}
let mut leaf_packets: Vec<BvhTri4> = Vec::with_capacity(bvh_rec.packet_count as usize);
for p_i in 0..(bvh_rec.packet_count as usize) {
let off: usize =
((bvh_rec.first_packet as usize) + p_i) * EUV3D_BVH_TRI4_STRIDE_BYTES;
leaf_packets.push(read_bvh_tri4_bytes(bvh_pkt_slice, off)?);
}
let mut triangles: Vec<BvhTriangle> = Vec::with_capacity(bvh_rec.tri_count as usize);
for t_i in 0..(bvh_rec.tri_count as usize) {
let off: usize = ((bvh_rec.first_tri as usize) + t_i) * EUV3D_BVH_TRI_STRIDE_BYTES;
triangles.push(read_bvh_tri_bytes(bvh_tri_slice, off)?);
}
for node in &bvh4_nodes {
let valid: usize = (node.valid_count as usize).min(4);
for lane in 0..valid {
let lc: usize = node.leaf_count[lane] as usize;
let ch: usize = node.child[lane] as usize;
if lc > 0 {
if ch
.checked_add(lc)
.is_none_or(|end: usize| end > leaf_packets.len())
{
return Err(ERR_EUV3D_INVALID_BVH4.to_string());
}
} else if ch >= bvh4_nodes.len() {
return Err(ERR_EUV3D_INVALID_BVH4.to_string());
}
}
}
for pkt in &leaf_packets {
for &t_idx in &pkt.tri_indices {
if t_idx != u32::MAX && (t_idx as usize) >= triangles.len() {
return Err(ERR_EUV3D_INVALID_BVH4.to_string());
}
}
}
let geom: Vec<BvhGeomTri> = triangles.iter().map(BvhGeomTri::from_triangle).collect();
let orig_indices: Vec<u32> = (0..triangles.len()).map(|i: usize| i as u32).collect();
local_bvhs.push(Bvh3D {
nodes: Vec::new(),
triangles,
geom,
leaf_packets,
flat_nodes: Vec::new(),
bvh4_nodes,
bvh4_src_children: Vec::new(),
root_min: bvh_rec.root_min,
root_max: bvh_rec.root_max,
#[cfg(target_arch = "x86_64")]
bvh8_nodes: Vec::new(),
#[cfg(target_arch = "x86_64")]
bvh8_src_children: Vec::new(),
orig_indices,
node_to_flat: Vec::new(),
build_sah_cost: bvh_rec.build_sah_cost,
});
}
let mut scene_graph: SceneGraph3D = SceneGraph3D::default();
if !meta.collections.is_empty() {
let mut active_mask: u64 = 0;
let entries: Vec<CollectionEntry3D> = meta
.collections
.iter()
.map(|c: &Euv3dCollectionRecord| {
if c.visible_viewport && c.bit_index < 64 {
active_mask |= 1u64 << u32::from(c.bit_index);
}
CollectionEntry3D {
name: c.name.clone(),
bit_index: c.bit_index,
visible_viewport: c.visible_viewport,
visible_render: c.visible_render,
}
})
.collect();
scene_graph.set_collections(CollectionRegistry3D {
entries,
active_mask,
});
}
for n_rec in &meta.nodes {
let mut node: SceneNode3D = SceneNode3D::from_name(&n_rec.name, n_rec.parent);
node.set_local_translation(Vec3::from_array(n_rec.translation));
node.set_local_rotation(Quat::from_array(n_rec.rotation));
node.set_local_scale(Vec3::from_array(n_rec.scale));
node.set_mesh_id(n_rec.mesh_id);
node.set_skin_id(n_rec.skin_id);
node.set_camera_id(n_rec.camera_id);
node.set_light_id(n_rec.light_id);
node.set_collection_mask(n_rec.collection_mask);
node.set_visible(n_rec.visible);
let collider: SceneColliderShape3D = match n_rec.collider_shape {
1 => SceneColliderShape3D::Box,
2 => SceneColliderShape3D::Sphere,
3 => SceneColliderShape3D::ConvexHull,
4 => SceneColliderShape3D::Mesh,
_ => SceneColliderShape3D::None,
};
node.set_extras(BlenderExtrasTags3D {
collider,
buoyancy_density: n_rec.buoyancy_density,
is_trigger: n_rec.is_trigger,
cast_shadows: n_rec.cast_shadows,
custom_json: n_rec.custom_json.clone(),
});
let node_id: u32 = scene_graph.add_node(node);
if !n_rec.morph_weights.is_empty() {
scene_graph.attach_morph_weights(node_id, &n_rec.morph_weights);
}
}
let _: usize = scene_graph.propagate_world_matrices();
let materials: Vec<PrincipledMaterial3D> =
meta.materials.iter().map(record_to_material).collect();
let mut textures: Vec<Texture2D3D> = Vec::with_capacity(meta.textures.len());
for t_rec in &meta.textures {
let color_space: TextureColorSpace = match t_rec.color_space {
1 => TextureColorSpace::Linear,
2 => TextureColorSpace::NormalTangent,
_ => TextureColorSpace::Srgb,
};
let decode_filter: fn(u8) -> TextureFilterMode = |tag: u8| match tag {
0 => TextureFilterMode::Nearest,
2 => TextureFilterMode::NearestMipmapNearest,
3 => TextureFilterMode::LinearMipmapNearest,
4 => TextureFilterMode::NearestMipmapLinear,
5 => TextureFilterMode::LinearMipmapLinear,
_ => TextureFilterMode::Linear,
};
let min_filter: TextureFilterMode = decode_filter(t_rec.min_filter);
let mag_filter: TextureFilterMode = decode_filter(t_rec.mag_filter);
let wrap_s: TextureWrapMode = match t_rec.wrap_s {
1 => TextureWrapMode::MirroredRepeat,
2 => TextureWrapMode::ClampToEdge,
_ => TextureWrapMode::Repeat,
};
let wrap_t: TextureWrapMode = match t_rec.wrap_t {
1 => TextureWrapMode::MirroredRepeat,
2 => TextureWrapMode::ClampToEdge,
_ => TextureWrapMode::Repeat,
};
let mut mips: Vec<TextureMipLevel3D> = Vec::with_capacity(t_rec.mips.len());
for mip_rec in &t_rec.mips {
let start: usize = mip_rec.byte_offset as usize;
let end: usize = start
.checked_add(mip_rec.byte_length as usize)
.ok_or_else(|| ERR_EUV3D_TRUNCATED_BLOB.to_string())?;
if end > tex_slice.len() {
return Err(ERR_EUV3D_TRUNCATED_BLOB.to_string());
}
mips.push(TextureMipLevel3D {
width: mip_rec.width,
height: mip_rec.height,
pixels: tex_slice[start..end].to_vec(),
});
}
let (width, height): (u32, u32) = mips
.first()
.map(|m: &TextureMipLevel3D| (m.get_width(), m.get_height()))
.unwrap_or((0, 0));
textures.push(Texture2D3D {
name: t_rec.name.clone(),
width,
height,
color_space,
sampler: TextureSampler3D::new(mag_filter, min_filter, wrap_s, wrap_t),
mips,
});
}
let skins: Vec<ImportedSkin3D> = meta
.skins
.iter()
.map(|s: &Euv3dSkinRecord| ImportedSkin3D {
name: s.name.clone(),
joints: s.joints.clone(),
skeleton_root: s.skeleton_root,
inverse_bind_matrices: s
.inverse_bind_matrices
.iter()
.map(|arr: &[f32; 16]| Mat4::from_cols_array(*arr))
.collect(),
})
.collect();
let mut animations: Vec<ImportedAnimationClip3D> =
Vec::with_capacity(meta.animations.len());
for c_rec in &meta.animations {
let mut samplers: Vec<ImportedAnimationSampler3D> =
Vec::with_capacity(c_rec.samplers.len());
for s_rec in &c_rec.samplers {
let mut timestamps: Vec<f32> = Vec::with_capacity(s_rec.time_count as usize);
for i in 0..(s_rec.time_count as usize) {
timestamps.push(read_f32_le(
anim_slice,
((s_rec.first_time as usize) + i) * 4,
)?);
}
let mut values: Vec<f32> = Vec::with_capacity(s_rec.value_count as usize);
for i in 0..(s_rec.value_count as usize) {
values.push(read_f32_le(
anim_slice,
((s_rec.first_value as usize) + i) * 4,
)?);
}
let interpolation: GltfInterpolationMode = match s_rec.interpolation {
0 => GltfInterpolationMode::Step,
2 => GltfInterpolationMode::CubicSpline,
_ => GltfInterpolationMode::Linear,
};
samplers.push(ImportedAnimationSampler3D {
timestamps,
values,
value_stride: s_rec.value_stride as usize,
interpolation,
});
}
let channels: Vec<ImportedAnimationChannel3D> = c_rec
.channels
.iter()
.map(|ch: &Euv3dAnimChannelRecord| {
let path: GltfAnimationPath = match ch.path {
1 => GltfAnimationPath::Rotation,
2 => GltfAnimationPath::Scale,
3 => GltfAnimationPath::MorphWeights,
_ => GltfAnimationPath::Translation,
};
ImportedAnimationChannel3D::new(ch.target_node, path, ch.sampler_index as usize)
})
.collect();
animations.push(ImportedAnimationClip3D {
name: c_rec.name.clone(),
duration_secs: c_rec.duration_secs,
samplers,
channels,
});
}
let cameras: Vec<ImportedCamera3D> = meta
.cameras
.iter()
.map(|c: &Euv3dCameraRecord| {
let projection: GltfCameraProjection = if c.is_perspective {
GltfCameraProjection::Perspective {
yfov_rad: c.param_a,
aspect_ratio: if c.param_b > 0.0 {
Some(c.param_b)
} else {
None
},
znear: c.znear,
zfar: c.zfar,
}
} else {
GltfCameraProjection::Orthographic {
xmag: c.param_a,
ymag: c.param_b,
znear: c.znear,
zfar: c.zfar.unwrap_or(1000.0),
}
};
ImportedCamera3D {
name: c.name.clone(),
projection,
}
})
.collect();
let lights: Vec<ImportedLight3D> = meta
.lights
.iter()
.map(|l: &Euv3dLightRecord| {
let kind: GltfLightKind = match l.kind {
1 => GltfLightKind::Point { range: l.range },
2 => GltfLightKind::Spot {
range: l.range,
inner_cone_angle: l.param_a,
outer_cone_angle: l.param_b,
},
3 => GltfLightKind::Area {
width: l.param_a,
height: l.param_b,
},
_ => GltfLightKind::Directional,
};
ImportedLight3D {
name: l.name.clone(),
color: Vec3::from_array(l.color),
intensity: l.intensity,
kind,
}
})
.collect();
let scene: ImportedScene3D = ImportedScene3D {
name: meta.name,
generator: meta.generator,
scene_graph,
meshes: lod0_meshes,
materials,
textures,
skins,
animations,
cameras,
lights,
};
let header: Euv3dHeader = view.get_header();
Ok(BakedAssetBundle3D {
scene,
lod_chains,
local_bvhs,
section_count: view.get_sections().len(),
total_bytes: header.get_total_bytes() as usize,
digest_fnv1a: header.get_digest_fnv1a(),
})
}
}