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
use super::scene_helper::*;
use babalcore::*;
use gdnative::api::GridMap;
use gdnative::prelude::*;

#[derive(NativeClass)]
#[inherit(Spatial)]
pub struct Tunnel {
    data: Option<Data>,
    template: Option<Ref<PackedScene, ThreadLocal>>,
    grid_scale: Vector3,
    level_row: isize,
    level_col: isize,
    player_position: Vector3,
    player_best_row: isize,
    now_sec: f64,
}

struct Data {
    level: Level,
    rail_resource_name: String,
}

const LENGTH_MARGIN: usize = 100;
const SLAB_SIZE: f32 = 1.0;
const RAIL_OFFSET: isize = 2;
const RAIL_FAR_VIEW: isize = 30;

#[methods]
impl Tunnel {
    fn new(_owner: &Spatial) -> Self {
        Tunnel {
            data: None,
            template: None,
            grid_scale: Vector3::new(1.0, 1.0, 1.0),
            level_row: 0,
            level_col: 0,
            player_position: Vector3::default(),
            player_best_row: 0,
            now_sec: 0.0,
        }
    }

    #[export]
    fn _ready(&self, _owner: &Spatial) {
        godot_print!("Tunnel is ready.");
    }

    #[export]
    fn _process(&mut self, owner: &Spatial, delta: f64) {
        self.now_sec += delta;
        self.sync(owner);
    }

    #[export]
    fn setup(
        &mut self,
        owner: &Spatial,
        rail_resource_name: GodotString,
        width: usize,
        length: usize,
    ) {
        godot_print!("Tunnel setup {}x{}.", width, length);
        let mut level = Level::new(0, width, Skill::Easy);
        Self::generate_missing(&mut level, 0);
        let data = Data {
            level,
            rail_resource_name: rail_resource_name.to_string(),
        };
        self.template = load_scene(data.rail_resource_name.as_str());
        match &self.template {
            Some(_) => godot_print!(
                "Loaded template rail scene \"{}\".",
                data.rail_resource_name
            ),
            None => godot_print!(
                "Unable to load rail scene \"{}\", please check name.",
                data.rail_resource_name
            ),
        };
        self.data = Some(data);

        self.remove_all_children(owner);
        self.add_all_rails(owner);
        match self.get_grid_scale(owner) {
            Ok(scale) => self.grid_scale = scale,
            Err(e) => godot_print!("unable to get grid scale: {}", e),
        }
        self.sync(owner);
    }

    fn generate_missing(level: &mut Level, row: isize) {
        while level.last() < row + (LENGTH_MARGIN as isize) {
            level.generate(LENGTH_MARGIN);
        }
    }

    #[export]
    fn remove_last_child(&mut self, owner: &Spatial) -> bool {
        let num_children = owner.get_child_count();
        if num_children <= 0 {
            return false;
        }

        let last_child = owner.get_child(num_children - 1);
        if let Some(node) = last_child {
            owner.remove_child(node);
            unsafe {
                node.assume_safe().queue_free();
            }
        }

        return num_children == owner.get_child_count() + 1;
    }

    #[export]
    fn remove_all_children(&mut self, owner: &Spatial) -> usize {
        let mut removed: usize = 0;
        while self.remove_last_child(owner) {
            removed += 1;
        }
        removed
    }

    fn prepare_rail_grid(&self, grid: &Spatial, n: usize) {
        let w: f32 = SLAB_SIZE * std::f32::consts::PI * 2f32 / n as f32;
        let mut translation = grid.translation();
        translation.x = -w / 2f32;
        grid.set_translation(translation);
        let mut scale = grid.scale();
        scale.x = w;
        grid.set_scale(scale);
    }

    fn prepare_rail(&self, rail: &Spatial, i: usize, n: usize) {
        let key_str = format!("rail_{}", i);
        rail.set_name(&key_str);
        let angle: f64 = i as f64 * 360f64 / n as f64;
        rail.rotate_z(angle * std::f64::consts::PI / 180f64);

        let num_children = rail.get_child_count();
        if num_children != 1 {
            godot_print!("Unexpected number of children for rail: {}.", num_children);
            return;
        }

        let child = rail.get_child(0);
        if let Some(grid) = child {
            let grid = unsafe { grid.assume_safe() };
            if let Some(grid) = grid.cast::<Spatial>() {
                self.prepare_rail_grid(&grid, n);
            }
        }
    }

    #[export]
    fn add_one_rail(&mut self, owner: &Spatial, i: usize, n: usize) -> bool {
        match &self.template {
            Some(template) => match instanciate_scene::<Spatial>(template) {
                Ok(spatial) => {
                    self.prepare_rail(&spatial, i, n);
                    owner.add_child(spatial.into_shared(), false);
                    true
                }
                Err(err) => {
                    godot_print!("Could not instanciate rail scene: \"{:?}\".", err);
                    false
                }
            },
            None => false,
        }
    }

    #[export]
    fn add_all_rails(&mut self, owner: &Spatial) -> usize {
        match &self.data {
            Some(data) => {
                let mut added: usize = 0;
                let width = data.level.width();
                if width == 0 {
                    return 0;
                }
                for i in 0..width {
                    if !self.add_one_rail(owner, i, width) {
                        break;
                    }
                    added += 1;
                }
                added
            }
            None => 0,
        }
    }

    fn get_grid_scale(&self, owner: &Spatial) -> Result<Vector3, String> {
        let num_children = owner.get_child_count() as usize;
        if num_children == 0 {
            return Err(format!("Please setup tunnel"));
        }
        match owner.get_child(0) {
            Some(rail) => {
                let rail = unsafe { rail.assume_safe() };
                match rail.cast::<Spatial>() {
                    Some(rail) => match rail.get_child(0) {
                        Some(grid) => {
                            let grid = unsafe { grid.assume_safe() };
                            match grid.cast::<GridMap>() {
                                Some(grid) => return Ok(grid.scale()),
                                None => Err(format!("Unable to cast child of rail to GridMap.")),
                            }
                        }
                        None => Err(format!("rail has no child")),
                    },
                    None => Err(format!("rail is not spatial")),
                }
            }
            None => Err(format!("tunnel has no child")),
        }
    }

    fn sync_rail_grid(&mut self, rail: &GridMap, col: isize) -> bool {
        //godot_print!("sync {:?} {}", rail, i);
        rail.clear();
        match &mut self.data {
            Some(data) => {
                data.level.set_now_sec(self.now_sec);
                let start = -RAIL_OFFSET;
                let end = std::cmp::min(
                    start + data.level.len() as isize,
                    RAIL_OFFSET + RAIL_FAR_VIEW,
                );
                for row in start..end {
                    let item = if row == 0 && self.level_col == col && self.player_position.y == 0.0
                    {
                        SlabKind::HighLight.as_item()
                    } else if self.player_best_row > self.level_row
                        && row == self.player_best_row - self.level_row
                        && data.level.item(col, row + self.level_row) >= 0
                    {
                        SlabKind::HighLight.as_item()
                    } else {
                        data.level.item(col, row + self.level_row)
                    };
                    if item >= 0 {
                        let orientation = 0;
                        rail.set_cell_item(0, 0, (RAIL_OFFSET - 2 - row) as i64, item, orientation);
                    }
                }
                true
            }
            None => false,
        }
    }

    #[export]
    fn sync(&mut self, owner: &Spatial) -> bool {
        match &mut self.data {
            Some(data) => {
                Self::generate_missing(&mut data.level, self.level_row);
                let num_children = owner.get_child_count() as usize;
                let width = data.level.width();
                if num_children == 0 {
                    godot_print!("Please setup tunnel");
                    return false;
                }
                if num_children != (data.level.width()) {
                    godot_print!("Wrong number of rails: {} != {}.", num_children, width);
                    return false;
                }

                for i in 0..(num_children as isize) {
                    let child = owner.get_child(i as i64);
                    if let Some(rail) = child {
                        let rail = unsafe { rail.assume_safe() };
                        match rail.cast::<Spatial>() {
                            Some(rail) => {
                                let child = rail.get_child(0);
                                if let Some(grid) = child {
                                    let grid = unsafe { grid.assume_safe() };
                                    match grid.cast::<GridMap>() {
                                        Some(grid) => {
                                            self.sync_rail_grid(&grid, i);
                                        }
                                        None => {
                                            godot_print!(
                                                "Unable to cast child of rail to GridMap.",
                                            );
                                        }
                                    }
                                }
                            }
                            None => {
                                godot_print!("Unable to cast child of rail to Spatial.",);
                            }
                        }
                    }
                }
                true
            }
            None => false,
        }
    }

    #[export]
    fn update_player_position(&mut self, owner: &Spatial, pos: Vector3, best_row: isize) {
        let mut rotation = owner.rotation();
        rotation.z = pos.x;
        owner.set_rotation(rotation);

        let mut translation = owner.translation();
        translation.z = pos.z * self.grid_scale.z;
        owner.set_translation(translation);

        self.player_position = pos;
        self.player_best_row = best_row;
    }

    #[export]
    fn set_level_row(&mut self, _owner: &Spatial, level_row: isize) {
        self.level_row = level_row;
    }

    #[export]
    fn set_level_col(&mut self, _owner: &Spatial, level_col: isize) {
        self.level_col = level_col;
    }

    #[export]
    pub fn width(&self, _owner: &Spatial) -> usize {
        match &self.data {
            Some(data) => data.level.width(),
            None => 0,
        }
    }

    #[export]
    pub fn len(&self, _owner: &Spatial) -> usize {
        match &self.data {
            Some(data) => data.level.len(),
            None => 0,
        }
    }

    #[export]
    pub fn first(&self, _owner: &Spatial) -> isize {
        match &self.data {
            Some(data) => data.level.first(),
            None => 0,
        }
    }

    #[export]
    pub fn last(&self, _owner: &Spatial) -> isize {
        match &self.data {
            Some(data) => data.level.last(),
            None => 0,
        }
    }

    #[export]
    pub fn item(&self, _owner: &Spatial, col: isize, row: isize) -> i64 {
        match &self.data {
            Some(data) => data.level.item(col, row),
            None => 0,
        }
    }

    #[export]
    pub fn find_start_spot(
        &self,
        _owner: &Spatial,
        col: isize,
        row: isize,
    ) -> Option<(isize, isize)> {
        match &self.data {
            Some(data) => data.level.find_start_spot(col, row),
            None => None,
        }
    }
}