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
use crate::DirectXMesh;
use anyhow::Result;
use bevy::{
asset::{AssetLoader, LoadContext},
ecs::world::World,
image::{CompressedImageFormats, Image},
prelude::*,
render::{
mesh::{Indices, Mesh},
render_asset::RenderAssetUsages,
render_resource::PrimitiveTopology,
},
scene::Scene,
};
use std::collections::HashMap;
use xfile_rs::{data::DataValue, XFile};
/// Loads DirectX Mesh files with all of their data as their corresponding bevy representations.
pub struct DirectXMeshLoader {
/// List of compressed image formats handled by the loader.
pub supported_compressed_formats: CompressedImageFormats,
}
impl AssetLoader for DirectXMeshLoader {
type Asset = DirectXMesh;
type Settings = ();
type Error = anyhow::Error;
async fn load(
&self,
reader: &mut dyn bevy::asset::io::Reader,
_settings: &(),
load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let xfile = XFile::read(&bytes)?;
let mut meshes = vec![];
let mut materials = vec![];
let mut world = World::new();
let mut material_handles: HashMap<String, Handle<StandardMaterial>> = HashMap::new();
for obj in &xfile.data_objects {
if let DataValue::Object {
type_name,
name,
members,
..
} = obj
{
if type_name == "Material" {
let material_name = name
.clone()
.unwrap_or_else(|| "UnnamedMaterial".to_string());
let mut texture_path = None;
for member in members {
if let DataValue::Object {
type_name, members, ..
} = member
{
if type_name == "TextureFilename" {
if let Some(DataValue::StringList(strings)) = members.get(0) {
texture_path = strings.get(0).cloned();
}
}
}
}
let material_handle = if let Some(tex_path) = texture_path {
match load_image(&tex_path, load_context, self.supported_compressed_formats).await {
Ok(image) => {
let tex_handle = load_context
.add_labeled_asset(format!("Texture_{}", material_name), image);
let material = StandardMaterial {
base_color_texture: Some(tex_handle.clone()),
perceptual_roughness: 1.0,
..Default::default()
};
load_context.add_labeled_asset(material_name.clone(), material)
}
Err(_) => {
let material = StandardMaterial::default();
load_context.add_labeled_asset(material_name.clone(), material)
}
}
} else {
let material = StandardMaterial::default();
load_context.add_labeled_asset(material_name.clone(), material)
};
material_handles.insert(material_name.clone(), material_handle.clone());
materials.push(material_handle);
}
}
}
for (mesh_index, obj) in xfile.data_objects.iter().enumerate() {
if let DataValue::Object {
type_name, members, ..
} = obj
{
if type_name != "Mesh" {
continue;
}
let vertex_count = members
.get(0)
.and_then(|v| match v {
DataValue::IntList(v) => v.get(0).copied(),
_ => None,
})
.unwrap_or(0) as usize;
let mut floats = vec![];
for member in members.iter().skip(1).take(vertex_count * 3) {
if let DataValue::FloatList(v) = member {
floats.push(v[0]);
}
}
let vertices: Vec<[f32; 3]> = floats
.chunks(3)
.map(|c| [c[0] as f32, c[1] as f32, -c[2] as f32])
.collect();
let mut texcoords_raw = vec![];
let mut normals_raw = vec![];
let mut material_assignments = vec![];
for member in members.iter() {
if let DataValue::Object {
type_name, members, ..
} = member
{
match type_name.as_str() {
"MeshTextureCoords" => {
for sub in members.iter().skip(1) {
if let DataValue::FloatList(v) = sub {
texcoords_raw.push(v[0]);
}
}
}
"MeshNormals" => {
for sub in members.iter().skip(1) {
if let DataValue::FloatList(v) = sub {
normals_raw.push(v[0]);
}
}
}
"MeshMaterialList" => {
if let Some(DataValue::IntList(counts)) = members.get(1) {
let face_count = counts[0] as usize;
if let Some(DataValue::IntList(assignments)) = members.get(2) {
for i in 0..face_count {
let mat_index =
assignments.get(i).copied().unwrap_or(0);
let name = if let Some(DataValue::Reference {
name: Some(name),
..
}) = members.get(3 + mat_index as usize)
{
name.clone()
} else {
format!("Material_{}_{}", mesh_index, mat_index)
};
material_assignments.push(name);
}
}
}
}
_ => {}
}
}
}
let tex_coords: Vec<[f32; 2]> = texcoords_raw
.chunks(2)
.map(|c| [c[0] as f32, c[1] as f32])
.collect();
let normals: Vec<[f32; 3]> = normals_raw
.chunks(3)
.map(|c| [c[0] as f32, c[1] as f32, -c[2] as f32])
.collect();
let mut face_map: HashMap<String, Vec<u32>> = HashMap::new();
let mut current_face: Vec<usize> = Vec::new();
let mut face_index = 0;
for member in members.iter().skip(1 + vertex_count * 3) {
match member {
DataValue::IntList(v) if v.len() == 1 => {
if !current_face.is_empty() {
let mat = material_assignments
.get(face_index)
.cloned()
.unwrap_or_else(|| "default".to_string());
let entry = face_map.entry(mat).or_default();
if current_face.len() == 3 {
entry.push(current_face[0] as u32);
entry.push(current_face[2] as u32); // swap last two
entry.push(current_face[1] as u32);
} else if current_face.len() > 3 {
let first = current_face[0];
for pair in current_face.windows(2).skip(1) {
entry.push(first as u32);
entry.push(pair[1] as u32); // swap order
entry.push(pair[0] as u32);
}
}
current_face.clear();
face_index += 1;
}
}
DataValue::IntList(v) => {
current_face.extend(v.iter().map(|x| *x as usize));
}
_ => {}
}
}
if !current_face.is_empty() {
let mat = material_assignments
.get(face_index)
.cloned()
.unwrap_or_else(|| "default".to_string());
let entry = face_map.entry(mat).or_default();
if current_face.len() == 3 {
entry.push(current_face[0] as u32);
entry.push(current_face[2] as u32); // swap last two
entry.push(current_face[1] as u32);
} else if current_face.len() > 3 {
let first = current_face[0];
for pair in current_face.windows(2).skip(1) {
entry.push(first as u32);
entry.push(pair[1] as u32); // swap order
entry.push(pair[0] as u32);
}
}
}
for (mat, indices) in face_map {
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, vertices.clone());
if !normals.is_empty() {
mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals.clone());
}
if !tex_coords.is_empty() {
mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, tex_coords.clone());
}
mesh.insert_indices(Indices::U32(indices));
let mesh_handle = load_context.add_labeled_asset(format!("{}_mesh", mat), mesh);
let mat_handle = material_handles.get(&mat).cloned().unwrap_or_else(|| {
let m = StandardMaterial::default();
load_context.add_labeled_asset(format!("{}_autogen", mat), m)
});
world.spawn((
Mesh3d(mesh_handle.clone()),
MeshMaterial3d::<StandardMaterial>(mat_handle.clone()),
));
meshes.push(mesh_handle);
materials.push(mat_handle);
}
}
}
Ok(DirectXMesh {
scene: load_context.add_labeled_asset("Scene".to_owned(), Scene::new(world)),
meshes,
materials,
})
}
fn extensions(&self) -> &[&str] {
&["x"]
}
}
/// Loads a bevy [`Image`] and returns it together with its label.
async fn load_image<'a>(
path: &str,
load_context: &mut LoadContext<'a>,
supported_compressed_formats: CompressedImageFormats,
) -> Result<Image, anyhow::Error> {
// Normalize the path: convert backslashes to forward slashes
let path = path.replace('\\', "/");
// Extract just the file name
let filename = std::path::Path::new(&path)
.file_name()
.expect("Expected filename in path");
// Resolve relative to the current asset location
let parent = load_context.path().parent().unwrap();
let image_path = parent.join(filename);
// Load the texture
let bytes = load_context.read_asset_bytes(image_path).await?;
let extension = filename
.to_str()
.and_then(|name| name.split('.').last())
.unwrap_or("png");
let image_type = bevy::image::ImageType::Extension(extension);
Ok(Image::from_buffer(
&bytes,
image_type,
supported_compressed_formats,
true,
bevy::image::ImageSampler::Descriptor(bevy::image::ImageSamplerDescriptor {
// rewriting mode to repeat image,
address_mode_u: bevy::image::ImageAddressMode::Repeat,
address_mode_v: bevy::image::ImageAddressMode::Repeat,
mag_filter: bevy::image::ImageFilterMode::Linear,
min_filter: bevy::image::ImageFilterMode::Linear,
mipmap_filter: bevy::image::ImageFilterMode::Linear,
..default()
}),
bevy::asset::RenderAssetUsages::default(),
)?)
}