aboutsummaryrefslogtreecommitdiff
path: root/v_windows/v/old/examples/fireworks/fireworks.v
blob: 9581cc54abdc6e794b107080dc6c0f73a63280f4 (plain)
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
import os
import objects
import gg
import gx
import rand

struct App {
mut:
	gg      &gg.Context       = 0
	ui      &objects.UIParams = 0
	rockets []objects.Rocket
	frames  [][]objects.Rocket
	// i thought about using a fixed fifo queue for the frames but the array
	// seemed to work fine, if you'd like a challenge try implementing it with the queue :)
	draw_flag bool = true
}

fn on_frame(mut app App) {
	if !app.draw_flag {
		return
	}
	app.gg.begin()

	// drawing previous frames
	for mut frame in app.frames {
		for mut rocket in frame {
			if !rocket.exploded {
				rocket.color.a = byte(f32_max(rocket.color.a - 8, 0))
				rocket.draw(mut app.gg)
			}
		}
	}

	// chance of firing new rocket
	if rand.intn(30) == 0 {
		app.rockets << objects.new_rocket()
	}
	// simulating rockets
	app.rockets = app.rockets.filter(!it.dead)

	for mut rocket in app.rockets {
		rocket.tick(mut app.gg)
	}

	// adding frame
	mut frame := app.rockets.clone()

	for mut rocket in frame {
		rocket.particles = []
	}

	app.frames << frame

	// trimming out frames
	if app.frames.len > 30 {
		app.frames.delete(0)
	}

	app.gg.end()
}

fn on_event(e &gg.Event, mut app App) {
	match e.typ {
		.resized, .resumed {
			app.resize()
		}
		.iconified {
			app.draw_flag = false
		}
		.restored {
			app.draw_flag = true
			app.resize()
		}
		else {
			// println("Type ${e.typ}")
		}
	}
}

fn (mut app App) resize() {
	size := gg.window_size()
	// avoid calls when minimized
	if size.width < 2 && size.height < 2 {
		return
	}
	mut s := gg.dpi_scale()

	if s == 0.0 {
		s = 1.0
	}
	app.ui.dpi_scale = s
	app.ui.width = size.width
	app.ui.height = size.height
}

// is needed for easier diagnostics on windows
[console]
fn main() {
	mut font_path := os.resource_abs_path(os.join_path('../assets/fonts/', 'RobotoMono-Regular.ttf'))
	$if android {
		font_path = 'fonts/RobotoMono-Regular.ttf'
	}

	mut app := &App{}
	app.ui = objects.get_params()

	app.gg = gg.new_context(
		width: app.ui.width
		height: app.ui.height
		window_title: 'Fireworks!'
		bg_color: gx.black
		user_data: app
		frame_fn: on_frame
		event_fn: on_event
		font_path: font_path
	)

	app.gg.run()
}