v / examples / fireworks / fireworks.v
107 lines · 93 sloc · 1.9 KB · bbb61ab3687afe512a1fa12492c876d011626107
Raw
1import objects
2import gg
3import rand
4
5struct App {
6mut:
7 gg &gg.Context = unsafe { nil }
8 ui &objects.UIParams = unsafe { nil }
9 rockets []objects.Rocket
10 frames [][]objects.Rocket
11 // i thought about using a fixed fifo queue for the frames but the array
12 // seemed to work fine, if you'd like a challenge try implementing it with the queue :)
13 draw_flag bool = true
14}
15
16fn on_frame(mut app App) {
17 if !app.draw_flag {
18 return
19 }
20 app.gg.begin()
21
22 // drawing previous frames
23 for mut frame in app.frames {
24 for mut rocket in frame {
25 if !rocket.exploded {
26 rocket.color.a = u8(f32_max(rocket.color.a - 8, 0))
27 rocket.draw(mut app.gg)
28 }
29 }
30 }
31
32 // chance of firing new rocket
33 if rand.intn(30) or { 0 } == 0 {
34 app.rockets << objects.new_rocket()
35 }
36 // simulating rockets
37 app.rockets = app.rockets.filter(!it.dead)
38
39 for mut rocket in app.rockets {
40 rocket.tick(mut app.gg)
41 }
42
43 // adding frame
44 mut frame := app.rockets.clone()
45
46 for mut rocket in frame {
47 rocket.particles = []
48 }
49
50 app.frames << frame
51
52 // trimming out frames
53 if app.frames.len > 30 {
54 app.frames.delete(0)
55 }
56
57 app.gg.end()
58}
59
60fn on_event(e &gg.Event, mut app App) {
61 match e.typ {
62 .resized, .resumed {
63 app.resize()
64 }
65 .iconified {
66 app.draw_flag = false
67 }
68 .restored {
69 app.draw_flag = true
70 app.resize()
71 }
72 else {
73 // println("Type ${e.typ}")
74 }
75 }
76}
77
78fn (mut app App) resize() {
79 size := gg.window_size()
80 // avoid calls when minimized
81 if size.width < 2 && size.height < 2 {
82 return
83 }
84 mut s := gg.dpi_scale()
85
86 if s == 0.0 {
87 s = 1.0
88 }
89 app.ui.dpi_scale = s
90 app.ui.width = size.width
91 app.ui.height = size.height
92}
93
94fn main() {
95 mut app := &App{}
96 app.ui = objects.get_params()
97 app.gg = gg.new_context(
98 width: app.ui.width
99 height: app.ui.height
100 window_title: 'Fireworks!'
101 bg_color: gg.black
102 user_data: app
103 frame_fn: on_frame
104 event_fn: on_event
105 )
106 app.gg.run()
107}
108