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