9 #include <OpenGL/glew.h>
11 #include <GLUT/glut.h>
13 #include <glm/glm.hpp>
14 #include <glm/ext.hpp>
15 #include <glm/gtc/type_ptr.hpp>
16 #include <assimp/Importer.hpp>
17 #include <assimp/scene.h>
18 #include <assimp/postprocess.h>
20 #include "program.hpp"
26 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
32 Program *textureProg, *plainProg, *reflectProg, *pbrProg;
34 std::vector<Skybox> skyboxes;
37 Assimp::Importer importer; // Need to keep this around, otherwise stuff disappears!
40 glm::vec3 camPos = {0, 0, -5}, camFront = {0, 0, 1}, camUp = {0, 1, 0};
41 float fov = glm::radians(30.f), znear = 0.01f, zfar = 10000.f;
42 float yaw = 1.57, pitch = 0;
44 glm::vec3 selectedPos;
51 std::vector<Light> lights;
53 bool discoLights = false;
55 int windowWidth = 800, windowHeight = 600;
58 return (float)windowWidth / (float)windowHeight;
61 inline glm::mat4 projMat() {
62 return glm::perspective(fov, aspect(), znear, zfar);
65 inline glm::mat4 viewMat() {
66 return glm::lookAt(camPos, camPos + camFront, camUp);
69 void setProjectionAndViewUniforms(GLuint progId) {
70 GLuint projLoc = glGetUniformLocation(progId, "projection");
71 glm::mat4 proj = projMat();
72 glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(proj));
74 GLuint viewLoc = glGetUniformLocation(progId, "view");
75 glm::mat4 view = viewMat();
76 glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
78 GLuint camPosLoc = glGetUniformLocation(progId, "camPos");
79 glUniform3fv(camPosLoc, 1, glm::value_ptr(camPos));
82 void setLightColorAndPos(GLuint progId, glm::vec3 lightPos, glm::vec4 lightColor) {
83 GLuint lightColorLoc = glGetUniformLocation(progId, "lightColor");
84 glUniform4fv(lightColorLoc, 1, glm::value_ptr(lightColor));
86 GLuint lightPosLoc = glGetUniformLocation(progId, "vLightPos");
87 glUniform3fv(lightPosLoc, 1, glm::value_ptr(lightPos));
89 GLuint viewPosLoc = glGetUniformLocation(progId, "vViewPos");
90 glUniform3fv(viewPosLoc, 1, glm::value_ptr(camPos));
93 void drawBox(glm::mat4 trans, glm::vec3 color) {
94 glUseProgram(plainProg->progId);
95 glBindVertexArray(lightVao);
96 setProjectionAndViewUniforms(plainProg->progId);
97 glm::mat4 model = glm::scale(trans, glm::vec3(0.3));
98 GLuint modelLoc = glGetUniformLocation(plainProg->progId, "model");
99 glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
101 GLuint colorLoc = glGetUniformLocation(plainProg->progId, "color");
102 glUniform4fv(colorLoc, 1, glm::value_ptr(color));
104 glDrawArrays(GL_TRIANGLES, 0, 36);
107 void drawLight(Light &light) {
108 drawBox(light.trans, light.color);
111 int findNodeTrans(const struct aiNode *n, const struct aiString name, glm::mat4 *dest) {
112 if (strcmp(n->mName.data, name.data) == 0) {
113 *dest = aiMatrixToMat4(n->mTransformation);
116 for (int i = 0; i < n->mNumChildren; i++) {
117 if (findNodeTrans(n->mChildren[i], name, dest) == 0) {
118 glm::mat4 t = aiMatrixToMat4(n->mTransformation);
126 glm::mat4 worldSpaceToModelSpace(aiNode *node, glm::mat4 m) {
127 aiNode *parent = node;
129 std::vector<glm::mat4> trans;
130 while (parent != nullptr) {
131 /* res = res * glm::inverse(aiMatrixToMat4(parent->mTransformation)); */
132 trans.push_back(glm::inverse(aiMatrixToMat4(parent->mTransformation)));
133 parent = parent->mParent;
135 while (!trans.empty()) { res = trans.back() * res; trans.pop_back(); }
140 auto res = sceneModel->closestVertex(sceneModel->getRoot(), camPos, selectedPos);
141 drawBox(glm::translate(glm::mat4(1), res.first), {1, 1, 0.5});
145 glClearColor(0.5, 0.5, 0.5, 1);
146 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
147 glViewport(0, 0, windowWidth * 2, windowHeight * 2);
149 float d = (float)glutGet(GLUT_ELAPSED_TIME) * 0.001f;
151 glUseProgram(getUtilProg()->progId);
152 setProjectionAndViewUniforms(getUtilProg()->progId);
154 glUseProgram(pbrProg->progId);
155 setProjectionAndViewUniforms(pbrProg->progId);
157 size_t numLights = lights.size() + (discoLights ? 3 : 0);
158 glm::vec3 lightPositions[numLights], lightColors[numLights];
159 for (int i = 0; i < lights.size(); i++) {
160 lightPositions[i] = glm::vec3(lights[i].trans[3]);
161 lightColors[i] = lights[i].color;
165 for (int i = numLights - 3; i < numLights; i++) {
166 auto m = glm::translate(glm::mat4(1.f), glm::vec3(-2.5, 0, 0));
167 m = glm::rotate(m, glm::radians(d * 100 + i * 30), glm::vec3(1, 0, 0));
168 m = glm::rotate(m, glm::radians(d * 100 + i * 30), glm::vec3(0, 1, 0));
169 m = glm::rotate(m, glm::radians(d * 100 + i * 30), glm::vec3(0, 0, 1));
170 lightPositions[i] = glm::vec3(m * glm::vec4(5, 0, 0, 1));
171 lightColors[i] = glm::vec3(0.2);
172 if (i % 3 == 0) lightColors[i].x = sin(d);
173 if (i % 3 == 1) lightColors[i].y = cos(d * 3);
174 if (i % 3 == 2) lightColors[i].z = cos(d);
178 glUniform1ui(glGetUniformLocation(pbrProg->progId, "numLights"), numLights);
179 glUniform3fv(glGetUniformLocation(pbrProg->progId, "lightPositions"), numLights, glm::value_ptr(lightPositions[0]));
180 glUniform3fv(glGetUniformLocation(pbrProg->progId, "lightColors"), numLights, glm::value_ptr(lightColors[0]));
184 glm::vec3 targetPos(sin(d) * 2 + 3, -2, 1);
185 Light targetLight = { glm::translate(glm::mat4(1), targetPos), {0.5, 1, 1} };
186 drawLight(targetLight);
187 inverseKinematics(*sceneModel->find("Shoulder.L"), *sceneModel->find("Finger.L"), targetPos);
189 targetPos = { sin(d * 2) * 2 - 5, 2.5, 0 };
190 targetLight = { glm::translate(glm::mat4(1), targetPos), {1, 1, 0.5} };
191 drawLight(targetLight);
192 inverseKinematics(*sceneModel->find("Shoulder.R"), *sceneModel->find("Finger.R"), targetPos);
196 sceneModel->draw(skyboxes[activeSkybox], d * 1000);
200 for (Light &light: lights) drawLight(light);
203 /* if (discoLights) { */
204 /* for (int i = numLights - 3; i < numLights; i++) { */
205 /* Light l = { lightPositions[i], lightColors[i] }; */
210 skyboxes[activeSkybox].draw(projMat(), viewMat());
215 void setupLightBuffers(GLuint progId) {
216 auto vertices = cube();
217 GLuint verticesSize = 36 * 3 * sizeof(GLfloat);
219 glGenVertexArrays(1, &lightVao);
221 glBindVertexArray(lightVao);
222 glGenBuffers(1, &vbo);
223 glBindBuffer(GL_ARRAY_BUFFER, vbo);
224 glBufferData(GL_ARRAY_BUFFER, verticesSize, NULL, GL_STATIC_DRAW);
225 glBufferSubData(GL_ARRAY_BUFFER, 0, verticesSize, glm::value_ptr(vertices[0]));
226 GLuint posLoc = glGetAttribLocation(progId, "vPosition");
227 glEnableVertexAttribArray(posLoc);
228 glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
235 plainProg = new Program("plainvertex.glsl", "plainfrag.glsl");
236 glUseProgram(plainProg->progId);
237 setupLightBuffers(plainProg->progId);
238 plainProg->validate();
240 skyboxes.push_back(Skybox(Image("skyboxes/loft/Newport_Loft_Ref.hdr")));
241 skyboxes.push_back(Skybox(Image("skyboxes/wooden_lounge_8k.hdr")));
242 skyboxes.push_back(Skybox(Image("skyboxes/machine_shop_02_8k.hdr")));
243 skyboxes.push_back(Skybox(Image("skyboxes/pink_sunrise_8k.hdr")));
245 pbrProg = new Program("pbrvert.glsl", "pbrfrag.glsl");
246 glUseProgram(pbrProg->progId);
248 const std::string scenePath = "models/blendshapeNeutral.glb";
249 const aiScene *scene = importer.ReadFile(scenePath, aiProcess_Triangulate | aiProcess_CalcTangentSpace | aiProcess_GenNormals | aiProcess_FlipUVs);
251 std::cerr << importer.GetErrorString() << std::endl;
255 if (scene->mNumCameras > 0) {
256 aiCamera *cam = scene->mCameras[0];
258 if (findNodeTrans(scene->mRootNode, cam->mName, &camTrans) != 0)
259 abort(); // there must be a node with the same name as camera
261 camPos = { camTrans[3][0], camTrans[3][1], camTrans[3][2] };
263 glm::vec3 camLookAt = glm::vec3(cam->mLookAt.x, cam->mLookAt.y, cam->mLookAt.z);
264 camFront = camLookAt - camPos;
266 camUp = glm::vec3(cam->mUp.x, cam->mUp.y, cam->mUp.z);
268 fov = cam->mHorizontalFOV;
269 // TODO: aspectRatio = cam->mAspect;
270 znear = cam->mClipPlaneNear;
271 zfar = cam->mClipPlaneFar;
274 for (int i = 0; i < scene->mNumLights; i++) {
275 aiLight *light = scene->mLights[i];
276 glm::mat4 trans; findNodeTrans(scene->mRootNode, light->mName, &trans);
277 glm::vec3 col = { light->mColorAmbient.r, light->mColorAmbient.g, light->mColorAmbient.b };
278 Light l = { trans, col };
282 sceneModel = new Model(scene, *pbrProg);
284 glEnable(GL_DEPTH_TEST);
285 glEnable(GL_CULL_FACE);
286 // prevent edge artifacts in specular cubemaps
287 glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
289 glViewport(0, 0, windowWidth * 2, windowHeight * 2);
292 bool keyStates[256] = {false};
294 void keyboard(unsigned char key, int x, int y) {
295 keyStates[key] = true;
297 activeSkybox = (activeSkybox + 1) % skyboxes.size();
299 discoLights = !discoLights;
302 void keyboardUp(unsigned char key, int x, int y) {
303 keyStates[key] = false;
306 /* #define ENABLE_MOVEMENT */
309 #ifdef ENABLE_MOVEMENT
310 float xSpeed = 0.f, ySpeed = 0.f, zSpeed = 0.f;
312 #pragma clang diagnostic push
313 #pragma clang diagnostic ignored "-Wchar-subscripts"
326 #pragma clang diagnostic pop
328 camPos.x += xSpeed * sin(yaw) + zSpeed * cos(yaw);
330 camPos.z += zSpeed * sin(yaw) - xSpeed * cos(yaw);
333 glutTimerFunc(16, timer, 0);
336 int prevMouseX, prevMouseY;
337 bool firstMouse = true;
339 void motion(int x, int y) {
340 #ifdef ENABLE_MOVEMENT
346 int dx = x - prevMouseX, dy = y - prevMouseY;
351 const float sensitivity = 0.005f;
352 yaw += dx * sensitivity;
353 pitch -= dy * sensitivity;
356 front.x = cos(pitch) * cos(yaw);
357 front.y = sin(pitch);
358 front.z = cos(pitch) * sin(yaw);
359 camFront = glm::normalize(front);
361 if (pitch < -1.57079632679 || pitch >= 1.57079632679) {
362 camUp = glm::vec3(0, -1, 0);
364 camUp = glm::vec3(0, 1, 0);
368 GLint vpArr[4]; glGetIntegerv(GL_VIEWPORT, vpArr);
369 glm::vec4 viewport(vpArr[0], vpArr[1], vpArr[2], vpArr[3]);
370 selectedPos = glm::unProject(glm::vec3(x * 2, viewport[3] - y * 2, 1), // hidpi
371 viewMat(), //view * model mat
376 void mouse(int button, int state, int x, int y) {
377 #ifdef ENABLE_MOVEMENT
378 if (button == GLUT_LEFT_BUTTON && state == GLUT_UP)
383 void reshape(int newWidth, int newHeight) {
384 windowWidth = newWidth, windowHeight = newHeight;
387 int main(int argc, char** argv) {
388 glutInit(&argc, argv);
389 glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGB|GLUT_3_2_CORE_PROFILE);
390 glutInitWindowSize(windowWidth, windowHeight);
391 glutCreateWindow("Physically Based Rendering");
392 glutDisplayFunc(display);
393 glutReshapeFunc(reshape);
399 glutKeyboardFunc(keyboard);
400 glutKeyboardUpFunc(keyboardUp);
401 glutTimerFunc(16, timer, 0);
402 glutMotionFunc(motion);
403 glutPassiveMotionFunc(motion);
404 glutMouseFunc(mouse);