aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: 04956772af844a4def39516565ef48f2b1e73035 (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
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
#include <raylib.h>
#include <rlgl.h>
#include <raymath.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <poll.h>
#include <unistd.h>
#include <sys/inotify.h>
#include <dirent.h>
#include "dynamic-array.h"

#define ZOOM_SPEED 1

#define FONT_COLOR WHITE
#define FONT_SIZE    20
#define TEXT_SPACING 5

#if defined(PLATFORM_DESKTOP)
#define GLSL_VERSION            330
#else
#define GLSL_VERSION            100
#endif

#define STRINGIFY(X) #X
#define TO_STRING(X) STRINGIFY(X)

#define DIRECTORY_SHADERS "./res/shaders/glsl" TO_STRING (GLSL_VERSION)

#define INOTIFY_EVENT_BUFFER_SIZE 4096

#define MOD(A, B) ((((A) % (B)) + (B)) % (B))
#define MIN(A, B) ((A) < (B) ? (A) : (B))

struct shader_info_da {
  struct shader_info {
    char *name;
    Shader shader;
  } *items;
  uint32_t count;
  uint32_t capacity;
};

int
main (void)
{
  SetTraceLogLevel (LOG_ALL);

  char inotify_event_buffer[INOTIFY_EVENT_BUFFER_SIZE]
    __attribute__ ((aligned (__alignof__ (struct inotify_event))));
  int inotify_fd = inotify_init ();
  if (inotify_fd < 0) {
    perror ("inotify_init");
    exit (EXIT_FAILURE);
  }

  int inotify_wd = inotify_add_watch (inotify_fd, DIRECTORY_SHADERS,
                                      IN_MODIFY |
                                      IN_CREATE |
                                      IN_DELETE |
                                      IN_MOVED_FROM |
                                      IN_MOVED_TO);
  if (inotify_wd == -1) {
    perror ("inotify_add_watch");
    exit (EXIT_FAILURE);
  } TraceLog (LOG_TRACE, "Watching "DIRECTORY_SHADERS" for changes");

  const int screen_width  = 800;
  const int screen_height = 450;

  SetConfigFlags (FLAG_WINDOW_RESIZABLE);
  InitWindow (screen_width, screen_height, "shadertoy");
  SetTargetFPS (60);

  Font font = GetFontDefault ();

  struct shader_info_da shader_info_da = {0};

  DIR *shaders_dp = opendir (DIRECTORY_SHADERS);
  if (shaders_dp == NULL) {
    perror ("opendir");
    exit (EXIT_FAILURE);
  }

  struct dirent *entry;
  while ((entry = readdir (shaders_dp)) != NULL) {
    if (entry->d_type == DT_REG &&
        entry->d_name[0] != '.' &&
        strlen (entry->d_name) > 3 &&
        !strcmp (entry->d_name + strlen (entry->d_name) - 3, ".fs")) {
      TraceLog (LOG_INFO, "Found shader %s", entry->d_name);

      char *name = malloc (strlen (entry->d_name) - 2);
      memcpy (name, entry->d_name, strlen (entry->d_name) - 3);
      name[strlen (entry->d_name) - 3] = '\0';
      Shader shader = LoadShader (NULL, TextFormat (DIRECTORY_SHADERS"/%s", entry->d_name));
      DYNAMIC_ARRAY_APPEND (shader_info_da, ((struct shader_info) {
                                               .name = name,
                                               .shader = shader,
                                             }));
    }
  } closedir (shaders_dp);

  int32_t shader_idx = 0;
  if (shader_info_da.count) {
    SetWindowTitle (TextFormat ("shadertoy - %s", shader_info_da.items[shader_idx].name));
  }

  RenderTexture2D target = LoadRenderTexture (GetScreenWidth (), GetScreenHeight ());
  float zoom_target = 1;
  float zoom = 1;
  while (!WindowShouldClose ()) {
    fd_set read_fds;
    FD_ZERO (&read_fds);
    FD_SET (inotify_fd, &read_fds);
    struct timeval notime = {0};
    int activity = select (FD_SETSIZE, &read_fds, NULL, NULL, &notime);
    if (activity < 0) {
      perror ("select");
      exit (EXIT_FAILURE);
    }
    if (FD_ISSET (inotify_fd, &read_fds)) {
      int length = read (inotify_fd, inotify_event_buffer, INOTIFY_EVENT_BUFFER_SIZE);

      if (length < 0) {
        perror ("read");
        exit (EXIT_FAILURE);
      }

      for (int i = 0; i + sizeof (struct inotify_event) < length; ) {
        struct inotify_event *event = (struct inotify_event *) &inotify_event_buffer[i];
        if (event->name[0] != '.' && !strcmp (&event->name[strlen (event->name) - 3], ".fs")) {
          if (event->mask & IN_MODIFY) {
            TraceLog (LOG_INFO, "Reloading shader %s", event->name);
            DYNAMIC_ARRAY_FOREACH (shader_info, shader_info_da) {
              if (!strncmp (event->name, shader_info->name,
                            strlen (shader_info->name))) {
                UnloadShader (shader_info->shader);
                shader_info->shader = LoadShader (NULL, TextFormat (DIRECTORY_SHADERS"/%s.fs", shader_info->name));
                break;
              }
            }
          } else if (event->mask & (IN_DELETE | IN_MOVED_FROM)) {
            TraceLog (LOG_INFO, "Unloading shader %s", event->name);
            DYNAMIC_ARRAY_FOREACH (shader_info, shader_info_da) {
              if (!strncmp (event->name, shader_info->name,
                            strlen (shader_info->name))) {
                free (shader_info->name);
                UnloadShader (shader_info->shader);
                int32_t i = shader_info - shader_info_da.items;
                memmove (&shader_info_da.items[i], &shader_info_da.items[i + 1],
                         (shader_info_da.count - i)*sizeof (struct shader_info));
                shader_info_da.count -= 1;
                if (shader_info_da.count) {
                  shader_idx = MIN (shader_idx, shader_info_da.count - 1);
                  SetWindowTitle (TextFormat ("shadertoy - %s", shader_info_da.items[shader_idx].name));
                } SetWindowTitle ("shadertoy");
                break;
              }
            }
          } else if (event->mask & (IN_CREATE | IN_MOVED_TO)) {
            TraceLog (LOG_INFO, "Loading shader %s", event->name);
            char *name = malloc (strlen (event->name) - 2);
            memcpy (name, event->name, strlen (event->name) - 3);
            name[strlen (event->name) - 3] = '\0';
            Shader shader = LoadShader (NULL, TextFormat (DIRECTORY_SHADERS"/%s", event->name));
            DYNAMIC_ARRAY_APPEND (shader_info_da, ((struct shader_info) {
                                                     .name = name,
                                                     .shader = shader,
                                                   }));
            if (shader_info_da.count == 1)
              SetWindowTitle (TextFormat ("shadertoy - %s", name));
          }
        } i += sizeof (struct inotify_event) + event->len;
      }
    }

    if (shader_info_da.count && (IsKeyPressed(KEY_LEFT) || IsKeyPressed(KEY_RIGHT))) {
      int32_t c = shader_info_da.count;
      if (IsKeyPressed(KEY_LEFT )) shader_idx = MOD (shader_idx - 1, c);
      if (IsKeyPressed(KEY_RIGHT)) shader_idx = MOD (shader_idx + 1, c);
      SetWindowTitle (TextFormat ("shadertoy - %s", shader_info_da.items[shader_idx].name));
    }

    zoom_target += GetMouseWheelMove()*ZOOM_SPEED;
    zoom += Clamp (zoom_target - zoom,
                   -10*GetFrameTime (),
                   +10*GetFrameTime ());

    if (shader_info_da.count) {
      if (shader_info_da.items[shader_idx].shader.id != rlGetShaderIdDefault ()) {
        Shader active_shader = shader_info_da.items[shader_idx].shader;

        float time = GetTime ();
        int shader_location_time = GetShaderLocation(active_shader, "time");
        SetShaderValue (active_shader, shader_location_time, &time, SHADER_UNIFORM_FLOAT);

        Vector2 resolution = { GetScreenWidth (), GetScreenHeight () };
        int shader_location_resolution = GetShaderLocation(active_shader, "resolution");
        SetShaderValue (active_shader, shader_location_resolution, &resolution, SHADER_UNIFORM_VEC2);

        Vector2 mouse = GetMousePosition ();
        mouse.y = GetScreenHeight () - mouse.y;
        int shader_location_mouse = GetShaderLocation (active_shader, "mouse");
        SetShaderValue (active_shader, shader_location_mouse, &mouse, SHADER_UNIFORM_VEC2);

        int shader_location_zoom = GetShaderLocation (active_shader, "zoom");
        SetShaderValue (active_shader, shader_location_zoom, &zoom, SHADER_UNIFORM_FLOAT);

        if (GetScreenWidth  () != target.texture.width ||
            GetScreenHeight () != target.texture.height) {
          UnloadRenderTexture (target);
          target = LoadRenderTexture (GetScreenWidth (), GetScreenHeight ());
        }

        BeginTextureMode (target); {
          ClearBackground (BLANK); // NOTE(cmmm): plugin code here
        } EndTextureMode ();
        BeginDrawing (); {
          BeginShaderMode (active_shader);
          {
            DrawTextureV(target.texture, Vector2Zero(),
                         BLANK); // NOTE(cmmm): plugin code maybe here
          }
          EndShaderMode();
        }
        EndDrawing();

      } else {
        BeginDrawing (); {
          ClearBackground (BLACK);
          const char *note = "Unable to compile shader";
          Vector2 note_size = MeasureTextEx (font, note, FONT_SIZE, TEXT_SPACING);
          Vector2 note_pos = Vector2Scale (
            Vector2Subtract ((Vector2) { GetScreenWidth (), GetScreenHeight () },
                             note_size), 0.5);
          DrawTextEx (font, note, note_pos, FONT_SIZE, TEXT_SPACING, FONT_COLOR);
        } EndDrawing ();
      }
    } else {
      BeginDrawing (); {
        ClearBackground (BLACK);
        const char *note = "There are no shaders in "DIRECTORY_SHADERS;
        Vector2 note_size = MeasureTextEx (font, note, FONT_SIZE, TEXT_SPACING);
        Vector2 note_pos = Vector2Scale (
          Vector2Subtract ((Vector2) { GetScreenWidth (), GetScreenHeight () },
                           note_size), 0.5);
        DrawTextEx (font, note, note_pos, FONT_SIZE, TEXT_SPACING, FONT_COLOR);
      } EndDrawing ();
    }
  }

  inotify_rm_watch (inotify_fd, inotify_wd);
  close (inotify_fd);

  DYNAMIC_ARRAY_FOREACH(shader_info, shader_info_da) {
    UnloadShader (shader_info->shader);
    free (shader_info->name);
  } DYNAMIC_ARRAY_FREE(shader_info_da);
  UnloadRenderTexture (target);
  CloseWindow ();

  return EXIT_SUCCESS;
}