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
|
use super::streaming_info::StreamingInfo;
use crate::object::{Value, parser::FromValue};
use anyhow::{Result, anyhow, bail};
use glam::{Mat4, Vec2, Vec3, Vec3A, Vec4};
use log::debug;
use serde::Serialize;
use std::mem::transmute;
#[derive(Debug, Serialize)]
pub struct Mesh {
pub name: String,
pub bind_pose: Vec<Mat4>,
pub bone_name_hashes: Vec<u32>,
pub index_format: i32,
pub index_buffer: Vec<u8>,
pub sub_meshes: Vec<SubMesh>,
pub stream_data: StreamingInfo,
pub vertex_data: VertexData,
}
#[derive(Debug, Serialize)]
pub struct SubMesh {
pub topology: i32,
pub vertex_count: u32,
pub base_vertex: u32,
pub first_byte: u32,
pub first_vertex: u32,
pub index_count: u32,
}
#[derive(Debug, Serialize)]
pub struct VertexData {
pub channels: Vec<ChannelInfo>,
pub data: Vec<u8>,
pub vertex_count: u32,
}
#[derive(Debug, Serialize)]
pub struct ChannelInfo {
pub dimension: u8,
pub format: VertexFormat,
pub offset: u8,
pub stream: u8,
}
impl FromValue for Mesh {
fn from_value(v: Value) -> Result<Self> {
let mut fields = v.as_class("Mesh")?;
Ok(Mesh {
name: fields.field("m_Name")?,
index_format: fields.field("m_IndexFormat")?,
vertex_data: fields.field("m_VertexData")?,
stream_data: fields.field("m_StreamData")?,
index_buffer: fields
.remove("m_IndexBuffer")
.unwrap()
.as_vector()
.unwrap()
.into_iter()
.map(|e| e.as_u8().unwrap())
.collect(),
sub_meshes: fields
.remove("m_SubMeshes")
.unwrap()
.as_vector()
.unwrap()
.into_iter()
.map(|e| e.parse().unwrap())
.collect(),
bind_pose: fields
.remove("m_BindPose")
.unwrap()
.as_vector()
.unwrap()
.into_iter()
.map(|e| e.parse().unwrap())
.collect(),
bone_name_hashes: fields
.remove("m_BoneNameHashes")
.unwrap()
.as_vector()
.unwrap()
.into_iter()
.map(|e| e.parse().unwrap())
.collect(),
})
}
}
impl Mesh {
pub fn read_indecies(&self) -> Vec<[u32; 3]> {
if self.index_format == 0 {
self.index_buffer
.array_chunks::<2>()
.map(|x| u16::from_le_bytes(*x) as u32)
.array_chunks()
.collect()
} else {
self.index_buffer
.array_chunks::<4>()
.map(|x| u32::from_le_bytes(*x))
.array_chunks()
.collect()
}
}
}
impl FromValue for VertexData {
fn from_value(v: Value) -> Result<Self> {
let mut fields = v.as_class("VertexData")?;
Ok(VertexData {
vertex_count: fields.field("m_VertexCount")?,
data: fields
.remove("m_DataSize")
.ok_or(anyhow!("m_DataSize missing"))?
.as_typeless()
.ok_or(anyhow!("m_DataSize is not typeless"))?,
channels: fields
.remove("m_Channels")
.unwrap()
.as_vector()
.unwrap()
.into_iter()
.map(|e| e.parse().unwrap())
.collect(),
})
}
}
impl VertexData {
/// Returns (offset, stride) for each stream.
pub fn stream_layout(&self) -> Vec<(usize, usize)> {
let stream_count = self.channels.iter().map(|c| c.stream).max().unwrap() + 1;
let mut streams = Vec::new();
let mut offset = 0;
for si in 0..stream_count {
let stride = self
.channels
.iter()
.filter(|c| c.stream == si)
// The modulo operator here is a hack to fix normal with 52 dimensions to 4
.map(|c| (c.dimension as usize % 48) * c.format.component_size())
.sum();
streams.push((offset, stride));
offset += stride * self.vertex_count as usize
}
streams
}
/// Reads a vertex channel and returns dimension count and data converted to floats
pub fn read_channel(&self, ch: VertexDataChannel) -> Option<(usize, Vec<f32>)> {
let channel = &self.channels[ch as u8 as usize];
if channel.dimension == 0 {
return None;
}
let dim = channel.dimension as usize % 48;
let component_offset = channel.offset as usize;
let component_size = channel.format.component_size();
let (offset, stride) = self.stream_layout()[channel.stream as usize];
debug!(
"reading {ch:?} vertex channel (stride={stride}, offset={offset}, format={:?})",
channel.format
);
let mut out = Vec::new();
for vi in 0..self.vertex_count as usize {
for di in 0..dim {
let off = offset + vi * stride + component_offset + component_size * di;
let e = &self.data[off..];
out.push(match channel.format {
VertexFormat::Float => f32::from_le_bytes([e[0], e[1], e[2], e[3]]),
VertexFormat::Float16 => f16::from_le_bytes([e[0], e[1]]) as f32,
VertexFormat::SInt8 => i8::from_le_bytes([e[0]]) as f32,
VertexFormat::UInt8 => u8::from_le_bytes([e[0]]) as f32,
VertexFormat::SInt16 => i16::from_le_bytes([e[0], e[1]]) as f32,
VertexFormat::UInt16 => u16::from_le_bytes([e[0], e[1]]) as f32,
VertexFormat::SInt32 => i32::from_le_bytes([e[0], e[1], e[2], e[3]]) as f32,
VertexFormat::UInt32 => u32::from_le_bytes([e[0], e[1], e[2], e[3]]) as f32,
VertexFormat::UNorm8 => u8::from_le_bytes([e[0]]) as f32 / 256.,
VertexFormat::SNorm8 => i8::from_le_bytes([e[0]]) as f32 / 128.,
VertexFormat::UNorm16 => u16::from_le_bytes([e[0], e[1]]) as f32 / 65536.,
VertexFormat::SNorm16 => i16::from_le_bytes([e[0], e[1]]) as f32 / 32768.,
})
}
}
Some((dim, out))
}
pub fn read_channel_vec<T: VectorType>(
&self,
channel: VertexDataChannel,
coerce: bool,
) -> Result<Option<Vec<T>>> {
let Some((dim, mut data)) = self.read_channel(channel) else {
return Ok(None);
};
if dim != T::DIM {
if coerce {
let mut ndata = Vec::new();
if dim > T::DIM {
for e in data.chunks_exact(dim) {
ndata.extend(&e[..T::DIM]);
}
} else if dim < T::DIM {
for e in data.chunks_exact(dim) {
ndata.extend(e);
for _ in 0..(T::DIM - dim) {
ndata.push(0.);
}
}
}
data = ndata;
} else {
bail!(
"dimension mismatch reading {channel:?} channel ({} != {})",
dim,
T::DIM
);
}
}
Ok(Some(VectorType::convert_array(data)))
}
}
pub trait VectorType: Sized {
const DIM: usize;
fn convert_array(a: Vec<f32>) -> Vec<Self>;
}
impl VectorType for Vec3A {
const DIM: usize = 3;
fn convert_array(a: Vec<f32>) -> Vec<Self> {
a.into_iter()
.array_chunks()
.map(Vec3A::from_array)
.collect()
}
}
impl VectorType for Vec3 {
const DIM: usize = 3;
fn convert_array(a: Vec<f32>) -> Vec<Self> {
a.into_iter().array_chunks().map(Vec3::from_array).collect()
}
}
impl VectorType for Vec2 {
const DIM: usize = 2;
fn convert_array(a: Vec<f32>) -> Vec<Self> {
a.into_iter().array_chunks().map(Vec2::from_array).collect()
}
}
impl VectorType for Vec4 {
const DIM: usize = 4;
fn convert_array(a: Vec<f32>) -> Vec<Self> {
a.into_iter().array_chunks().map(Vec4::from_array).collect()
}
}
impl FromValue for ChannelInfo {
fn from_value(v: Value) -> Result<Self> {
let mut fields = v.as_class("ChannelInfo")?;
Ok(ChannelInfo {
dimension: fields.field("dimension")?,
format: fields.field("format")?,
offset: fields.field("offset")?,
stream: fields.field("stream")?,
})
}
}
impl FromValue for SubMesh {
fn from_value(v: Value) -> Result<Self> {
let mut fields = v.as_class("SubMesh")?;
Ok(SubMesh {
topology: fields.field("topology")?,
vertex_count: fields.field("vertexCount")?,
base_vertex: fields.field("baseVertex")?,
first_byte: fields.field("firstByte")?,
first_vertex: fields.field("firstVertex")?,
index_count: fields.field("indexCount")?,
})
}
}
#[repr(u8)]
#[derive(Debug, Serialize, Clone, Copy, PartialEq)]
pub enum VertexDataChannel {
Position,
Normal,
Tangent,
Color,
TexCoord0,
TexCoord1,
TexCoord2,
TexCoord3,
TexCoord4,
TexCoord5,
TexCoord6,
TexCoord7,
BlendWeight,
BlendIndices,
}
#[repr(u8)]
#[derive(Debug, Serialize, Clone, Copy, PartialEq)]
pub enum VertexFormat {
Float,
Float16,
UNorm8,
SNorm8,
UNorm16,
SNorm16,
UInt8,
SInt8,
UInt16,
SInt16,
UInt32,
SInt32,
}
impl FromValue for VertexFormat {
fn from_value(v: Value) -> Result<Self> {
let x = v.as_u8().ok_or(anyhow!("expected u8 vertex format"))?;
if x < 12 {
Ok(unsafe { transmute(x) })
} else {
bail!("unknown vertex format")
}
}
}
impl VertexFormat {
pub fn component_size(&self) -> usize {
use VertexFormat::*;
match self {
Float | UInt32 | SInt32 => 4,
Float16 | UInt16 | SInt16 | UNorm16 | SNorm16 => 2,
UInt8 | SInt8 | UNorm8 | SNorm8 => 1,
}
}
}
|