celeste_rs 0.5.1

Library for working with files related to Celeste and it's modding scene.
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
//! Implements reading and writing of Celeste's map format
//! along with providing helper structs for all the map elements seen in the vanilla game
use std::{
    any::Any,
    collections::HashMap,
    fmt::{Debug, Display},
    io::{Read, Write},
};

pub mod elements;
pub mod encoder;
pub mod lookup;
pub mod parser;
pub mod reader;
pub mod var_types;
pub mod writer;
use elements::*;
pub use lookup::*;

use crate::maps::{
    encoder::MapEncoder,
    entities::{Entity, MapEntity},
    parser::{ElementParser, ElementParserImpl, MapElementParsingError, MapParser},
    reader::{MapReadError, MapReader},
    triggers::{MapTrigger, Trigger},
    var_types::EncodedVar,
    writer::{MapWriteError, MapWriter},
};

#[derive(Debug, Clone)]
/// The raw structure of an element in the map binary
///
/// All elements get parsed to this before being parsed into proper structs.
pub struct RawMapElement {
    pub name: ResolvableString,
    pub attributes: Vec<MapAttribute>,
    pub children: Vec<RawMapElement>,
}

#[derive(Debug, Clone)]
/// An attribute attached to a map element
pub struct MapAttribute {
    pub name: ResolvableString,
    pub value: EncodedVar,
}

impl MapAttribute {
    pub fn new(name: ResolvableString, value: impl Into<EncodedVar>) -> Self {
        MapAttribute {
            name,
            value: value.into(),
        }
    }
}

#[derive(Debug)]
/// The raw format of the map binary, is parsed into a [MapRoot]
pub struct RawMap {
    pub name: String,
    pub lookup_table: LookupTable,
    pub root_element: RawMapElement,
}

impl RawMap {
    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self, MapReadError> {
        let mut reader = MapReader::new(bytes);

        let check_string = reader.read_string()?;

        if check_string != "CELESTE MAP" {
            return Err(MapReadError::InvalidHeader(check_string));
        }

        let name = reader.read_string()?;
        let lookup_table = reader.read_lookup_table()?;
        let root_element = reader.read_element()?;

        Ok(Self {
            name,
            lookup_table,
            root_element,
        })
    }

    fn to_bytes(&self) -> Result<Vec<u8>, MapWriteError> {
        let mut writer = MapWriter::new();

        writer.write_string("CELESTE MAP");

        writer.write_string(&self.name);
        writer.write_lookup_table(&self.lookup_table);
        writer.write_element(&self.root_element)?;

        Ok(writer.bytes())
    }

    /// Resolve all the [ResolvableString]s stored in the map
    ///
    /// This should be called directly after reading in the map file,
    /// as modifications can change the lookup table without updating the indicies.
    ///
    /// Note: not needed if using a [MapManager]
    pub fn resolve_strings(&mut self) {
        self.root_element.resolve_strings(&self.lookup_table);
    }

    /// Converts all the [ResolvableString]s to indicies in the lookup table.
    ///
    /// This should be done only right before you serialize.
    /// The indicies change on pretty much any change to the map data.
    ///
    /// Note: not needed if using a [MapManager]
    pub fn unresolve_strings(&mut self) {
        self.root_element
            .add_attr_value_strs(&mut self.lookup_table);
        self.root_element.unresolve_strings(&mut self.lookup_table);
    }
}

impl Display for RawMap {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} {{\n\tlookup_table: {}\n\troot_element: {}\n}}",
            &self.name,
            self.lookup_table.to_string(2),
            self.root_element.to_string(2, &self.lookup_table)
        )
    }
}

impl RawMapElement {
    fn to_string(&self, depth: u8, lookup_table: &LookupTable) -> String {
        let mut buf = String::new();

        buf.push_str(self.name.to_string(lookup_table));
        buf.push_str(" {\n");

        for _ in 0 .. depth {
            buf.push('\t');
        }

        buf.push_str("attributes: [");

        for attr in &self.attributes {
            buf.push('\n');
            for _ in 0 .. depth + 1 {
                buf.push('\t');
            }
            buf.push_str(&attr.to_string(lookup_table));
        }

        if !self.attributes.is_empty() {
            buf.push('\n');
            for _ in 0 .. depth {
                buf.push('\t');
            }
        }

        buf.push_str("],\n");
        for _ in 0 .. depth {
            buf.push('\t');
        }

        buf.push_str("children: [");

        for child in &self.children {
            buf.push('\n');
            for _ in 0 .. depth {
                buf.push('\t');
            }

            buf.push_str(&child.to_string(depth + 1, lookup_table));
        }

        if !self.children.is_empty() {
            buf.push('\n');
            for _ in 0 .. depth {
                buf.push('\t');
            }
        }

        buf.push_str("]\n");
        for _ in 0 .. depth - 1 {
            buf.push('\t');
        }
        buf.push('}');

        buf
    }

    fn resolve_strings(&mut self, lookup_table: &LookupTable) {
        self.name.resolve(lookup_table);

        for attr in &mut self.attributes {
            attr.name.resolve(lookup_table);

            if let EncodedVar::LookupIndex(i) = attr.value {
                attr.value = lookup_table[i].clone().into()
            }
        }

        for child in &mut self.children {
            child.resolve_strings(lookup_table)
        }
    }

    fn add_attr_value_strs(&self, lookup_table: &mut LookupTable) {
        for attr in &self.attributes {
            if let EncodedVar::String(str) = &attr.value {
                lookup_table.add_string(str);
            }
        }

        for child in &self.children {
            child.add_attr_value_strs(lookup_table);
        }
    }

    fn unresolve_strings(&mut self, lookup_table: &mut LookupTable) {
        self.name.to_index(lookup_table);

        for attr in &mut self.attributes {
            attr.name.to_index(lookup_table);

            if let EncodedVar::String(str) = &attr.value {
                if let Some(idx) = lookup_table.lookup_string(str) {
                    attr.value = EncodedVar::LookupIndex(idx);
                }
            }
        }

        for child in &mut self.children {
            child.unresolve_strings(lookup_table);
        }
    }
}

impl MapAttribute {
    fn to_string(&self, lookup_table: &LookupTable) -> String {
        format!(
            "{}: {}",
            self.name.to_string(lookup_table),
            self.value.to_string(lookup_table)
        )
    }
}

/// A trait to represent an element of a map.
pub trait MapElement: Any + Debug {
    /// The name of the element in the map binary
    const NAME: &'static str;

    fn from_raw(parser: MapParser) -> Result<Self, MapElementParsingError>
    where Self: Sized;
    fn to_raw(&self, encoder: &mut MapEncoder);
}

/// An object-safe version of [MapElement]
pub trait ErasedMapElement: Any + Debug {
    fn name(&self) -> &str;
    fn from_raw(parser: MapParser) -> Result<Self, MapElementParsingError>
    where Self: Sized;
    fn to_raw(&self, encoder: &mut MapEncoder);
}

impl<T: MapElement> ErasedMapElement for T {
    fn name(&self) -> &'static str {
        T::NAME
    }

    fn from_raw(parser: MapParser) -> Result<Self, MapElementParsingError>
    where Self: Sized {
        T::from_raw(parser)
    }

    fn to_raw(&self, encoder: &mut MapEncoder) {
        self.to_raw(encoder)
    }
}

// This allows us to parse optional children when using MapParser::child
// BUT add_parser shouldn't be called with Option
// It'll probably be fine because of monomorphization
// so Option<u8> and Option<u16> are different
// BUT still doesn't make sense to allow this when parsing dyn elements
// impl<T: MapElement> MapElement for Option<T> {
//     const NAME: &'static str = T::NAME;

//     fn from_raw(parser: MapParser) -> Result<Self, MapElementParsingError>
//     where Self: Sized {
//         Ok(parser.parse_element::<T>().ok())
//     }

//     fn to_raw(&self, encoder: &mut MapEncoder) {
//         if let Some(t) = self {
//             t.to_raw(encoder)
//         }
//     }
// }

/// A dynamic element, if a parser for the element was registered it will be parsed into that struct, otherwise it is a [RawMapElement]
///
/// You can check what the element is with [ErasedMapElement::name], and check if the element is parsed using [Any::type_id]
pub type DynMapElement = Box<dyn ErasedMapElement>;

impl ErasedMapElement for RawMapElement {
    fn name(&self) -> &str {
        self.name.as_str().unwrap_or("UNRESOLVED STRING")
    }

    fn from_raw(parser: MapParser) -> Result<Self, MapElementParsingError>
    where Self: Sized {
        Ok(parser.raw.clone())
    }

    fn to_raw(&self, encoder: &mut MapEncoder) {
        encoder.from_raw(self)
    }
}


impl ErasedMapElement for Box<dyn ErasedMapElement> {
    fn name(&self) -> &str {
        self.as_ref().name()
    }

    fn from_raw(_parser: MapParser) -> Result<Self, MapElementParsingError>
    where Self: Sized {
        Err(MapElementParsingError::custom(
            "can't use trait object for from_raw",
        ))
    }

    fn to_raw(&self, encoder: &mut MapEncoder) {
        (**self).to_raw(encoder)
    }
}

/// A manager struct that can read and write celeste maps.
pub struct MapManager {
    map: RawMap,
    parsers: HashMap<&'static str, Box<dyn ElementParserImpl>>,
}

impl MapManager {
    /// Creates a new `MapManager` reading in a celeste map from the passed reader
    pub fn new(mut reader: impl Read) -> Result<Self, MapReadError> {
        let mut buf = Vec::new();

        reader.read_to_end(&mut buf)?;

        let mut raw = RawMap::from_bytes(buf)?;

        let parsers = HashMap::new();

        raw.resolve_strings();

        Ok(MapManager { map: raw, parsers })
    }

    /// Parse the map passed in the constructor using any registered parsers when needed
    pub fn parse_map(&self) -> Result<MapRoot, MapElementParsingError> {
        let parser = MapParser {
            verbose_debug: false,
            lookup: &self.map.lookup_table,
            raw: &self.map.root_element,
            parsers: &self.parsers,
        };

        parser.parse_self::<MapRoot>()
    }

    /// Same as [parse_map](Self::parse_map) but when compiled with `debug_assertions` will
    /// print debug information about the parser
    pub fn verbose_parse(&self) -> Result<MapRoot, MapElementParsingError> {
        let parser = MapParser {
            verbose_debug: cfg!(debug_assertions),
            lookup: &self.map.lookup_table,
            raw: &self.map.root_element,
            parsers: &self.parsers,
        };

        parser.parse_self::<MapRoot>()
    }

    /// Encode the map data back into a [RawMap]. The raw map is stored in the manager itself.
    pub fn encode_map(&mut self, name: impl ToString, root: &MapRoot) {
        let mut lookup = LookupTable::new();

        let root_name = lookup.index_string(MapRoot::NAME);

        let mut encoder = MapEncoder {
            lookup: &mut lookup,
            element_name: root_name,
            children: Vec::new(),
            attrs: Vec::new(),
        };

        MapElement::to_raw(root, &mut encoder);

        self.map.root_element = encoder.resolve();
        self.map.name = name.to_string();
        self.map.lookup_table = lookup;

        self.map.unresolve_strings();
    }

    /// Allows the `MapManager` to parse a new type of [MapElement].
    ///
    /// All [MapElement] implementations in this crate can be added via [MapManager::default_parsers].
    ///
    /// This is used exclusively for parsing [DynMapElement]s
    /// during calls to [MapParser::parse_any_element] any calls to [MapParser::parse_element] or [MapParser::parse_all_elements] will work even if a parser is never registered.
    ///
    /// This generally should not be called with any `Option<T>`, as that will conflict with the parser for `T`.
    /// There is no place in the vanilla elements where having a [DynMapElement] be optional makes sense and so
    /// no `Option<T>` impls are registered by default.
    pub fn add_parser<T: MapElement>(&mut self) {
        self.parsers
            .insert(T::NAME, Box::new(ElementParser::<T>::new()));
    }

    /// Allows the `MapManager` to parse a new type of [Entity]
    ///
    /// Acts the same as (add_parser)[MapManager::add_parser] but for entities
    pub fn add_entity_parser<T: Entity>(&mut self) {
        self.add_parser::<MapEntity<T>>();
    }

    /// Gets a reference to the [RawMap] stored in the manager.
    ///
    /// This is initialized in the constructor and modified in [encode_map](Self::encode_map)
    pub fn map(&self) -> &RawMap {
        &self.map
    }

    /// Allows the `MapManager` to parse a new type of [Trigger]
    ///
    /// Acts the same as (add_parser)[MapManager::add_parser] but for triggers
    pub fn add_trigger_parser<T: Trigger>(&mut self) {
        self.add_parser::<MapTrigger<T>>();
    }

    /// Writes the stored map data as binary into the provided writer
    pub fn write_map(&mut self, writer: &mut impl Write) -> std::io::Result<()> {
        writer.write_all(&self.map.to_bytes()?)
    }
}