Fix billboard orientation
[clouds.git] / clouds.cpp
1 #include "debug.hpp"
2 #include "simulation.h"
3 #include "program.hpp"
4 #include <GL/glew.h>
5 #include <GLUT/glut.h>
6 #include <cmath>
7 #include <cstdio>
8 #include <cstdlib>
9 #include <glm/ext.hpp>
10 #include <glm/glm.hpp>
11 #include <vector>
12
13 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
14
15 using namespace std;
16 using namespace glm;
17
18 // calculate continuous distribution
19 void calcContDist(Clouds *clds);
20
21 float w(int i, int j, int k) { return 1; }
22
23 const float metaballR = 1;
24 float metaballField(float r) {
25   if (r > metaballR)
26     return 0;
27   const float a = r / metaballR;
28   return (-4.f / 9.f * powf(a, 6)) + (17.f / 9.f * powf(a, 4)) -
29          (22.f / 9.f * powf(a, 2)) + 1;
30 }
31
32 /* const float normalizationFactor = 748.f / 405.f * M_PI * metaballR; */
33
34 void calcContDist(Clouds *clds, float t) {
35   const int i0 = 2, j0 = 2, k0 = 2, t0 = 2;
36   const float divisor =
37       1.f / ((2 * t0 + 1) * (2 * k0 + 1) * (2 * j0 + 1) * (2 * i0 + 1));
38   float sum = 0;
39   for (int i = 0; i < CLOUD_DIM; i++) {
40     for (int j = 0; j < CLOUD_DIM; j++) {
41       for (int k = 0; k < CLOUD_DIM; k++) {
42
43         // inner sums
44         /* for (int tp = -t0, tp < t0; tp++) { */
45         for (int ip = -i0; ip < i0; ip++) {
46           for (int jp = -j0; jp < j0; jp++) {
47             for (int kp = -k0; kp < k0; kp++) {
48
49               sum += w(ip, jp, kp) * (float)clds->cld[i + ip][j + jp][k + kp];
50             }
51           }
52         }
53         /* } */
54
55         clds->contDist[i][j][k] = sum / divisor;
56       }
57     }
58   }
59 }
60
61 void checkError() {
62   if (GLenum e = glGetError()) {
63     fprintf(stderr, "%s\n", gluErrorString(e));
64     abort();
65   }
66 }
67
68 vector<vec4> bbColors;
69
70 GLuint bbProg;
71 GLuint bbVao;
72
73 // Here we need to generate n_q textures for different densities of metaballs
74 // These textures then go on the billboards
75 // The texture stores attenuation ratio?
76
77 #define NQ 1
78 GLuint bbTexIds[NQ];
79
80 // Stores attenuation ratio inside r channel
81 // Should be highest value at center
82 void precalculateBillboardTextures() {
83   float data[32 * 32];
84   // TODO: properly calculate this instead of whatever this is
85   for (int j = 0; j < 32; j++)
86     for (int i = 0; i < 32; i++)
87       data[i + j * 32] = fmin(1.f, 0.5f + 2.f * (distance(vec2(i, j), vec2(16, 16)) / 16));
88
89   glGenTextures(NQ, bbTexIds);
90
91   for (int i = 0; i < NQ; i++) {
92     glBindTexture(GL_TEXTURE_2D, bbTexIds[i]);
93     checkError();
94
95     glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 32, 32, 0, GL_RED, GL_FLOAT, data);
96     glGenerateMipmap(GL_TEXTURE_2D); // required, otherwise texture is blank
97
98     checkError();
99   }
100 }
101
102 struct Metaball {
103   vec3 pos;
104   float r;
105 };
106 // TODO: why is the x axis flipped??
107 /* vector<Metaball> metaballs = {{{-0.5, 0.5, 0.5}, 0.25}, */
108 /*                               {{-0.3, 0.5, 0.3}, 0.25}}; */
109 vector<Metaball> metaballs = {{{0, 0, 0.5}, 1.f},
110                               {{0, 0.3, 0.3}, 0.7f}};
111
112 Clouds cs;
113
114 void calculateMetaballs() {
115   /* stepClouds(&cs); */
116   metaballs.clear();
117   for (int i = 0; i < 256; i++) {
118     float x = ((float)rand()/(float)(RAND_MAX) - 0.5) * 2;
119     float y = ((float)rand()/(float)(RAND_MAX) - 0.5) * 2;
120     float z = ((float)rand()/(float)(RAND_MAX) - 0.5) * 2;
121     float r = (float)rand()/(float)(RAND_MAX) * 1;
122     Metaball m = {{x,y,z}, r};
123     metaballs.push_back(m);
124   }
125   /* for (int i = 0; i < CLOUD_DIM; i++) { */
126   /*   for (int j = 0; j < CLOUD_DIM; j++) { */
127   /*     for (int k = 0; k < CLOUD_DIM; k++) { */
128   /*       if (cs.cld[i][j][k]) { */
129   /*         Metaball m = {{i / (float)CLOUD_DIM, j / (float)CLOUD_DIM, k / (float)CLOUD_DIM}, */
130   /*                       1.f / (float)CLOUD_DIM }; */
131   /*         m.pos = (m.pos * vec3(2)) - vec3(1); */
132   /*         metaballs.push_back(m); */
133   /*       } */
134   /*     } */
135   /*   } */
136   /* } */
137   fprintf(stderr, "num metaballs: %lu\n", metaballs.size());
138 }
139
140 vec3 sunPos = {0, 2, 2}, sunDir = {0, -1, -1};
141 vec3 camPos = {0, 0, -5}, viewPos = {0, 0, 0};
142 mat4 proj; // projection matrix
143 mat4 view; // view matrix
144 float znear = 0.001, zfar = 1000;
145 float width = 600, height = 400;
146 float aspect = width / height;
147
148 void setProjectionAndViewUniforms(GLuint progId) {
149   GLuint projLoc = glGetUniformLocation(progId, "projection");
150   glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(proj));
151
152   GLuint viewLoc = glGetUniformLocation(progId, "view");
153   glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
154 }
155
156 /** Orientates the transformation matrix to face the camera in the view matrix
157  */
158 mat4 faceView(mat4 m) {
159   m[0][0] = view[0][0];
160   m[0][1] = view[1][0];
161   m[0][2] = view[2][0];
162   m[1][0] = view[0][1];
163   m[1][1] = view[1][1];
164   m[1][2] = view[2][1];
165   m[2][0] = view[0][2];
166   m[2][1] = view[1][2];
167   m[2][2] = view[2][2];
168   return m;
169 }
170
171 GLuint attenuationTex;
172
173 void shadeClouds() {
174
175   bbColors.clear();
176
177   glDisable(GL_DEPTH_TEST);
178   // shaderOutput * 0 + buffer * shader alpha
179   glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
180   glEnable(GL_BLEND);
181
182   // sort by ascending distance from the sun
183   sort(metaballs.begin(), metaballs.end(), [](Metaball &a, Metaball &b) {
184     return distance(sunPos, a.pos) < distance(sunPos, b.pos);
185   });
186
187   glActiveTexture(GL_TEXTURE0);
188   glBindTexture(GL_TEXTURE_2D, bbTexIds[0]);
189   glUniform1i(glGetUniformLocation(bbProg, "tex"), 0);
190
191   GLuint modelLoc = glGetUniformLocation(bbProg, "model");
192
193   for (auto k : metaballs) {
194     // place the billboard at the center of k
195     mat4 model = scale(translate(mat4(1), k.pos), vec3(k.r) * 2.f);
196
197     // rotate the billboard so that its normal is oriented to the sun
198     model = faceView(model);
199
200     glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
201
202     // Set the billboard color as RGBA = (1.0, 1.0, 1.0, 1.0).
203     vec4 color = {1, 1, 1, 1};
204     glUniform4fv(glGetUniformLocation(bbProg, "color"), 1,
205                  glm::value_ptr(color));
206
207     // Map the billboard texture with GL_MODULATE.
208     // i.e. multiply rather than add
209     // but glTexEnv is for the old fixed function pipeline --
210     // need to just tell our fragment shader then to modulate
211     glUniform1i(glGetUniformLocation(bbProg, "modulate"), 1);
212
213     // Render the billboard.
214     glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
215
216     // Read the pixel value corresponding to the center of metaball k.
217     // 1. First get position in opengl screen space: from [-1,1]
218     // 2. Normalize to [0,1]
219     // 3. Multiply by (width * height)
220     vec2 screenPos = ((vec2(proj * view * model * vec4(0,0,0,1)) + vec2(1)) / vec2(2))
221                       * vec2(width, height);
222     vec4 pixel;
223     glReadPixels(screenPos.x, screenPos.y, 1, 1, GL_RGBA, GL_FLOAT, value_ptr(pixel));
224     /* if (pixel.g == 0 && pixel.b == 0) abort(); */
225     /* fprintf(stderr, "pixel:"); */
226     /* dump(pixel); */
227
228     // Multiply the pixel value by the sunlight color.
229     vec4 sunColor = {1, 1, 0.9, 1};
230     pixel *= sunColor;
231
232     // Store the color into an array C[k] as the color of the billboard.
233     bbColors.push_back(pixel);
234   }
235
236   saveFBO();
237   checkError();
238 }
239
240 void renderObject() {}
241
242 void renderClouds() {
243   // Sort metaballs in descending order from the viewpoint
244   sort(metaballs.begin(), metaballs.end(), [](Metaball &a, Metaball &b) {
245     return distance(camPos, a.pos) > distance(camPos, b.pos);
246   });
247
248   glDisable(GL_DEPTH_TEST);
249   glEnable(GL_BLEND);
250   // shaderOutput * 1 + buffer * shader alpha
251   glBlendFunc(GL_ONE, GL_SRC_ALPHA);
252   for (int i = 0; i < metaballs.size(); i++) {
253     Metaball k = metaballs[i];
254
255     GLuint modelLoc = glGetUniformLocation(bbProg, "model");
256
257     // Place the billboard at the center of the corresponding metaball n.
258     mat4 model = scale(translate(mat4(1), k.pos), vec3(k.r) * 2.f);
259     // Rotate the billboard so that its normal is oriented to the viewpoint.
260     model = faceView(model);
261
262     glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
263
264     // Set the billboard color as C[n].
265     fprintf(stderr, "bbColors[i]: ");
266     dump(bbColors[i]);
267     /* bbColors[i].x = 1 - bbColors[i].x; */
268     /* bbColors[i].y = 1 - bbColors[i].y; */
269     /* bbColors[i].z = 1 - bbColors[i].z; */
270     bbColors[i].w = 1;
271     glUniform4fv(glGetUniformLocation(bbProg, "color"), 1,
272                  glm::value_ptr(bbColors[i]));
273
274     // Map the billboard texture.
275     glActiveTexture(GL_TEXTURE0);
276     glBindTexture(GL_TEXTURE_2D, bbTexIds[0]);
277     glUniform1i(glGetUniformLocation(bbProg, "tex"), 0);
278
279     // Don't modulate it -- blend it
280     glUniform1i(glGetUniformLocation(bbProg, "modulate"), 0);
281
282     // Render the billboard with the blending function.
283     glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
284   }
285 }
286
287 void display() {
288   // TODO: find a way to make sure there's no clipping
289   view = glm::lookAt(sunPos + sunDir * vec3(20), sunPos, {0, 1, 0});
290   proj = glm::ortho(1.f * aspect, -1.f * aspect, -1.f, 1.f, znear, zfar);
291   setProjectionAndViewUniforms(bbProg);
292
293   glClearColor(1, 1, 1, 1);
294   glClear(GL_COLOR_BUFFER_BIT);
295   shadeClouds();
296
297   view = glm::lookAt(camPos, viewPos, {0, 1, 0});
298   proj = glm::perspective(45.f, aspect, znear, zfar);
299   setProjectionAndViewUniforms(bbProg);
300
301   glClearColor(0.83,1,1,1); // background color
302   glClear(GL_COLOR_BUFFER_BIT);
303   renderObject();               // render things that aren't clouds
304   renderClouds();
305
306   glutSwapBuffers();
307 }
308
309 bool needsRedisplay = false;
310 void timer(int _) {
311   /* calculateMetaballs(); */
312   if (needsRedisplay) {
313     glutPostRedisplay();
314     needsRedisplay = false;
315   }
316   glutTimerFunc(16, timer, 0);
317 }
318
319 void keyboard(unsigned char key, int x, int y) {
320         if (key == ' ') {
321                 calculateMetaballs();
322                 glutPostRedisplay();
323         }
324 }
325
326 int prevMouseX, prevMouseY;
327 bool firstMouse = true;
328 void motion(int x, int y) {
329         if (firstMouse) {
330                 prevMouseX = x;
331                 prevMouseY = y;
332                 firstMouse = false;
333         }
334         float dx = x - prevMouseX, dy = y - prevMouseY;
335         prevMouseX = x; prevMouseY = y;
336         const vec3 origin(0,18,0);
337         const float sensitivity = 0.003f;
338         auto camMat = translate(mat4(1), origin + camPos);
339         auto rotation = rotate(rotate(mat4(1), -dx * sensitivity, {0, 1, 0}),
340                         -dy * sensitivity, {1, 0, 0});
341         auto rotAroundOrig = camMat * rotation * translate(mat4(1), origin - camPos);
342         camPos = rotAroundOrig * glm::vec4(camPos, 0);
343     needsRedisplay = true;
344 }
345
346 int main(int argc, char **argv) {
347   glutInit(&argc, argv);
348   glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGB |
349                       GLUT_3_2_CORE_PROFILE);
350   glutInitWindowSize(width, height);
351   glutCreateWindow("Clouds");
352   glutDisplayFunc(display);
353
354   glewInit();
355
356   Program prog("billboardvert.glsl", "billboardfrag.glsl");
357
358   bbProg = prog.progId;
359   glUseProgram(bbProg);
360
361   glGenVertexArrays(1, &bbVao);
362   glBindVertexArray(bbVao);
363   GLuint vbos[2];
364   glGenBuffers(2, vbos);
365
366   vector<vec3> poss = {{-1, -1, 0}, {-1, 1, 0}, {1, 1, 0}, {1, -1, 0}};
367   vector<GLuint> indices = {2, 1, 0, 3, 2, 0};
368
369   GLuint posLoc = glGetAttribLocation(bbProg, "vPosition");
370   glBindBuffer(GL_ARRAY_BUFFER, vbos[0]);
371   glBufferData(GL_ARRAY_BUFFER, poss.size() * sizeof(glm::vec3), &poss[0],
372                GL_STATIC_DRAW);
373   glEnableVertexAttribArray(posLoc);
374   glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
375
376   glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbos[1]);
377   glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint),
378                &indices[0], GL_STATIC_DRAW);
379
380   prog.validate();
381
382   precalculateBillboardTextures();
383
384   initClouds(&cs);
385   calculateMetaballs();
386
387   glGenTextures(1, &attenuationTex);
388
389   glutKeyboardFunc(keyboard);
390   glutMotionFunc(motion);
391   glutTimerFunc(16, timer, 0);
392
393   // set up billboard prog
394
395   glutMainLoop();
396
397   return 0;
398 }