Read whole buffer to get it proper asynchronous
[clouds.git] / clouds.cpp
1 #include "GL/glew.h"
2 #include "debug.hpp"
3 #include "program.hpp"
4 #include "simulation.hpp"
5 #include <GLUT/glut.h>
6 #include <array>
7 #include <chrono>
8 #include <cmath>
9 #include <cstdio>
10 #include <cstdlib>
11 #include <glm/ext.hpp>
12 #include <glm/glm.hpp>
13 #include <sys/stat.h>
14 #include <vector>
15
16 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
17
18 enum Mode { render, debugContDist, debugColor, debugProbExt, debugProbAct };
19 Mode curMode = render;
20
21 using namespace std;
22 using namespace glm;
23
24 const float metaballR = 1.f / 16.f;
25 inline float metaballField(float r) {
26   if (r > 1)
27     return 0;
28   const float a = r / (1);
29   return (-4.f / 9.f * powf(a, 6)) + (17.f / 9.f * powf(a, 4)) -
30          (22.f / 9.f * powf(a, 2)) + 1;
31 }
32
33 const float normalizationFactor = (748.f / 405.f) * M_PI;
34
35 void checkError() {
36   if (GLenum e = glGetError()) {
37     fprintf(stderr, "%s\n", gluErrorString(e));
38     abort();
39   }
40 }
41
42 GLuint bbProg, sunProg;
43 GLuint bbVao;
44
45 // Here we need to generate n_q textures for different densities of metaballs
46 // These textures then go on the billboards
47 // The texture stores attenuation ratio?
48
49 #define NQ 64
50 GLuint bbTexIds[NQ];
51
52 // Stores attenuation ratio inside r channel
53 // Should be highest value at center
54 void precalculateBillboardTextures() {
55   fprintf(stderr, "Calculating billboard textures...\n");
56   glGenTextures(NQ, bbTexIds);
57
58   for (int d = 0; d < NQ; d++) {
59     float data[32 * 32];
60     for (int j = 0; j < 32; j++) {
61       for (int i = 0; i < 32; i++) {
62         // TODO: properly calculate this instead of whatever this is
63         float r = distance(vec2(i, j), vec2(16, 16)) / 16;
64         float density = (float)d / NQ;
65         data[i + j * 32] =
66             1 -
67             fmin(1, (3 * density * (metaballField(r) / normalizationFactor)));
68       }
69     }
70
71     mkdir("bbtex", 0777);
72     char path[32];
73     snprintf(path, 32, "bbtex/%i.tga", d);
74     saveGrayscale(data, 32, 32, path);
75
76     glBindTexture(GL_TEXTURE_2D, bbTexIds[d]);
77
78     glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 32, 32, 0, GL_RED, GL_FLOAT, data);
79     glGenerateMipmap(GL_TEXTURE_2D); // required, otherwise texture is blank
80
81     fprintf(stderr, "\r%i out of %i densities calculated%s", d + 1, NQ,
82             d == NQ - 1 ? "\n" : "");
83   }
84 }
85
86 struct Metaball {
87   vec3 pos;
88   ivec3 coords;
89   /** Density */
90   float d;
91   vec4 col;
92 };
93
94 array<Metaball, CLOUD_DIM_X * CLOUD_DIM_Y * CLOUD_DIM_Z> metaballs;
95
96 const float cloudScale = metaballR;
97 const float metaballScale = metaballR * 1.5f;
98 Clouds cs;
99
100 void calculateMetaballs() {
101   stepClouds(&cs);
102   /* for (int i = 0; i < 256; i++) { */
103   /*   float x = ((float)rand()/(float)(RAND_MAX) - 0.5) * 2; */
104   /*   float y = ((float)rand()/(float)(RAND_MAX) - 0.5) * 2; */
105   /*   float z = ((float)rand()/(float)(RAND_MAX) - 0.5) * 2; */
106   /*   float r = (float)rand()/(float)(RAND_MAX) * 1; */
107   /*   Metaball m = {{x,y,z}, r}; */
108   /*   metaballs.push_back(m); */
109   /* } */
110   for (int i = 0; i < CLOUD_DIM_X; i++) {
111     for (int j = 0; j < CLOUD_DIM_Y; j++) {
112       for (int k = 0; k < CLOUD_DIM_Z; k++) {
113         Metaball m = {vec3(i, j, k) * vec3(cloudScale), {i, j, k}};
114         /* m.pos = (m.pos * vec3(2)) - (cloudScale / 2); */
115         m.pos -= vec3(CLOUD_DIM_X, CLOUD_DIM_Y, CLOUD_DIM_Z) * cloudScale / 2.f;
116         m.d = cs.q[i][j][k];
117         /* m.d = 0; */
118         metaballs[i * CLOUD_DIM_Y * CLOUD_DIM_Z + j * CLOUD_DIM_Z + k] = m;
119       }
120     }
121   }
122   /* for (int z = 0; z < CLOUD_DIM_Z; z++) */
123   /*   metaballs[32 * CLOUD_DIM_Y * CLOUD_DIM_Z + 32 * CLOUD_DIM_Z + z].d = 1;
124    */
125 }
126
127 vec3 sunPos = {0, 5, 0}, sunDir = {0, -1, 0};
128 size_t envColorIdx = 0;
129 // First color is sun color, second is sky color
130 std::array<std::array<vec4, 2>, 3> envColors{
131     {{vec4(1, 1, 1, 1), vec4(0.9, 1, 1, 1)},
132      {vec4(0.939, 0.632, 0.815, 1), vec4(0.9, 1, 1, 1)},
133      {vec4(0.999, 0.999, 0.519, 1), vec4(0.981, 0.667, 0.118, 1)}}};
134 vec3 camPos = {0, 0, -3}, viewPos = {0, 0, 0};
135 mat4 proj; // projection matrix
136 mat4 view; // view matrix
137 float znear = 0.001, zfar = 1000;
138 // for performance with glReadPixels these should be powers of 2!
139 float width = 1200, height = 800;
140
141 void setProjectionAndViewUniforms(GLuint progId) {
142   GLuint projLoc = glGetUniformLocation(progId, "projection");
143   glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(proj));
144
145   GLuint viewLoc = glGetUniformLocation(progId, "view");
146   glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
147 }
148
149 /** Orientates the transformation matrix to face the camera in the view matrix
150  */
151 mat4 faceView(mat4 m) {
152   m[0][0] = view[0][0];
153   m[0][1] = view[1][0];
154   m[0][2] = view[2][0];
155   m[1][0] = view[0][1];
156   m[1][1] = view[1][1];
157   m[1][2] = view[2][1];
158   m[2][0] = view[0][2];
159   m[2][1] = view[1][2];
160   m[2][2] = view[2][2];
161   return m;
162 }
163
164 #define PBO
165
166 /* const int shadeWidth = 256, shadeHeight = 256; */
167 const int shadeWidth = 256, shadeHeight = 256;
168
169 #ifdef PBO
170 const int numPbos = 64;
171 GLuint pboBufs[numPbos];
172 GLuint pboOffsets[numPbos]; // offsets into GL_PIXEL_PACK_BUFFER that
173                             // mapPixelRead should read from
174 GLbyte sink[shadeWidth * shadeHeight * 4];
175
176 void inline mapPixelRead(int pboBuf, int metaball) {
177   glBindBuffer(GL_PIXEL_PACK_BUFFER, pboBufs[pboBuf]);
178   GLubyte *src =
179       (GLubyte *)glMapBufferRange(GL_PIXEL_PACK_BUFFER, pboOffsets[pboBuf],
180                                   4 * sizeof(GLubyte), GL_MAP_READ_BIT);
181   vec4 pixel = vec4(src[0], src[1], src[2], src[3]) / vec4(255.f);
182   glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
183
184   glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
185
186   // Multiply the pixel value by the sunlight color.
187   pixel *= envColors[envColorIdx][0];
188
189   // Store the color for the previous set of pixels
190   metaballs[metaball].col = pixel;
191 }
192
193 #endif
194
195 void shadeClouds() {
196
197   glDisable(GL_DEPTH_TEST);
198   // shaderOutput * 0 + buffer * shader alpha
199   glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
200   glEnable(GL_BLEND);
201
202   // sort by ascending distance from the sun
203   sort(metaballs.begin(), metaballs.end(), [](Metaball &a, Metaball &b) {
204     return distance(sunPos, a.pos) < distance(sunPos, b.pos);
205   });
206
207   glActiveTexture(GL_TEXTURE0);
208   glUniform1i(glGetUniformLocation(bbProg, "tex"), 0);
209
210   GLuint modelLoc = glGetUniformLocation(bbProg, "model");
211   glUniform1i(glGetUniformLocation(bbProg, "debug"), 0);
212
213   glViewport(0, 0, shadeWidth, shadeHeight);
214
215 #ifdef PBO
216   int pboIdx = 0;
217 #endif
218
219   auto begin_time = std::chrono::system_clock::now();
220   size_t i = 0;
221   for (auto &k : metaballs) {
222     /* fprintf(stderr, "\rShading metaball %lu/%lu...", i, metaballs.size()); */
223     // place the billboard at the center of k
224     mat4 model = translate(mat4(1), k.pos);
225
226     // rotate the billboard so that its normal is oriented to the sun
227     model = faceView(model);
228
229     model = scale(model, vec3(metaballScale));
230
231     glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
232
233     // Set the billboard color as RGBA = (1.0, 1.0, 1.0, 1.0).
234     vec4 color = {1, 1, 1, 1};
235     glUniform4fv(glGetUniformLocation(bbProg, "color"), 1,
236                  glm::value_ptr(color));
237
238     // Map the billboard texture with GL_MODULATE.
239     // i.e. multiply rather than add
240     // but glTexEnv is for the old fixed function pipeline --
241     // need to just tell our fragment shader then to modulate
242     int dIdx = k.d * NQ;
243     glBindTexture(GL_TEXTURE_2D, bbTexIds[dIdx]);
244     glUniform1i(glGetUniformLocation(bbProg, "modulate"), 1);
245
246     // Render the billboard.
247     glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
248
249     // Read the pixel value corresponding to the center of metaball k.
250     // 1. First get position in opengl screen space: from [-1,1]
251     // 2. Normalize to [0,1]
252     // 3. Multiply by (width * height)
253     ivec2 screenPos =
254         ((vec2(proj * view * model * vec4(0, 0, 0, 1)) + vec2(1)) / vec2(2)) *
255         vec2(shadeWidth, shadeHeight);
256
257 #ifndef PBO
258     vec4 pixel;
259     // TODO: This is a huge bottleneck
260     glReadPixels(screenPos.x, screenPos.y, 1, 1, GL_RGBA, GL_FLOAT, &pixel);
261
262     // Multiply the pixel value by the sunlight color.
263     pixel *= envColors[envColorIdx][0];
264
265     // Store the color into an array C[k] as the color of the billboard.
266     k.col = pixel;
267 #else
268
269     glBindBuffer(GL_PIXEL_PACK_BUFFER, pboBufs[pboIdx]);
270     // It would be nice if this worked. But it doesn't
271     // macOS driver does this synchronously
272     /* glReadPixels(screenPos.x, screenPos.y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,
273      */
274     /*              NULL); */
275     glReadPixels(0, 0, shadeWidth, shadeHeight, GL_RGBA, GL_UNSIGNED_BYTE,
276                  NULL);
277     pboOffsets[pboIdx] = screenPos.x * 4 + screenPos.y * shadeWidth * 4;
278
279     int nextPbo = (pboIdx + 1) % numPbos;
280     if (i >= numPbos - 1) {
281       // start mapping the read values back
282       mapPixelRead(nextPbo, i - numPbos + 1);
283     }
284     pboIdx = nextPbo;
285 #endif
286
287     i++;
288   }
289   /* fprintf(stderr, "\n"); */
290
291 #ifdef PBO
292   // sink remaining reads
293   for (int i = 0; i < numPbos; i++) {
294     mapPixelRead(i, metaballs.size() - numPbos + i);
295   }
296 #endif
297
298   auto elapsed = std::chrono::system_clock::now() - begin_time;
299   double elapsed_seconds =
300       std::chrono::duration_cast<std::chrono::duration<double>>(elapsed)
301           .count();
302   fprintf(stderr, "Time taken to shade: %fs\n", elapsed_seconds);
303
304   saveFBO();
305   checkError();
306   glViewport(0, 0, width, height);
307 }
308
309 void renderObject() {
310   glDisable(GL_BLEND);
311   // render the sun
312   glUseProgram(sunProg);
313   mat4 model = translate(mat4(1), sunPos);
314   model = lookAt(sunPos, sunPos + sunDir, {0, 1, 0}) * model;
315   model = translate(scale(translate(model, -sunPos), vec3(0.3)), sunPos);
316   glUniformMatrix4fv(glGetUniformLocation(sunProg, "model"), 1, GL_FALSE,
317                      glm::value_ptr(model));
318   glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
319 }
320
321 void renderClouds() {
322   glUseProgram(bbProg);
323
324   // Sort metaballs in descending order from the viewpoint
325   sort(metaballs.begin(), metaballs.end(), [](Metaball &a, Metaball &b) {
326     return distance(camPos, a.pos) > distance(camPos, b.pos);
327   });
328
329   glUniform1i(glGetUniformLocation(bbProg, "debug"), curMode != render);
330
331   glDisable(GL_DEPTH_TEST);
332   glEnable(GL_BLEND);
333   // shaderOutput * 1 + buffer * shader alpha
334   glBlendFunc(GL_ONE, GL_SRC_ALPHA);
335
336   /* glBlendColor(1.f,1.f,1.f,1.f); */
337   /* glBlendFuncSeparate(GL_ONE, GL_SRC_ALPHA, GL_CONSTANT_ALPHA, GL_SRC_ALPHA);
338    */
339
340   glActiveTexture(GL_TEXTURE0);
341   glUniform1i(glGetUniformLocation(bbProg, "tex"), 0);
342
343   for (int i = 0; i < metaballs.size(); i++) {
344     Metaball k = metaballs[i];
345
346     GLuint modelLoc = glGetUniformLocation(bbProg, "model");
347
348     // Place the billboard at the center of the corresponding metaball n.
349     mat4 model = translate(mat4(1), k.pos);
350     // Rotate the billboard so that its normal is oriented to the viewpoint.
351     model = faceView(model);
352
353     model = scale(model, vec3(metaballScale));
354
355     glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
356
357     // Set the billboard color as C[n].
358     k.col.w = 1;
359     glUniform4fv(glGetUniformLocation(bbProg, "color"), 1,
360                  glm::value_ptr(k.col));
361
362     // Map the billboard texture.
363     int dIdx = k.d * (NQ - 1);
364     glBindTexture(GL_TEXTURE_2D, bbTexIds[dIdx]);
365
366     // Don't modulate it -- blend it
367     glUniform1i(glGetUniformLocation(bbProg, "modulate"), 0);
368
369     glUniform1f(glGetUniformLocation(bbProg, "debugColor"),
370                 curMode == debugColor);
371     if (curMode != render) {
372       float debugVal = 0;
373       if (curMode == debugContDist)
374         debugVal = k.d;
375       else if (curMode == debugProbAct)
376         debugVal = cs.p_act[k.coords.x][k.coords.y][k.coords.z] / P_ACT;
377       else if (curMode == debugProbExt)
378         debugVal = cs.p_ext[k.coords.x][k.coords.y][k.coords.z] / P_EXT;
379       glUniform1f(glGetUniformLocation(bbProg, "debugVal"), debugVal);
380       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
381       model = scale(model, vec3(0.1));
382       glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
383     }
384
385     // Render the billboard with the blending function.
386     glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
387   }
388 }
389
390 bool curBeenShaded = false;
391
392 void display() {
393   if (!curBeenShaded && (curMode == render || curMode == debugColor)) {
394     // TODO: find a way to make sure there's no clipping
395     view = glm::lookAt(sunPos + sunDir * vec3(100.f), sunPos, {0, 0, 1});
396     // TODO: calculate bounds so everything is covered
397     proj = glm::ortho(2.5f, -2.5f, -2.5f, 2.5f, znear, 10000.f);
398     glUseProgram(bbProg);
399     setProjectionAndViewUniforms(bbProg);
400
401     glClearColor(1, 1, 1, 1);
402     glClear(GL_COLOR_BUFFER_BIT);
403     shadeClouds();
404     curBeenShaded = true;
405   }
406
407   view = glm::lookAt(camPos, viewPos, {0, 1, 0});
408   const float aspect = width / height;
409   proj = glm::perspective(45.f, aspect, znear, zfar);
410   glUseProgram(sunProg);
411   setProjectionAndViewUniforms(sunProg);
412   glUseProgram(bbProg);
413   setProjectionAndViewUniforms(bbProg);
414
415   vec4 skyColor = envColors[envColorIdx][1];
416   glClearColor(skyColor.r, skyColor.g, skyColor.b,
417                skyColor.a); // background color
418   glClear(GL_COLOR_BUFFER_BIT);
419   renderObject(); // render things that aren't clouds
420   renderClouds();
421
422   glutSwapBuffers();
423 }
424
425 bool needsRedisplay = false;
426 void timer(int _) {
427   if (needsRedisplay) {
428     glutPostRedisplay();
429   }
430   needsRedisplay = false;
431   glutTimerFunc(16, timer, 0);
432 }
433
434 void keyboard(unsigned char key, int x, int y) {
435   if (key == ' ') {
436     calculateMetaballs();
437     needsRedisplay = true;
438     curBeenShaded = false;
439   }
440   if (key == '0') {
441     curMode = render;
442     needsRedisplay = true;
443   }
444   if (key == '1') {
445     curMode = debugContDist;
446     needsRedisplay = true;
447   }
448   if (key == '2') {
449     curMode = debugColor;
450     needsRedisplay = true;
451   }
452   if (key == '3') {
453     curMode = debugProbAct;
454     needsRedisplay = true;
455   }
456   if (key == '4') {
457     curMode = debugProbExt;
458     needsRedisplay = true;
459   }
460   if (key == 's') {
461     envColorIdx = (envColorIdx + 1) % envColors.size();
462     needsRedisplay = true;
463     curBeenShaded = false;
464   }
465 }
466
467 int prevMouseX, prevMouseY;
468 bool firstMouse = true;
469 void motion(int x, int y) {
470   if (firstMouse) {
471     prevMouseX = x;
472     prevMouseY = y;
473     firstMouse = false;
474   }
475   float dx = x - prevMouseX, dy = y - prevMouseY;
476   prevMouseX = x;
477   prevMouseY = y;
478   const vec3 origin(0, 0, 0);
479   const float sensitivity = 0.003f;
480   auto camMat = translate(mat4(1), origin + camPos);
481   auto rotation = rotate(rotate(mat4(1), -dx * sensitivity, {0, 1, 0}),
482                          -dy * sensitivity, {1, 0, 0});
483   auto rotAroundOrig = camMat * rotation * translate(mat4(1), origin - camPos);
484   camPos = rotAroundOrig * glm::vec4(camPos, 0);
485   needsRedisplay = true;
486 }
487
488 void passiveMotion(int x, int y) {
489   prevMouseX = x;
490   prevMouseY = y;
491 }
492
493 void reshape(int w, int h) {
494   width = w;
495   height = h;
496 }
497
498 int main(int argc, char **argv) {
499   glutInit(&argc, argv);
500   glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_ALPHA |
501                       GLUT_3_2_CORE_PROFILE);
502   glutInitWindowSize(width, height);
503   glutCreateWindow("Clouds");
504   glutDisplayFunc(display);
505   glutReshapeFunc(reshape);
506   glutKeyboardFunc(keyboard);
507   glutMotionFunc(motion);
508   glutPassiveMotionFunc(passiveMotion);
509   glutTimerFunc(16, timer, 0);
510
511   glewInit();
512
513   Program prog("billboardvert.glsl", "billboardfrag.glsl");
514   bbProg = prog.progId;
515   Program sProg("sunvert.glsl", "sunfrag.glsl");
516   sunProg = sProg.progId;
517
518   glGenVertexArrays(1, &bbVao);
519   glUseProgram(sunProg);
520   glBindVertexArray(bbVao);
521   glUseProgram(bbProg);
522   glBindVertexArray(bbVao);
523   GLuint vbos[2];
524   glGenBuffers(2, vbos);
525
526   vector<vec3> poss = {{-1, -1, 0}, {-1, 1, 0}, {1, 1, 0}, {1, -1, 0}};
527   vector<GLuint> indices = {2, 1, 0, 3, 2, 0};
528
529   GLuint posLoc = glGetAttribLocation(bbProg, "vPosition");
530   glBindBuffer(GL_ARRAY_BUFFER, vbos[0]);
531   glBufferData(GL_ARRAY_BUFFER, poss.size() * sizeof(glm::vec3), &poss[0],
532                GL_STATIC_DRAW);
533   glEnableVertexAttribArray(posLoc);
534   glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
535
536   glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbos[1]);
537   glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint),
538                &indices[0], GL_STATIC_DRAW);
539
540   prog.validate();
541
542   precalculateBillboardTextures();
543
544   initClouds(&cs);
545   calculateMetaballs();
546
547 #ifdef PBO
548   // setup PBOs for buffering readPixels
549   glGenBuffers(numPbos, pboBufs);
550   for (int i = 0; i < numPbos; i++) {
551     glBindBuffer(GL_PIXEL_PACK_BUFFER, pboBufs[i]);
552     glBufferData(GL_PIXEL_PACK_BUFFER, shadeWidth * shadeHeight * 4, NULL,
553                  GL_DYNAMIC_READ);
554   }
555   glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
556 #endif
557
558   glutMainLoop();
559
560   return 0;
561 }