-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathView.cpp
332 lines (261 loc) · 11.1 KB
/
View.cpp
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#include "View.h"
#include "GLFW/glfw3.h"
#include "../include/Light.h"
#include "PPMImageLoader.h"
#include "PolygonMesh.h"
#include "TextureImage.h"
#include "sgraph/LightAccumulator.h"
#include "sgraph/RaycastRenderer.hpp"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
#include <glm/glm.hpp>
#include <glm/ext/quaternion_trigonometric.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/quaternion.hpp>
#include <chrono>
#include <ctime>
#include "sgraph/GLScenegraphRenderer.h"
#include "VertexAttrib.h"
View::View(bool useOpenGl) : useRaycast(!useOpenGl) {
}
View::~View(){
}
void View::init(Callbacks *callbacks, Model& model)
{
if (!glfwInit())
exit(EXIT_FAILURE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
window = glfwCreateWindow(800, 800, "Hello GLFW: Per-vertex coloring", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwSetWindowUserPointer(window, (void *)callbacks);
//using C++ functions as callbacks to a C-style library
glfwSetKeyCallback(window,
[](GLFWwindow* window, int key, int scancode, int action, int mods)
{
reinterpret_cast<Callbacks*>(glfwGetWindowUserPointer(window))->onkey(key,scancode,action,mods);
});
glfwSetWindowSizeCallback(window,
[](GLFWwindow* window, int width,int height)
{
reinterpret_cast<Callbacks*>(glfwGetWindowUserPointer(window))->reshape(width,height);
});
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
glfwSetCursorPosCallback(window,
[](GLFWwindow* window, double xpos, double ypos)
{
reinterpret_cast<Callbacks*>(glfwGetWindowUserPointer(window))->mousePosition(xpos,ypos);
});
glfwSetMouseButtonCallback(window,
[](GLFWwindow* window, int button, int action, int mods)
{
reinterpret_cast<Callbacks*>(glfwGetWindowUserPointer(window))->mouseButton(button, action, mods);
});
glfwMakeContextCurrent(window);
gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
glfwSwapInterval(1);
// create the shader program
program.createProgram(string("shaders/phong-multiple.vert.glsl"),
string("shaders/phong-spot.frag.glsl"));
// assuming it got created, get all the shader variables that it uses
// so we can initialize them at some point
// enable the shader program
program.enable();
shaderLocations = program.getAllShaderVariables();
initObjects(model);
initLights(model);
initShaderVariables();
resize();
frames = 0;
time = glfwGetTime();
deltaTime = 0;
if (!useRaycast)
renderer = new sgraph::GLScenegraphRenderer(modelview,objects,textureIds,shaderLocations);
}
void View::initLights(Model& model) {
modelview.push(glm::mat4(1.0));
sgraph::LightAccumulator lightAccum(modelview);
model.getScenegraph()->getRoot()->accept(&lightAccum);
modelview.pop();
for (auto light : lightAccum.getLights()) {
lights.push_back(light);
lightCoordinateSystems.push_back("world"); //in world
}
}
void View::initObjects(Model& model) {
map<string,string> shaderVarsToVertexAttribs;
shaderVarsToVertexAttribs["vPosition"] = "position";
shaderVarsToVertexAttribs["vNormal"] = "normal";
shaderVarsToVertexAttribs["vTexCoord"] = "texcoord";
map<string,util::PolygonMesh<VertexAttrib> > meshes = model.getScenegraph()->getMeshes();
for (typename map<string,util::PolygonMesh<VertexAttrib> >::iterator it=meshes.begin();
it!=meshes.end();
it++) {
std::cout << it->first << std::endl;
util::ObjectInstance * obj = new util::ObjectInstance(it->first);
obj->initPolygonMesh(shaderLocations,shaderVarsToVertexAttribs,it->second);
objects[it->first] = obj;
}
//textures
textures = model.getScenegraph()->getTextures();
PPMImageLoader ppmLoader;
ImageLoader *imgLoader = &ppmLoader;
imgLoader->load("textures/white.ppm");
textures[""] = new util::TextureImage(imgLoader->getPixels(),imgLoader->getWidth(),imgLoader->getHeight(),"");
glEnable(GL_TEXTURE_2D);
for (auto& texturePair : textures) {
util::TextureImage* textureObject = texturePair.second;
unsigned int textureId;
glGenTextures(1,&textureId);
glBindTexture(GL_TEXTURE_2D,textureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); //if the s-coordinate goes outside (0,1), repeat it
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); //if the t-coordinate goes outside (0,1), repeat it
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, textureObject->getWidth(),textureObject->getHeight(), 0, GL_RGB, GL_UNSIGNED_BYTE,textureObject->getImage());
glGenerateMipmap(GL_TEXTURE_2D);
textureIds[texturePair.first] = textureId;
}
util::PolygonMesh<VertexAttrib> cameraMesh = model.getCameraMesh();
cameraObj = new util::ObjectInstance("camera");
cameraObj->initPolygonMesh(shaderLocations, shaderVarsToVertexAttribs, cameraMesh);
}
void View::initShaderVariables() {
//get input variables that need to be given to the shader program
for (int i = 0; i < lights.size(); i++)
{
LightLocation ll;
stringstream name;
name << "light[" << i << "]";
ll.ambient = shaderLocations.getLocation(name.str() + "" +".ambient");
ll.diffuse = shaderLocations.getLocation(name.str() + ".diffuse");
ll.specular = shaderLocations.getLocation(name.str() + ".specular");
ll.position = shaderLocations.getLocation(name.str() + ".position");
ll.spotDirection = shaderLocations.getLocation(name.str() + ".spotDirection");
ll.spotCutoff = shaderLocations.getLocation(name.str() + ".spotCutoff");
lightLocations.push_back(ll);
}
}
float View::display(sgraph::IScenegraph *scenegraph, vector<Camera*>& cameras, Camera* activeCamera) {
if (useRaycast) {
modelview.push(glm::mat4(1.0));
modelview.top() *= activeCamera->GetViewMatrix();
raycastRenderer = new sgraph::RaycastRenderer(textures, modelview,lights,"output_render.ppm");
scenegraph->getRoot()->accept(raycastRenderer);
raycastRenderer->raytrace(800, 800, modelview);
modelview.pop();
return -1;
}
program.enable();
glClearColor(0,0,0,1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
modelview.push(glm::mat4(1.0));
modelview.top() *= activeCamera->GetViewMatrix();
glUniformMatrix4fv(shaderLocations.getLocation("projection"), 1, GL_FALSE, glm::value_ptr(projection));
//modelview currently represents world-to-view transformation
//transform all lights into the view coordinate system before passing to
//shaders. That way everything will be in one coordinate system in the shader
//(the view) and the math will be correct
for (int i = 0; i < lights.size(); i++) {
glm::vec4 pos = lights[i].getPosition();
glm::vec4 spotDir = lights[i].getSpotDirection();
glm::mat4 lightTransformation;
if (lightCoordinateSystems[i]=="view") {
lightTransformation = glm::mat4(1.0);
}
else { //(lightCoordinateSystems[i]=="world") {
lightTransformation = modelview.top();
}
/*
else {
lightTransformation = modelview.top() * model.getTransform(lightCoordinateSystems[i]);
}
*/
pos = lightTransformation * pos;
// cout << glm::to_string(pos) << endl;
glUniform4fv(lightLocations[i].position, 1, glm::value_ptr(pos));
spotDir = lightTransformation * spotDir;
glUniform3fv(lightLocations[i].spotDirection, 1, glm::value_ptr(glm::normalize(spotDir)));
glUniform1f(lightLocations[i].spotCutoff, cosf(lights[i].getSpotCutoff()));
}
//pass light color properties to shader
glUniform1i(shaderLocations.getLocation("numLights"),lights.size());
//pass light colors to the shader
for (int i = 0; i < lights.size(); i++) {
glUniform3fv(lightLocations[i].ambient, 1, glm::value_ptr(lights[i].getAmbient()));
glUniform3fv(lightLocations[i].diffuse, 1, glm::value_ptr(lights[i].getDiffuse()));
glUniform3fv(lightLocations[i].specular, 1,glm::value_ptr(lights[i].getSpecular()));
}
glUniform1i(shaderLocations.getLocation("useOldShader"), false);
//draw scene graph here
scenegraph->getRoot()->accept(renderer);
for (auto& camera : cameras) {
if (camera == activeCamera) continue;
glUniform1i(shaderLocations.getLocation("useOldShader"), true);
glUniform4f(shaderLocations.getLocation("vColor"), 0.0, 1.0, 0.0, 1.0);
glUniformMatrix4fv(shaderLocations.getLocation("modelview"), 1, GL_FALSE, glm::value_ptr(camera->GetModelviewMatrix(modelview.top(), aspectRatio, glm::radians(60.0f))));
cameraObj->draw();
}
modelview.pop();
glFlush();
program.disable();
glfwSwapBuffers(window);
glfwPollEvents();
frames++;
double currenttime = glfwGetTime();
deltaTime = currenttime - time;
time = currenttime;
return deltaTime;
}
void View::resize() {
if (useRaycast) return;
int window_width,window_height;
glfwGetFramebufferSize(window,&window_width,&window_height);
aspectRatio = (float)window_width/window_height;
//prepare the projection matrix for perspective projection
projection = glm::perspective(glm::radians(60.0f),aspectRatio,0.1f,10000.0f);
glViewport(0, 0, window_width,window_height);
}
bool View::shouldWindowClose() {
if (useRaycast) return false;
return glfwWindowShouldClose(window);
}
void View::closeWindow() {
for (map<string,util::ObjectInstance *>::iterator it=objects.begin();
it!=objects.end();
it++) {
it->second->cleanup();
delete it->second;
}
cameraObj->cleanup();
delete cameraObj;
if (useRaycast) {
delete raycastRenderer;
}
glfwDestroyWindow(window);
glfwTerminate();
}
void View::output_raytrace(sgraph::IScenegraph *scenegraph, Camera *activeCamera) {
cout << "Attempting to output raytrace." << endl;
auto startTime = std::chrono::system_clock::now();
modelview.push(glm::mat4(1.0));
modelview.top() *= activeCamera->GetViewMatrix();
raycastRenderer = new sgraph::RaycastRenderer(textures, modelview,lights,"output_render.ppm");
scenegraph->getRoot()->accept(raycastRenderer);
raycastRenderer->raytrace(800, 800, modelview);
modelview.pop();
std::chrono::duration<double> elapsedTime = std::chrono::system_clock::now() - startTime;
cout << "Generated raytrace output in " << elapsedTime.count() << " seconds" << endl;
}