quake-util 0.4.0

A utility library for using Quake file formats
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
#[cfg(feature = "std")]
extern crate std;

extern crate alloc;

#[cfg(feature = "std")]
use std::io;

use {
    alloc::ffi::CString, alloc::format, alloc::string::String, alloc::vec::Vec,
    core::ffi::CStr,
};

#[cfg(feature = "std")]
use crate::{WriteAttempt, WriteError};

/// Return type for validating writability of entities and other items
pub type ValidationResult = Result<(), String>;

/// Validation of entities and other items
pub trait CheckWritable {
    /// Determine if an item can be written to file
    ///
    /// Note that passing this check only implies that the item can be written
    /// to file and can also be parsed back non-destructively.  It is up to the
    /// consumer to ensure that the maps written are in a form that can be used
    /// by other tools, e.g. qbsp.
    fn check_writable(&self) -> ValidationResult;
}

/// 3-dimensional point used to determine the half-space a surface lies on
pub type Point = [f64; 3];
pub type Vec3 = [f64; 3];
pub type Vec2 = [f64; 2];

/// Transparent data structure representing a Quake source map
///
/// Contains a list of entities. Internal texture alignments may be in the
/// original "legacy" Id format, the "Valve 220" format, or a mix of the two.
#[derive(Clone, Debug)]
pub struct QuakeMap {
    pub entities: Vec<Entity>,
}

impl QuakeMap {
    /// Instantiate a new map with 0 entities
    pub const fn new() -> Self {
        QuakeMap {
            entities: Vec::new(),
        }
    }

    /// Writes the map to the provided writer in text format, failing if
    /// validation fails or an I/O error occurs
    #[cfg(feature = "std")]
    pub fn write_to<W: io::Write>(&self, writer: &mut W) -> WriteAttempt {
        for ent in &self.entities {
            ent.write_to(writer)?;
        }
        Ok(())
    }
}

impl Default for QuakeMap {
    fn default() -> Self {
        Self::new()
    }
}

impl CheckWritable for QuakeMap {
    fn check_writable(&self) -> ValidationResult {
        for ent in &self.entities {
            ent.check_writable()?;
        }

        Ok(())
    }
}

/// Entity type: `Brush` for entities with brushes, `Point` for entities without
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum EntityKind {
    Point,
    Brush,
}

/// A collection of key/value pairs in the form of an *edict* and 0 or more
/// brushes
#[derive(Clone, Debug)]
pub struct Entity {
    pub edict: Edict,
    pub brushes: Vec<Brush>,
}

impl Entity {
    /// Instantiate a new entity without any keyvalues or brushes
    pub fn new() -> Self {
        Entity {
            edict: Edict::new(),
            brushes: Vec::new(),
        }
    }

    /// Determine whether this is a point or brush entity
    pub fn kind(&self) -> EntityKind {
        if self.brushes.is_empty() {
            EntityKind::Point
        } else {
            EntityKind::Brush
        }
    }

    #[cfg(feature = "std")]
    pub fn write_to<W: io::Write>(&self, writer: &mut W) -> WriteAttempt {
        self.check_writable().map_err(WriteError::Validation)?;

        writer.write_all(b"{\r\n").map_err(WriteError::Io)?;

        write_edict_to(&self.edict, writer)?;

        for brush in &self.brushes {
            write_brush_to(brush, writer)?;
        }

        writer.write_all(b"}\r\n").map_err(WriteError::Io)?;
        Ok(())
    }
}

impl Default for Entity {
    /// Same as `Entity::new`
    fn default() -> Self {
        Entity::new()
    }
}

impl CheckWritable for Entity {
    fn check_writable(&self) -> ValidationResult {
        self.edict.check_writable()?;

        for brush in &self.brushes {
            brush.check_writable()?
        }

        Ok(())
    }
}

/// Entity dictionary
pub type Edict = Vec<(CString, CString)>;

impl CheckWritable for Edict {
    fn check_writable(&self) -> ValidationResult {
        for (k, v) in self {
            check_writable_quoted(k)?;
            check_writable_quoted(v)?;
        }

        Ok(())
    }
}

/// Convex polyhedron
pub type Brush = Vec<Surface>;

impl CheckWritable for Brush {
    fn check_writable(&self) -> ValidationResult {
        for surface in self {
            surface.check_writable()?;
        }

        Ok(())
    }
}

/// Brush face
///
/// Set `q2ext` to its default (`Default::default()`) value to create a surface
/// compatible for Quake 1 tools
#[derive(Clone, Debug)]
pub struct Surface {
    pub half_space: HalfSpace,
    pub texture: CString,
    pub alignment: Alignment,
    pub q2ext: Quake2SurfaceExtension,
}

impl Surface {
    #[cfg(feature = "std")]
    fn write_to<W: io::Write>(&self, writer: &mut W) -> WriteAttempt {
        write_half_space_to(&self.half_space, writer)?;
        writer.write_all(b" ").map_err(WriteError::Io)?;
        write_texture_to(&self.texture, writer)?;
        writer.write_all(b" ").map_err(WriteError::Io)?;
        self.alignment.write_to(writer)?;

        if !self.q2ext.is_zeroed() {
            writer.write_all(b" ").map_err(WriteError::Io)?;
            self.q2ext.write_to(writer)?;
        }

        Ok(())
    }
}

impl CheckWritable for Surface {
    fn check_writable(&self) -> ValidationResult {
        self.half_space.check_writable()?;
        check_writable_texture(&self.texture)?;
        self.alignment.check_writable()
    }
}

/// A set of 3 points that determine a plane with its facing direction
/// determined by the winding order of the points
pub type HalfSpace = [Point; 3];

impl CheckWritable for HalfSpace {
    fn check_writable(&self) -> ValidationResult {
        for num in self.iter().flatten() {
            check_writable_f64(*num)?;
        }

        Ok(())
    }
}

/// Texture alignment properties
///
/// If axes are present, the alignment will be written in the "Valve220" format;
/// otherwise it will be written in the "legacy" format pre-dating Valve220.
#[derive(Clone, Copy, Debug)]
pub struct Alignment {
    pub offset: Vec2,
    pub rotation: f64,
    pub scale: Vec2,

    /// Describes the X and Y texture-space axes
    pub axes: Option<[Vec3; 2]>,
}

impl Alignment {
    #[cfg(feature = "std")]
    fn write_to<W: io::Write>(&self, writer: &mut W) -> WriteAttempt {
        match self.axes {
            None => {
                write!(
                    writer,
                    "{} {} {} {} {}",
                    self.offset[0],
                    self.offset[1],
                    self.rotation,
                    self.scale[0],
                    self.scale[1]
                )
                .map_err(WriteError::Io)?;
            }
            Some([u, v]) => {
                write!(
                    writer,
                    "[ {} {} {} {} ] [ {} {} {} {} ] {} {} {}",
                    u[0],
                    u[1],
                    u[2],
                    self.offset[0],
                    v[0],
                    v[1],
                    v[2],
                    self.offset[1],
                    self.rotation,
                    self.scale[0],
                    self.scale[1]
                )
                .map_err(WriteError::Io)?;
            }
        }
        Ok(())
    }
}

/// Quake II Surface Extension
///
/// Additional fields for surfaces to support Quake II maps.  Contains two
/// bit fields (up to 31 bits in each; negative values are non-standard, but
/// a signed type is used for consistency with existing tools) and a floating-
/// point value (_ought_ to be an integer, but TrenchBroom allows writing
/// floats).
#[derive(Clone, Copy, Debug)]
pub struct Quake2SurfaceExtension {
    /// Flags describing contents of the brush
    pub content_flags: i32,

    /// Flags describing the surface
    pub surface_flags: i32,

    /// Value associated with surface, e.g. light value for emissive surfaces
    pub surface_value: f64,
}

impl Quake2SurfaceExtension {
    /// Returns true if all fields are 0, otherwise false.  Behavior is
    /// undefined if `surface_value` is NaN (read: behavior may change between
    /// revisions without remark).
    pub fn is_zeroed(&self) -> bool {
        self.content_flags == 0
            && self.surface_flags == 0
            && self.surface_value == 0.0
    }

    #[cfg(feature = "std")]
    fn write_to<W: io::Write>(&self, writer: &mut W) -> WriteAttempt {
        write!(
            writer,
            "{} {} {}",
            self.content_flags, self.surface_flags, self.surface_value,
        )
        .map_err(WriteError::Io)?;

        Ok(())
    }
}

impl Default for Quake2SurfaceExtension {
    fn default() -> Self {
        Self {
            content_flags: 0,
            surface_flags: 0,
            surface_value: 0.0,
        }
    }
}

impl CheckWritable for Alignment {
    fn check_writable(&self) -> ValidationResult {
        check_writable_array(self.offset)?;
        check_writable_f64(self.rotation)?;
        check_writable_array(self.scale)?;

        if let Some(axes) = self.axes {
            for axis in axes {
                check_writable_array(axis)?;
            }
        }

        Ok(())
    }
}

#[cfg(feature = "std")]
fn write_edict_to<W: io::Write>(edict: &Edict, writer: &mut W) -> WriteAttempt {
    for (key, value) in edict {
        writer.write_all(b"\"").map_err(WriteError::Io)?;
        writer.write_all(key.as_bytes()).map_err(WriteError::Io)?;
        writer.write_all(b"\" \"").map_err(WriteError::Io)?;
        writer.write_all(value.as_bytes()).map_err(WriteError::Io)?;
        writer.write_all(b"\"\r\n").map_err(WriteError::Io)?;
    }
    Ok(())
}

#[cfg(feature = "std")]
fn write_brush_to<W: io::Write>(brush: &Brush, writer: &mut W) -> WriteAttempt {
    writer.write_all(b"{\r\n").map_err(WriteError::Io)?;

    for surf in brush {
        surf.write_to(writer)?;
        writer.write_all(b"\r\n").map_err(WriteError::Io)?;
    }

    writer.write_all(b"}\r\n").map_err(WriteError::Io)?;
    Ok(())
}

#[cfg(feature = "std")]
fn write_half_space_to<W: io::Write>(
    half_space: &HalfSpace,
    writer: &mut W,
) -> WriteAttempt {
    for (index, pt) in half_space.iter().enumerate() {
        writer.write_all(b"( ").map_err(WriteError::Io)?;

        for element in pt.iter() {
            write!(writer, "{} ", element).map_err(WriteError::Io)?;
        }

        writer.write_all(b")").map_err(WriteError::Io)?;

        if index != 2 {
            writer.write_all(b" ").map_err(WriteError::Io)?;
        }
    }
    Ok(())
}

#[cfg(feature = "std")]
fn write_texture_to<W: io::Write>(
    texture: &CStr,
    writer: &mut W,
) -> WriteAttempt {
    let needs_quotes =
        texture.to_bytes().iter().any(|c| c.is_ascii_whitespace())
            || texture.to_bytes().is_empty();

    if needs_quotes {
        writer.write_all(b"\"").map_err(WriteError::Io)?;
    }

    writer
        .write_all(texture.to_bytes())
        .map_err(WriteError::Io)?;

    if needs_quotes {
        writer.write_all(b"\"").map_err(WriteError::Io)?;
    }

    Ok(())
}

fn check_writable_array<const N: usize>(arr: [f64; N]) -> ValidationResult {
    for num in arr {
        check_writable_f64(num)?;
    }

    Ok(())
}

fn check_writable_f64(num: f64) -> ValidationResult {
    if num.is_finite() {
        Ok(())
    } else {
        Err(format!("Non-finite number ({})", num))
    }
}

fn check_writable_texture(s: &CStr) -> ValidationResult {
    if check_writable_unquoted(s).is_ok() {
        return Ok(());
    }

    match check_writable_quoted(s) {
        Ok(_) => Ok(()),
        Err(_) => Err(format!(
            "Cannot write texture {:?}, not quotable and contains whitespace",
            s
        )),
    }
}

fn check_writable_quoted(s: &CStr) -> ValidationResult {
    let bad_chars = [b'"', b'\r', b'\n'];

    for c in s.to_bytes() {
        if bad_chars.contains(c) {
            return Err(format!(
                "Cannot write quote-wrapped string, contains {:?}",
                char::from(*c)
            ));
        }
    }

    Ok(())
}

fn check_writable_unquoted(s: &CStr) -> ValidationResult {
    let s_bytes = s.to_bytes();

    if s_bytes.is_empty() {
        return Err(String::from("Cannot write unquoted empty string"));
    }

    if s_bytes[0] == b'"' {
        return Err(String::from("Cannot lead unquoted string with quote"));
    }

    if contains_ascii_whitespace(s) {
        Err(String::from(
            "Cannot write unquoted string, contains whitespace",
        ))
    } else {
        Ok(())
    }
}

fn contains_ascii_whitespace(s: &CStr) -> bool {
    s.to_bytes().iter().any(|c| c.is_ascii_whitespace())
}