v2 / examples / gg / spirograph.v
72 lines · 70 sloc · 1.77 KB · e2e5cf8db56f3562c7baa735061690be936bdf3e
Raw
1import gg
2import math
3
4const pixel_count = 15000
5const p = 3
6const s = math.pi * 2 / f32(pixel_count)
7const color = gg.Color{255, 255, 255, 255}
8const background = gg.Color{20, 20, 64, 5}
9const colors = [
10 gg.Color{255, 255, 255, 255},
11 gg.Color{255, 0, 255, 255},
12 gg.Color{255, 255, 0, 255},
13 gg.Color{0, 255, 255, 255},
14 gg.Color{0, 0, 255, 255},
15 gg.Color{0, 0, 0, 255},
16]!
17
18mut k := 497
19mut scale := 200
20gg.start(
21 window_title: 'Spirograph'
22 bg_color: background
23 width: 900
24 height: 950
25 sample_count: 2
26 frame_fn: fn [mut k, mut scale] (mut ctx gg.Context) {
27 wsize := gg.window_size()
28 ctx.begin()
29 ctx.draw_rect_filled(0, 0, wsize.width, wsize.height, gg.Color{10, 1, 30, 60})
30 t := f64(ctx.frame) / 300
31 d := math.sin(t)
32 if math.abs(d) < 0.0015 {
33 k++
34 }
35 if ctx.pressed_keys[int(gg.KeyCode._0)] {
36 ctx.frame = 475
37 }
38 if ctx.pressed_keys[int(gg.KeyCode.left)] {
39 k--
40 }
41 if ctx.pressed_keys[int(gg.KeyCode.right)] {
42 k++
43 }
44 if ctx.pressed_keys[int(gg.KeyCode.up)] {
45 scale++
46 }
47 if ctx.pressed_keys[int(gg.KeyCode.down)] {
48 scale--
49 }
50 d600 := math.sin(f64(ctx.frame) / 60)
51 cd600 := math.cos(d600)
52 mut pdj, mut pkj := [p]f64{}, [p]f64{}
53 for j := 0; j < p; j++ {
54 pdj[j], pkj[j] = math.pow(d, j), math.pow(k, j)
55 }
56 for i := 0; i < pixel_count; i++ {
57 mut x, mut y := 0.0, 0.0
58 for j := 0; j < p; j++ {
59 a := pkj[j] * i * s
60 x += pdj[j] * math.sin(a - t) * cd600
61 y += pdj[j] * math.cos(a - t) * cd600
62 }
63 ctx.draw_rect_filled(f32(wsize.width / 2 + scale * x),
64 f32(wsize.height / 2 + scale * y), 1, 1, colors[i % colors.len])
65 }
66 ctx.draw_text(wsize.width / 2 - 170, wsize.height - 15,
67 'frame: ${ctx.frame:06}, k: ${k:4}, scale: ${scale:4}, arrows to change',
68 color: colors[1]
69 )
70 ctx.end(how: .passthru)
71 }
72)
73