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
use cairo::{Context, Format, ImageSurface, ImageSurfaceData};
use gdk_pixbuf::*;
use gtk::prelude::*;
use rand::Rng;
use rodio::Source;
use std::cell::RefCell;
use std::io::Cursor;
use std::rc::Rc;

const FPS: u32 = 60;

pub struct GameWindow {
    pub width: f64,
    pub height: f64,
}

pub struct Input {
    pub x: f64,
    pub y: f64,
    pub is_down: bool,
}

pub fn init(resource_bytes: &'static [u8]) {
    // we embed our image,glade file, and css  in a glib gresource file generated
    //  from app.xml, let's load it in from bytes embedded in our app
    let bytes = glib::Bytes::from_static(resource_bytes);
    let res = gio::Resource::from_data(&bytes).unwrap();
    gio::resources_register(&res);
}

pub fn random() -> f64 {
    let mut rng = rand::thread_rng();
    rng.gen()
}

pub fn random_sign() -> f64 {
    let s = random() - 0.5;
    if s < 0.0 {
        -1.0
    } else {
        1.0
    }
}

pub fn bytes_from_resource(path: &str) -> Vec<u8> {
    let bytes = gio::resources_lookup_data(path, gio::ResourceLookupFlags::NONE).unwrap();
    bytes.as_ref().to_owned()
}

pub fn text_from_resource(path: &str) -> String {
    let b = bytes_from_resource(path);
    let text = std::str::from_utf8(&b).unwrap();
    text.to_string()
}

pub fn sound_from_resource(path: &str) -> Vec<u8> {
    bytes_from_resource(path)
}

pub fn play_sound(sound: &'_ [u8]) {
    let device = rodio::default_output_device().unwrap();
    let source = rodio::Decoder::new(Cursor::new(sound.to_owned())).unwrap();
    rodio::play_raw(&device, source.convert_samples());
}

pub fn image_from_resource(path: &str) -> ImageSurface {
    let pb = Pixbuf::from_resource(path).unwrap();
    let pixels = unsafe { pb.get_pixels().to_owned() };
    let has_alpha = pb.get_has_alpha();
    let mut img = ImageSurface::create(Format::ARgb32, pb.get_width(), pb.get_height()).unwrap();
    {
        let mut d: ImageSurfaceData = img.get_data().unwrap();
        let data = &mut d;
        let w = pb.get_width();
        for x in 0..w {
            for y in 0..pb.get_height() {
                if has_alpha {
                    let sp = ((y * w + x) * 4) as usize;
                    let p = ((y * w + x) * 4) as usize;
                    data[p] = pixels[sp + 2];
                    data[p + 1] = pixels[sp + 1];
                    data[p + 2] = pixels[sp];
                    data[p + 3] = pixels[sp + 3];
                    // not sure why but alpha needs to be black
                    if pixels[sp + 3] == 0 {
                        data[p] = 0;
                        data[p + 1] = 0;
                        data[p + 2] = 0;
                    }
                } else {
                    // TODO, there's a bug with pngs without transparency... not sure where..
                    let sp = ((y * w + x) * 3) as usize;
                    let p = ((y * w + x) * 4) as usize;
                    data[p] = pixels[sp + 2];
                    data[p + 1] = pixels[sp + 1];
                    data[p + 2] = pixels[sp];
                    data[p + 3] = 255;
                }
            }
        }
    }
    img
}

pub struct Rect {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
}

pub trait MochiCairoExt {
    fn clear(&self, r: f64, g: f64, b: f64);
    fn draw_image_centered(&self, x: f64, y: f64, img: &ImageSurface);
    fn draw_subimage_centered(&self, x: f64, y: f64, img: &ImageSurface, source_rect: Rect);
    fn draw_atlas_frame_centered(&self, x: f64, y: f64, img: &Atlas, frame: usize);
}

impl MochiCairoExt for cairo::Context {
    fn clear(&self, r: f64, g: f64, b: f64) {
        self.set_source_rgb(r, g, b);
        self.paint();
    }

    fn draw_image_centered(&self, x: f64, y: f64, img: &ImageSurface) {
        self.save();
        self.translate(
            x - (img.get_width() / 2) as f64,
            y - (img.get_height() / 2) as f64,
        );
        self.set_source_surface(img, 0.0, 0.0);
        self.paint();
        self.restore();
    }

    fn draw_subimage_centered(&self, x: f64, y: f64, img: &ImageSurface, source_rect: Rect) {
        self.save();
        self.rectangle(
            x - source_rect.width / 2.0,
            y - source_rect.height / 2.0 as f64,
            source_rect.width as f64,
            source_rect.height as f64,
        );
        self.clip();
        self.translate(
            x - (source_rect.width / 2.0) as f64 - source_rect.x,
            y - (source_rect.height / 2.0) as f64 - source_rect.y,
        );
        self.set_source_surface(img, 0.0, 0.0);
        self.paint();
        self.restore();
    }

    fn draw_atlas_frame_centered(&self, x: f64, y: f64, atlas: &Atlas, frame: usize) {
        let frame = &atlas.frames[frame];
        self.draw_subimage_centered(
            x,
            y,
            &atlas.img.borrow(),
            Rect {
                x: frame.x,
                y: frame.y,
                width: frame.w,
                height: frame.h,
            },
        );
    }
}

pub fn run_game<T>(run: T)
where
    T: 'static + Fn(GameWindow, &Context, &Input, f64),
{
    if gtk::init().is_err() {
        panic!("Failed to initialize GTK.");
    }

    // grab the controls we'll be using
    let window = Rc::new(RefCell::new(gtk::Window::new(gtk::WindowType::Toplevel)));
    window.borrow().set_decorated(false);
    let event_box = gtk::EventBox::new();
    event_box.set_events(gdk::EventMask::STRUCTURE_MASK | gdk::EventMask::TOUCH_MASK);
    window.borrow().add(&event_box);
    let drawing_area = gtk::DrawingArea::new();
    event_box.add(&drawing_area);
    let canvas: Rc<RefCell<gtk::DrawingArea>> = Rc::new(RefCell::new(drawing_area));

    window.borrow().connect_window_state_event(|w, e| {
        if e.get_new_window_state().contains(gdk::WindowState::FOCUSED) {
            w.fullscreen();
        }
        Inhibit(false)
    });

    let display = gdk::DisplayManager::get().get_default_display().unwrap();
    let mon = display.get_monitor(0).unwrap();
    let win2 = window.clone();
    mon.connect_property_geometry_notify(move |_| {
        win2.borrow().unfullscreen();
        win2.borrow().maximize();
        win2.borrow().fullscreen();
    });

    let input = Rc::new(RefCell::new(Input {
        x: 0.0,
        y: 0.0,
        is_down: false,
    }));

    let input2 = input.clone();
    let canvas2 = canvas.clone();
    // handle draw and use cairo context
    canvas.borrow_mut().connect_draw(move |_, ctx| {
        run(
            GameWindow {
                width: canvas2.borrow().get_allocated_width() as f64,
                height: canvas2.borrow().get_allocated_height() as f64,
            },
            ctx,
            &input2.borrow(),
            1_f64 / FPS as f64,
        );
        Inhibit(false)
    });

    let input3 = input.clone();
    event_box.connect_button_press_event(move |_, e| {
        let mut inp = input3.borrow_mut();
        let pos = e.get_coords().unwrap();
        inp.is_down = true;
        inp.x = pos.0;
        inp.y = pos.1;
        Inhibit(false)
    });

    let input4 = input.clone();
    event_box.connect_button_release_event(move |_, e| {
        let mut inp = input4.borrow_mut();
        let pos = e.get_coords().unwrap();
        inp.is_down = false;
        inp.x = pos.0;
        inp.y = pos.1;
        Inhibit(false)
    });

    let input5 = input.clone();
    event_box.connect_motion_notify_event(move |_, e| {
        let mut inp = input5.borrow_mut();
        let pos = e.get_coords().unwrap();
        inp.x = pos.0;
        inp.y = pos.1;
        Inhibit(false)
    });

    let input6 = input;

    event_box.connect_touch_event(move |_, e| {
        let mut inp = input6.borrow_mut();
        let pos = e.get_coords().unwrap();
        inp.x = pos.0;
        inp.y = pos.1;
        Inhibit(false)
    });

    // show the window
    window.borrow().show_all();

    window.borrow().fullscreen();

    let canvas2 = canvas;
    let tick = move || {
        canvas2.borrow_mut().queue_draw();
        glib::Continue(true)
    };

    // executes the game every 30 seconds
    gtk::timeout_add(1000 / FPS, tick);

    // exit properly if our window is closing
    window.borrow().connect_delete_event(|_, _| {
        gtk::main_quit();
        Inhibit(false)
    });

    gtk::main();
}

pub struct AtlasFrame {
    pub x: f64,
    pub y: f64,
    pub w: f64,
    pub h: f64,
}

pub struct Atlas {
    pub img: Rc<RefCell<ImageSurface>>,
    pub frames: Vec<AtlasFrame>,
}

impl Atlas {
    pub fn new(
        img: Rc<RefCell<ImageSurface>>,
        frame_width: u32,
        frame_height: u32,
        num_frames: u32,
    ) -> Atlas {
        let mut frames = vec![];
        {
            let i = img.borrow();
            let fw = i.get_width() as u32 / frame_width;
            let fh = i.get_height() as u32 / frame_height;
            let mut i = 0;
            for y in 0..frame_height {
                for x in 0..frame_width {
                    if i >= num_frames {
                        break;
                    }
                    frames.push(AtlasFrame {
                        x: (x * fw) as f64,
                        y: (y * fh) as f64,
                        w: fw as f64,
                        h: fh as f64,
                    });
                    i += 1;
                }
            }
        }
        Atlas { img, frames }
    }
}