gdlib 0.4.0

Rust library for editing Geometry Dash savefiles
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
//! This module contains the GDObject struct, used for parsing to/from raw object strings
//! This module also contains the GDObjConfig metadata descriptor struct for GDObjects
use std::fmt::{Debug, Display, Write};

use crate::cclocallevels::{
    gdobj::{
        ids::properties::*,
        meta::{GDObjAttributes, GDObjConfig},
        structs::{ColourChannel, Event, GDObjPropType, GDValue, Group, MoveEasing, ZLayer},
    },
    properties::{self, OBJECT_NAMES, get_obj_property_type},
};

pub mod defaults;
/// This file contains all supported block ids and property ids.
/// This file is autogenerated by the build script.
pub mod ids {
    #![allow(missing_docs)]
    include!(concat!(env!("OUT_DIR"), "/ids.rs"));
}
pub mod constructors;
pub mod meta;
pub mod structs;

macro_rules! parse {
    ($v:expr => $t:ty) => {
        $v.parse::<$t>().unwrap_or_default()
    };
}

// for debug purposes

// fn parse_with_err_handle<T>(s: &str, p: u16) -> T
// where
//     T: FromStr + Default + Display,
//     <T as FromStr>::Err: Debug,
// {
//     match s.parse::<T>() {
//         Ok(n) => n,
//         Err(e) => {
//             println!(
//                 "Error with parsing property {p} with value {s}, type {} ({e:?})",
//                 type_name::<T>()
//             );
//             T::default()
//         }
//     }
// }

/// Container for GD Object properties.
#[derive(Clone, PartialEq)]
#[must_use]
pub struct GDObject {
    /// The object's ID.
    pub id: i32,
    /// General properties, such as position and scale.
    pub config: GDObjConfig,
    /// Object-specific properties
    pub properties: Vec<(u16, GDValue)>,
}

impl Display for GDObject {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut group_str = String::new();
        if !self.config.groups.is_empty() {
            group_str += " with groups: ";
            for (idx, g) in self.config.groups.iter().enumerate() {
                if idx != 0 {
                    group_str.push_str(", ");
                }
                let _ = write!(group_str, "{}", g.id());
            }
        }

        let mut trigger_conf_str = String::new();
        if self.config.trigger_cfg.spawnable || self.config.trigger_cfg.touchable {
            if self.config.trigger_cfg.multitriggerable {
                trigger_conf_str += "Multi";
            }
            if self.config.trigger_cfg.touchable {
                trigger_conf_str += "touchable ";
            } else if self.config.trigger_cfg.spawnable {
                trigger_conf_str += "spawnable ";
            }
        }

        write!(
            f,
            "{trigger_conf_str}{} @ ({}, {}) scaled to ({}, {}){} angled to {}°",
            self.get_name(),
            self.config.pos.0,
            self.config.pos.1,
            self.config.scale.0,
            self.config.scale.1,
            group_str,
            self.config.angle
        )
    }
}

impl Debug for GDObject {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut property_str = String::with_capacity(self.properties.len() * 32);

        for (property, value) in &self.properties {
            let desc = properties::PROPERTY_TABLE.get(property).map(|p| p.0);
            if let Some(d) = desc {
                write!(property_str, "\n    - {d}: {value:?}")
            } else {
                write!(property_str, "\n    - {property}: {value:?}")
            }
            .unwrap();
        }

        write!(
            f,
            "{} with properties:{property_str}",
            <Self as ToString>::to_string(self),
        )
    }
}

impl GDObject {
    /// Parses raw object string to `GDObject`
    pub fn parse_str<T: AsRef<str>>(s: T) -> GDObject {
        let s = s.as_ref();
        let mut obj = GDObject {
            id: 1,
            config: GDObjConfig::default(),
            properties: vec![],
        };

        let mut iter = s.trim_end_matches(';').split(',');
        while let (Some(idx), Some(val)) = (iter.next(), iter.next()) {
            let idx_u16 = match idx.parse::<u16>() {
                Ok(n) => n,
                Err(_) => match idx[2..].parse::<u16>() {
                    Ok(n) => n + 10_000,
                    Err(_) => 65535,
                },
            };

            match idx_u16 {
                OBJECT_ID => obj.id = parse!(val => i32),
                X_POS => obj.config.pos.0 = val.parse().unwrap_or(0.0),
                Y_POS => obj.config.pos.1 = val.parse().unwrap_or(0.0),
                ROTATION => obj.config.angle = val.parse().unwrap_or(0.0),
                TOUCH_TRIGGERABLE => obj.config.trigger_cfg.touchable = parse!(val => bool),
                SPAWN_TRIGGERABLE => obj.config.trigger_cfg.spawnable = parse!(val => bool),
                MULTITRIGGERABLE => obj.config.trigger_cfg.multitriggerable = parse!(val => bool),
                GROUPS => {
                    obj.config.add_groups(
                        val.trim_matches('"')
                            .split('.')
                            .filter_map(|g| g.parse::<i16>().ok())
                            .map(Group::Regular)
                            .collect::<Vec<Group>>(),
                    );
                }
                X_SCALE => obj.config.scale.0 = val.parse().unwrap_or(1.0),
                Y_SCALE => obj.config.scale.1 = val.parse().unwrap_or(1.0),
                EDITOR_LAYER_1 => obj.config.editor_layers.0 = parse!(val => i16),
                EDITOR_LAYER_2 => obj.config.editor_layers.1 = parse!(val => i16),
                OBJECT_COLOUR => {
                    obj.config.colour_channels.0 = ColourChannel::from(parse!(val => i16));
                }
                SECONDARY_COLOUR => {
                    obj.config.colour_channels.1 = ColourChannel::from(parse!(val => i16));
                }
                Z_LAYER => obj.config.z_layer = ZLayer::from(parse!(val => i32)),
                Z_ORDER => obj.config.z_order = parse!(val => i32),
                ENTER_EFFECT_CHANNEL => obj.config.enter_effect_channel = parse!(val => i16),
                OBJECT_MATERIAL => obj.config.material_id = parse!(val => i16),
                DONT_FADE => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::dont_fade, parse!(val => bool)),
                DONT_ENTER => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::dont_enter, parse!(val => bool)),
                NO_OBJECT_EFFECTS => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::no_effects, parse!(val => bool)),
                IS_GROUP_PARENT => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::is_group_parent, parse!(val => bool)),
                IS_AREA_PARENT => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::is_area_parent, parse!(val => bool)),
                DONT_BOOST_X => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::dont_boost_x, parse!(val => bool)),
                DONT_BOOST_Y => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::dont_boost_y, parse!(val => bool)),
                IS_HIGH_DETAIL => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::high_detail, parse!(val => bool)),
                NO_TOUCH => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::no_touch, parse!(val => bool)),
                PASSABLE => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::passable, parse!(val => bool)),
                HIDDEN => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::hidden, parse!(val => bool)),
                NONSTICK_X => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::non_stick_x, parse!(val => bool)),
                NONSTICK_Y => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::non_stick_y, parse!(val => bool)),
                EXTRA_STICKY => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::extra_sticky, parse!(val => bool)),
                HAS_EXTENDED_COLLISION => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::extended_collision, parse!(val => bool)),
                IS_ICE_BLOCK => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::is_ice_block, parse!(val => bool)),
                GRIP_SLOPE => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::grip_slope, parse!(val => bool)),
                NO_GLOW => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::no_glow, parse!(val => bool)),
                NO_PARTICLES => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::no_particles, parse!(val => bool)),
                SCALE_STICK => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::scale_stick, parse!(val => bool)),
                NO_AUDIO_SCALE => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::no_audio_scale, parse!(val => bool)),
                SINGLE_PLAYER_TOUCH => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::single_ptouch, parse!(val => bool)),
                CENTER_EFFECT => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::center_effect, parse!(val => bool)),
                REVERSES_GAMEPLAY => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::reverse, parse!(val => bool)),
                MATERIAL_CONTROL_ID => obj.config.control_id = parse!(val => i16),
                PARENT_GROUPS => {
                    // add groups method handles deduping
                    obj.config.add_groups(
                        val.trim_matches('"')
                            .split('.')
                            .filter_map(|g| g.parse::<i16>().ok())
                            .map(Group::Parent)
                            .collect::<Vec<Group>>(),
                    );
                }
                n => obj.set_property_raw(n, val),
            }
        }

        obj
    }

    fn set_property_raw(&mut self, p: u16, value: &str) {
        self.set_property(
            p,
            GDValue::from(
                get_obj_property_type(p).unwrap_or(GDObjPropType::Unknown),
                value,
            ),
        );
    }

    /// Sets the prpoerty ID to the value, and craetes it if it doesn't exist
    pub fn set_property(&mut self, p: u16, val: GDValue) {
        match self.properties.binary_search_by_key(&p, |t| t.0) {
            Ok(idx) => self.properties[idx].1 = val,
            Err(idx) => self.properties.insert(idx, (p, val)),
        }
    }

    /// Removes the property from this object's property map by its ID.
    pub fn del_property(&mut self, p: u16) {
        if let Ok(idx) = self.properties.binary_search_by_key(&p, |t| t.0) {
            let _ = self.properties.remove(idx);
        }
    }

    /// Returns this object as a property string
    #[must_use]
    pub fn serialise_to_string(&self) -> String {
        let mut properties_string = String::with_capacity(self.properties.len() * 8);
        for (idx, val) in &self.properties {
            let (pref, id) = if *idx < 10_000 {
                ("", *idx)
            } else {
                ("kA", idx - 10_000) // also need to add a "kA" prepend
            };

            write!(properties_string, ",{pref}{id},{val}").unwrap();
        }
        let config_str = self.config.serialise_to_string();

        let mut raw_str = format!("1,{}{config_str}{properties_string}", self.id);
        raw_str.retain(|c| c != '"');
        raw_str.push(';');
        raw_str
    }

    /// Returns this object's name
    #[inline]
    #[must_use]
    pub fn get_name(&self) -> String {
        OBJECT_NAMES
            .iter()
            .find(|&o| o.0 == self.id)
            .unwrap_or(&(0, format!("Object {}", self.id).as_str()))
            .1
            .to_string()
    }

    /// Creates a new GDObject from ID, config, and extra proerties
    #[inline]
    pub fn new(id: i32, config: &GDObjConfig, properties: Vec<(u16, GDValue)>) -> Self {
        GDObject {
            id,
            config: config.clone(),
            properties,
        }
    }

    #[inline]
    /// Creates a default object from the specified ID
    pub fn default_from_id(id: i32) -> Self {
        defaults::default_object(id)
    }

    #[inline]
    fn get_attr_as_gdvalue(&self, attr: GDObjAttributes) -> GDValue {
        GDValue::Bool(self.config.get_attribute_flag(attr))
    }

    /// Fetches a property from this object's configuration
    pub fn get_property(&self, p: u16) -> Option<GDValue> {
        match p {
            // one of the most fascinating matches of all time
            1 => Some(GDValue::Int(self.id)),
            2 => Some(GDValue::Float(self.config.pos.0)),
            3 => Some(GDValue::Float(self.config.pos.1)),
            6 => Some(GDValue::Float(self.config.angle)),
            11 => Some(GDValue::Bool(self.config.trigger_cfg.touchable)),
            57 => Some(GDValue::from_group_list(&self.config.groups)),
            62 => Some(GDValue::Bool(self.config.trigger_cfg.spawnable)),
            87 => Some(GDValue::Bool(self.config.trigger_cfg.multitriggerable)),
            128 => Some(GDValue::Float(self.config.scale.0)),
            129 => Some(GDValue::Float(self.config.scale.1)),
            20 => Some(GDValue::Short(self.config.editor_layers.0)),
            61 => Some(GDValue::Short(self.config.editor_layers.1)),
            21 => Some(GDValue::Short(self.config.colour_channels.0.into())),
            22 => Some(GDValue::Short(self.config.colour_channels.1.into())),
            24 => Some(GDValue::ZLayer(self.config.z_layer)),
            25 => Some(GDValue::Int(self.config.z_order)),
            343 => Some(GDValue::Short(self.config.enter_effect_channel)),
            446 => Some(GDValue::Short(self.config.material_id)),
            534 => Some(GDValue::Short(self.config.control_id)),
            64 => Some(self.get_attr_as_gdvalue(GDObjAttributes::dont_fade)),
            67 => Some(self.get_attr_as_gdvalue(GDObjAttributes::dont_enter)),
            116 => Some(self.get_attr_as_gdvalue(GDObjAttributes::no_effects)),
            34 => Some(self.get_attr_as_gdvalue(GDObjAttributes::is_group_parent)),
            279 => Some(self.get_attr_as_gdvalue(GDObjAttributes::is_area_parent)),
            509 => Some(self.get_attr_as_gdvalue(GDObjAttributes::dont_boost_x)),
            496 => Some(self.get_attr_as_gdvalue(GDObjAttributes::dont_boost_y)),
            103 => Some(self.get_attr_as_gdvalue(GDObjAttributes::high_detail)),
            121 => Some(self.get_attr_as_gdvalue(GDObjAttributes::no_touch)),
            134 => Some(self.get_attr_as_gdvalue(GDObjAttributes::passable)),
            135 => Some(self.get_attr_as_gdvalue(GDObjAttributes::hidden)),
            136 => Some(self.get_attr_as_gdvalue(GDObjAttributes::non_stick_x)),
            289 => Some(self.get_attr_as_gdvalue(GDObjAttributes::non_stick_y)),
            495 => Some(self.get_attr_as_gdvalue(GDObjAttributes::extra_sticky)),
            511 => Some(self.get_attr_as_gdvalue(GDObjAttributes::extended_collision)),
            137 => Some(self.get_attr_as_gdvalue(GDObjAttributes::is_ice_block)),
            193 => Some(self.get_attr_as_gdvalue(GDObjAttributes::grip_slope)),
            96 => Some(self.get_attr_as_gdvalue(GDObjAttributes::no_glow)),
            507 => Some(self.get_attr_as_gdvalue(GDObjAttributes::no_particles)),
            356 => Some(self.get_attr_as_gdvalue(GDObjAttributes::scale_stick)),
            372 => Some(self.get_attr_as_gdvalue(GDObjAttributes::no_audio_scale)),
            284 => Some(self.get_attr_as_gdvalue(GDObjAttributes::single_ptouch)),
            369 => Some(self.get_attr_as_gdvalue(GDObjAttributes::center_effect)),
            117 => Some(self.get_attr_as_gdvalue(GDObjAttributes::reverse)),

            _ => self
                .properties
                .binary_search_by_key(&p, |(key, _)| *key)
                .ok()
                .map(|idx| self.properties[idx].1.clone()),
        }
    }

    /// Set this object's internal config
    pub fn set_config(&mut self, config: GDObjConfig) {
        self.config = config;
    }
}