summaryrefslogtreecommitdiff
path: root/examples/sinewave.c
blob: 0c338034b43a6d52b551b57eb67c665438707b4e (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
#include "../graphics.c"

f32 frames[PRIMARY_SOUND_SAMPLE_RATE * NUM_PRIMARY_SOUND_CHANNELS] = {0};

b8 ui_button(f64 x, f64 y, f64 width, f64 height) {
  b8 has_cursor = g_platform.cursor_x >= x && g_platform.cursor_x < x + width &&
                  g_platform.cursor_y >= y && g_platform.cursor_y < y + height;

  b8 is_pressed = has_cursor && g_platform.key_down[BUTTON_LEFT];

  if (is_pressed)
    fill_rectangle(RGB(1.f, 1.f, 1.f), x, y, width, height);
  else if (has_cursor)
    fill_rectangle(RGB(.8f, .8f, 0.f), x, y, width, height);
  else
    fill_rectangle(RGB(.8f, .8f, .2f), x, y, width, height);

  return has_cursor && g_platform.key_pressed[BUTTON_LEFT];
}

void update_and_render_frame(void) {
  i32 num_events = handle_main_window_events();

  if (num_events > 0) {
    fill_rectangle(RGB(.1f, .1f, .1f), 0, 0, g_platform.frame_width, g_platform.frame_height);

    if (ui_button(100, 100, 200, 200))
      queue_primary_sound(0, PRIMARY_SOUND_SAMPLE_RATE, frames);
  }

  handle_primary_sound();
  render_main_window_frame();
  suspend_thread_for_milliseconds(0);
}

i32 main(i32 argc, c8 **argv) {
  (void) argc;
  (void) argv;

  g_platform = (Platform) {
    .title             = "Sine Wave",
    .graceful_shutdown = 1,
  };

  f64 frequency = 440.;

  for (i64 i = 0; i < PRIMARY_SOUND_SAMPLE_RATE; ++i) {
    f64 t = ((f64) i) / PRIMARY_SOUND_SAMPLE_RATE;
    f64 x = sin(t * (M_PI * 2.) * frequency);
    if (t < .005)
      x *= t / .005;
    if (t > .1)
      x *= (1. - t) / .9;
    frames[i * 2]     = (f32) (x * .5);
    frames[i * 2 + 1] = (f32) (x * .5);
  }

  run_main_window_event_loop();
  return 0;
}