wc3 0.2.0

Read, edit, and write Warcraft III models, BLP textures, and MPQ archives
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
//! Explicit conversions between typed MDX layouts.
use crate::model::scene::{set_node_kind, Node, NodeFlagInterpretation};
use crate::model::visit_model;
use std::error::Error;
use std::fmt::{self, Display, Formatter};

use crate::model::{
    Camera, CamerasChunk, DynamicModel, Geoset, GeosetsChunk, Layer, Light, LightsChunk, Material,
    MaterialsChunk, Model, ModelChunk, ModelVersion, UnknownChunk, Version, VersionChunk,
};

/// Whether conversion may discard data that the target cannot represent.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum LossPolicy {
    #[default]
    /// Rejects conversion that would lose nondefault data.
    Reject,
    /// Allows unsupported data to be dropped and records it in the report.
    Drop,
}

/// Handling of opaque chunks when changing versions.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum UnknownChunkPolicy {
    #[default]
    /// Rejects opaque chunks when changing model versions.
    Reject,
    /// Retain exact bytes without guaranteeing target-version compatibility.
    Preserve,
    /// Drops opaque chunks when changing model versions.
    Drop,
}

/// Conversion policies. Unknown chunks require a separate explicit choice.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct ConversionOptions {
    /// Handling of fields and records unsupported by the target version.
    pub loss_policy: LossPolicy,
    /// Handling of opaque chunks when changing versions.
    pub unknown_chunks: UnknownChunkPolicy,
}
impl ConversionOptions {
    /// Rejects unsupported nondefault data and opaque chunks when changing versions.
    pub fn strict() -> Self {
        Self::default()
    }
    /// Allows unsupported data to be dropped; opaque chunks still require a choice.
    pub fn lossy() -> Self {
        Self {
            loss_policy: LossPolicy::Drop,
            ..Self::default()
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
/// Classification of a change or caveat produced by conversion.
pub enum ConversionIssueKind {
    /// Equivalent storage was normalized to the target layout without losing values.
    Normalized,
    /// A target-only field was initialized with its documented default.
    Initialized,
    /// A neutral source field was omitted because the target has no storage for it.
    OmittedDefault,
    /// Data was discarded with the caller's permission.
    Dropped,
    /// Opaque bytes were preserved without a compatibility guarantee.
    PreservedUnknown,
}

/// A change or compatibility caveat at a concrete source location.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ConversionIssue {
    /// Path identifying the affected chunk, record, or field.
    pub path: String,
    /// Classification of this change or caveat.
    pub kind: ConversionIssueKind,
    /// Human-readable explanation of the conversion result.
    pub description: String,
}
/// Changes and compatibility caveats to inspect after a successful conversion.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ConversionReport {
    /// Changes and caveats in conversion traversal order.
    pub issues: Vec<ConversionIssue>,
}
/// A converted model or record together with the changes made to produce it.
#[derive(Clone, Debug)]
pub struct Conversion<T> {
    /// The converted model or record.
    pub model: T,
    /// Changes and caveats generated while producing the result.
    pub report: ConversionReport,
}

/// The first field or chunk that cannot be converted under the selected policy.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ConversionError {
    /// Numeric version of the input model or record.
    pub source_version: Version,
    /// Requested numeric destination version.
    pub target_version: Version,
    /// Path identifying the field or chunk that prevented conversion.
    pub path: String,
    /// Human-readable reason conversion failed.
    pub description: String,
}
impl Display for ConversionError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "cannot convert MDX {} to {} at {}: {}",
            self.source_version, self.target_version, self.path, self.description
        )
    }
}
impl Error for ConversionError {}

pub(crate) struct ConversionContext<'a> {
    options: &'a ConversionOptions,
    source: Version,
    target: Version,
    pub(crate) report: ConversionReport,
}
impl<'a> ConversionContext<'a> {
    fn new<S: ModelVersion, T: ModelVersion>(options: &'a ConversionOptions) -> Self {
        Self {
            options,
            source: S::NUMBER,
            target: T::NUMBER,
            report: ConversionReport::default(),
        }
    }
    pub(crate) fn issue(&mut self, path: &str, kind: ConversionIssueKind, description: &str) {
        self.report.issues.push(ConversionIssue {
            path: path.into(),
            kind,
            description: description.into(),
        });
    }
    pub(crate) fn error(&self, path: &str, description: &str) -> ConversionError {
        ConversionError {
            source_version: self.source,
            target_version: self.target,
            path: path.into(),
            description: description.into(),
        }
    }
    pub(crate) fn drop(&mut self, path: &str, description: &str) -> Result<(), ConversionError> {
        if self.options.loss_policy == LossPolicy::Reject {
            return Err(self.error(path, description));
        }
        self.issue(path, ConversionIssueKind::Dropped, description);
        Ok(())
    }
    /// Absent target fields may omit neutral defaults without a loss.
    pub(crate) fn field<T: PartialEq>(
        &mut self,
        source: Option<T>,
        target: Option<&mut T>,
        neutral: T,
        path: &str,
    ) -> Result<(), ConversionError> {
        match (source, target) {
            (Some(value), Some(target)) => *target = value,
            (Some(value), None) if value != neutral => {
                self.drop(path, "field is not supported by the target")?
            }
            (None, Some(_)) => self.issue(
                path,
                ConversionIssueKind::Initialized,
                "initialized with the target field default",
            ),
            (Some(_), None) => self.issue(
                path,
                ConversionIssueKind::OmittedDefault,
                "omitted neutral default; field is not supported by the target",
            ),
            (None, None) => {}
        }
        Ok(())
    }
}

macro_rules! record_conversion {
    ($($record:ident),+) => {$(
        impl<V: ModelVersion> $record<V> {
            /// Converts this record without modifying it. Neutral defaults may be omitted.
            pub fn convert<T: ModelVersion>(&self, options: &ConversionOptions) -> Result<Conversion<$record<T>>, ConversionError> {
                let mut context = ConversionContext::new::<V, T>(options);
                let model = self.convert_with::<T>(&mut context, "record")?;
                Ok(Conversion { model, report: context.report })
            }
        }
    )+};
}
record_conversion!(Material, Layer, Geoset, Light, Camera);

impl<V: ModelVersion> Model<V> {
    /// Returns a normalized copy and its report, preserving the model version.
    ///
    /// Equivalent camera variants and missing node kind bits are normalized.
    /// The source is unchanged. This is strict conversion to the same version;
    /// it does not guarantee that every binary value can be exported to MDL.
    pub fn normalized(&self) -> Result<Conversion<Self>, ConversionError> {
        self.convert::<V>(&ConversionOptions::strict())
    }

    /// Converts ordered chunks to another layout without modifying the source.
    ///
    /// ```
    /// use wc3::model::{ConversionOptions, Model, V800, V1100};
    /// let source = Model::<V800>::new();
    /// let converted = source.convert::<V1100>(&ConversionOptions::strict())?;
    /// assert_eq!(converted.model.version(), 1100);
    /// # Ok::<(), wc3::model::ConversionError>(())
    /// ```
    ///
    /// Shared fields retain exact storage, except equivalent camera variants 0/3
    /// are normalized to the target default and reported. Missing node kind bits
    /// are inferred from their record type and reported; conflicting kind bits are retained.
    /// New fields use constructor defaults.
    /// Unsupported non-default fields and tracks fail unless dropping is enabled.
    /// A missing VERS is inserted so the encoded result identifies its target layout.
    pub fn convert<T: ModelVersion>(
        &self,
        options: &ConversionOptions,
    ) -> Result<Conversion<Model<T>>, ConversionError> {
        let mut context = ConversionContext::new::<V, T>(options);
        let mut model = Model::<T>::new();
        model.chunks.clear();
        for (index, chunk) in self.chunks.iter().enumerate() {
            let path = format!("chunks[{index}]");
            if T::NUMBER < 900
                && matches!(
                    chunk,
                    ModelChunk::BindPose(_)
                        | ModelChunk::FaceFx(_)
                        | ModelChunk::PopcornEmitters(_)
                )
            {
                context.drop(&path, "chunk is not supported by the target")?;
                continue;
            }
            macro_rules! records {
                ($value:expr, $collection:ident, $name:literal) => {{
                    let records = $value
                        .records
                        .iter()
                        .enumerate()
                        .map(|(i, record)| {
                            record
                                .convert_with::<T>(&mut context, &format!("{path}.{}[{i}]", $name))
                        })
                        .collect::<Result<Vec<_>, _>>()?;
                    $collection::<T>::new(records).into()
                }};
            }
            let mut converted = match chunk {
                ModelChunk::Version(value) => {
                    let mut version = VersionChunk::<T>::new();
                    version.extension = value.extension.clone();
                    version.into()
                }
                ModelChunk::Materials(value) => records!(value, MaterialsChunk, "materials"),
                ModelChunk::Geosets(value) => records!(value, GeosetsChunk, "geosets"),
                ModelChunk::Lights(value) => records!(value, LightsChunk, "lights"),
                ModelChunk::Cameras(value) => records!(value, CamerasChunk, "cameras"),
                ModelChunk::Unknown(value) => {
                    if V::NUMBER != T::NUMBER {
                        match options.unknown_chunks {
                            UnknownChunkPolicy::Reject => {
                                return Err(
                                    context.error(&path, "opaque chunk compatibility is unknown")
                                )
                            }
                            UnknownChunkPolicy::Drop => {
                                context.issue(
                                    &path,
                                    ConversionIssueKind::Dropped,
                                    "dropped opaque chunk",
                                );
                                continue;
                            }
                            UnknownChunkPolicy::Preserve => context.issue(
                                &path,
                                ConversionIssueKind::PreservedUnknown,
                                "retained opaque bytes; target compatibility is unknown",
                            ),
                        }
                    }
                    ModelChunk::Unknown(
                        UnknownChunk::<T>::new(value.raw().clone())
                            .expect("unknown tag remains unknown"),
                    )
                }
                ModelChunk::ModelInfo(value) => ModelChunk::ModelInfo(value.clone()),
                ModelChunk::Sequences(value) => ModelChunk::Sequences(value.clone()),
                ModelChunk::GlobalSequences(value) => ModelChunk::GlobalSequences(value.clone()),
                ModelChunk::Textures(value) => ModelChunk::Textures(value.clone()),
                ModelChunk::GeosetAnimations(value) => ModelChunk::GeosetAnimations(value.clone()),
                ModelChunk::Bones(value) => ModelChunk::Bones(value.clone()),
                ModelChunk::Helpers(value) => ModelChunk::Helpers(value.clone()),
                ModelChunk::Attachments(value) => ModelChunk::Attachments(value.clone()),
                ModelChunk::EventObjects(value) => ModelChunk::EventObjects(value.clone()),
                ModelChunk::CollisionShapes(value) => ModelChunk::CollisionShapes(value.clone()),
                ModelChunk::ParticleEmitters(value) => ModelChunk::ParticleEmitters(value.clone()),
                ModelChunk::ParticleEmitters2(value) => {
                    ModelChunk::ParticleEmitters2(value.clone())
                }
                ModelChunk::RibbonEmitters(value) => ModelChunk::RibbonEmitters(value.clone()),
                ModelChunk::PopcornEmitters(value) => ModelChunk::PopcornEmitters(value.clone()),
                ModelChunk::TextureAnimations(value) => {
                    ModelChunk::TextureAnimations(value.clone())
                }
                ModelChunk::FaceFx(value) => ModelChunk::FaceFx(value.clone()),
                ModelChunk::PivotPoints(value) => ModelChunk::PivotPoints(value.clone()),
                ModelChunk::BindPose(value) => ModelChunk::BindPose(value.clone()),
                ModelChunk::Gliders(value) => ModelChunk::Gliders(value.clone()),
            };
            macro_rules! normalize_nodes {
                ($value:expr, $name:literal, $kind:expr) => {
                    for (i, record) in $value.records.iter_mut().enumerate() {
                        normalize_node_kind(
                            &mut record.node,
                            $kind,
                            &mut context,
                            &format!("{path}.{}[{i}].node.flags", $name),
                        );
                    }
                };
            }
            match &mut converted {
                ModelChunk::Bones(value) => normalize_nodes!(value, "bones", 0x100),
                ModelChunk::Lights(value) => normalize_nodes!(value, "lights", 0x200),
                ModelChunk::EventObjects(value) => normalize_nodes!(value, "event_objects", 0x400),
                ModelChunk::Attachments(value) => normalize_nodes!(value, "attachments", 0x800),
                ModelChunk::ParticleEmitters(value) => {
                    normalize_nodes!(value, "particle_emitters", 0x1000)
                }
                ModelChunk::ParticleEmitters2(value) => {
                    normalize_nodes!(value, "particle_emitters2", 0x1000)
                }
                ModelChunk::PopcornEmitters(value) => {
                    normalize_nodes!(value, "popcorn_emitters", 0x1000)
                }
                ModelChunk::CollisionShapes(value) => {
                    normalize_nodes!(value, "collision_shapes", 0x2000)
                }
                ModelChunk::RibbonEmitters(value) => {
                    normalize_nodes!(value, "ribbon_emitters", 0x4000)
                }
                _ => {}
            }
            model.chunks.push(converted);
        }
        if model.chunk(*b"VERS").is_none() {
            model.chunks.insert(0, VersionChunk::<T>::new().into());
            context.issue(
                "VERS",
                ConversionIssueKind::Initialized,
                "inserted target version chunk",
            );
        }
        Ok(Conversion {
            model,
            report: context.report,
        })
    }
}

fn normalize_node_kind<F: NodeFlagInterpretation>(
    node: &mut Node<F>,
    kind: u32,
    context: &mut ConversionContext<'_>,
    path: &str,
) {
    // Only the seven object-kind bits are redundant with the enclosing record.
    // Transform, emitter behavior, and unknown bits must remain untouched.
    if node.flags.bits() & 0x7f00 == 0 {
        set_node_kind(node, kind);
        context.issue(
            path,
            ConversionIssueKind::Normalized,
            &format!("added missing node object-kind bit {kind:#x} inferred from record type"),
        );
    }
}

impl DynamicModel {
    /// Returns a normalized copy and its report without changing the runtime version.
    /// Uses the same rules as [`Model::normalized`] and leaves the source unchanged.
    pub fn normalized(&self) -> Result<Conversion<Self>, ConversionError> {
        macro_rules! normalize {
            ($($variant:ident),+) => {
                match self {
                    $(Self::$variant(model) => {
                        let converted = model.normalized()?;
                        Ok(Conversion {
                            model: Self::$variant(converted.model),
                            report: converted.report,
                        })
                    }),+
                }
            };
        }
        normalize!(V800, V900, V1000, V1100, V1200, V1300, V1400, V1600, V1800)
    }

    /// Converts a runtime-dispatched source to a typed target layout.
    pub fn convert<T: ModelVersion>(
        &self,
        options: &ConversionOptions,
    ) -> Result<Conversion<Model<T>>, ConversionError> {
        visit_model!(self, |model| model.convert::<T>(options))
    }
}