/
OpenGLGraphicsManager.cpp
616 lines (497 loc) · 20.2 KB
/
OpenGLGraphicsManager.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
#include <iostream>
#include <fstream>
#include "OpenGLGraphicsManager.hpp"
#include "AssetLoader.hpp"
#include "IApplication.hpp"
#include "SceneManager.hpp"
const char VS_SHADER_SOURCE_FILE[] = "Shaders/basic_vs.glsl";
const char PS_SHADER_SOURCE_FILE[] = "Shaders/basic_ps.glsl";
using namespace My;
using namespace std;
extern struct gladGLversionStruct GLVersion;
namespace My {
extern AssetLoader* g_pAssetLoader;
static void OutputShaderErrorMessage(unsigned int shaderId, const char* shaderFilename)
{
int logSize, i;
char* infoLog;
ofstream fout;
// Get the size of the string containing the information log for the failed shader compilation message.
glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &logSize);
// Increment the size by one to handle also the null terminator.
logSize++;
// Create a char buffer to hold the info log.
infoLog = new char[logSize];
if(!infoLog)
{
return;
}
// Now retrieve the info log.
glGetShaderInfoLog(shaderId, logSize, NULL, infoLog);
// Open a file to write the error message to.
fout.open("shader-error.txt");
// Write out the error message.
for(i=0; i<logSize; i++)
{
fout << infoLog[i];
}
// Close the file.
fout.close();
// Pop a message up on the screen to notify the user to check the text file for compile errors.
cerr << "Error compiling shader. Check shader-error.txt for message." << shaderFilename << endl;
return;
}
static void OutputLinkerErrorMessage(unsigned int programId)
{
int logSize, i;
char* infoLog;
ofstream fout;
// Get the size of the string containing the information log for the failed shader compilation message.
glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &logSize);
// Increment the size by one to handle also the null terminator.
logSize++;
// Create a char buffer to hold the info log.
infoLog = new char[logSize];
if(!infoLog)
{
return;
}
// Now retrieve the info log.
glGetProgramInfoLog(programId, logSize, NULL, infoLog);
// Open a file to write the error message to.
fout.open("linker-error.txt");
// Write out the error message.
for(i=0; i<logSize; i++)
{
fout << infoLog[i];
}
// Close the file.
fout.close();
// Pop a message up on the screen to notify the user to check the text file for linker errors.
cerr << "Error compiling linker. Check linker-error.txt for message." << endl;
}
}
int OpenGLGraphicsManager::Initialize()
{
int result;
result = gladLoadGL();
if (!result) {
cerr << "OpenGL load failed!" << endl;
result = -1;
} else {
result = 0;
cout << "OpenGL Version " << GLVersion.major << "." << GLVersion.minor << " loaded" << endl;
if (GLAD_GL_VERSION_3_3) {
// Set the depth buffer to be entirely cleared to 1.0 values.
glClearDepth(1.0f);
// Enable depth testing.
glEnable(GL_DEPTH_TEST);
// Set the polygon winding to front facing for the right handed system.
glFrontFace(GL_CCW);
// Enable back face culling.
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
// Initialize the world/model matrix to the identity matrix.
BuildIdentityMatrix(m_DrawFrameContext.m_worldMatrix);
}
InitializeShader(VS_SHADER_SOURCE_FILE, PS_SHADER_SOURCE_FILE);
InitializeBuffers();
}
return result;
}
void OpenGLGraphicsManager::Finalize()
{
for (auto dbc : m_DrawBatchContext) {
glDeleteVertexArrays(1, &dbc.vao);
}
m_DrawBatchContext.clear();
for (auto i = 0; i < m_Buffers.size() - 1; i++) {
glDisableVertexAttribArray(i);
}
for (auto buf : m_Buffers) {
glDeleteBuffers(1, &buf);
}
m_Buffers.clear();
// Detach the vertex and fragment shaders from the program.
glDetachShader(m_shaderProgram, m_vertexShader);
glDetachShader(m_shaderProgram, m_fragmentShader);
// Delete the vertex and fragment shaders.
glDeleteShader(m_vertexShader);
glDeleteShader(m_fragmentShader);
// Delete the shader program.
glDeleteProgram(m_shaderProgram);
}
void OpenGLGraphicsManager::Tick()
{
}
void OpenGLGraphicsManager::Clear()
{
// Set the color to clear the screen to.
glClearColor(0.2f, 0.3f, 0.4f, 1.0f);
// Clear the screen and depth buffer.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void OpenGLGraphicsManager::Draw()
{
// Render the model using the color shader.
RenderBuffers();
glFlush();
}
bool OpenGLGraphicsManager::SetPerFrameShaderParameters()
{
unsigned int location;
// Set the world matrix in the vertex shader.
location = glGetUniformLocation(m_shaderProgram, "worldMatrix");
if(location == -1)
{
return false;
}
glUniformMatrix4fv(location, 1, false, m_DrawFrameContext.m_worldMatrix);
// Set the view matrix in the vertex shader.
location = glGetUniformLocation(m_shaderProgram, "viewMatrix");
if(location == -1)
{
return false;
}
glUniformMatrix4fv(location, 1, false, m_DrawFrameContext.m_viewMatrix);
// Set the projection matrix in the vertex shader.
location = glGetUniformLocation(m_shaderProgram, "projectionMatrix");
if(location == -1)
{
return false;
}
glUniformMatrix4fv(location, 1, false, m_DrawFrameContext.m_projectionMatrix);
// Set lighting parameters for PS shader
location = glGetUniformLocation(m_shaderProgram, "lightPosition");
if(location == -1)
{
return false;
}
glUniform3fv(location, 1, m_DrawFrameContext.m_lightPosition);
location = glGetUniformLocation(m_shaderProgram, "lightColor");
if(location == -1)
{
return false;
}
glUniform4fv(location, 1, m_DrawFrameContext.m_lightColor);
return true;
}
bool OpenGLGraphicsManager::SetPerBatchShaderParameters(const char* paramName, const Matrix4X4f& param)
{
unsigned int location;
location = glGetUniformLocation(m_shaderProgram, paramName);
if(location == -1)
{
return false;
}
glUniformMatrix4fv(location, 1, false, param);
return true;
}
bool OpenGLGraphicsManager::SetPerBatchShaderParameters(const char* paramName, const Vector3f& param)
{
unsigned int location;
location = glGetUniformLocation(m_shaderProgram, paramName);
if(location == -1)
{
return false;
}
glUniform3fv(location, 1, param);
return true;
}
bool OpenGLGraphicsManager::SetPerBatchShaderParameters(const char* paramName, const float param)
{
unsigned int location;
location = glGetUniformLocation(m_shaderProgram, paramName);
if(location == -1)
{
return false;
}
glUniform1f(location, param);
return true;
}
void OpenGLGraphicsManager::InitializeBuffers()
{
auto& scene = g_pSceneManager->GetSceneForRendering();
// Geometries
auto pGeometryNode = scene.GetFirstGeometryNode();
while (pGeometryNode)
{
if (pGeometryNode->Visible())
{
auto pGeometry = scene.GetGeometry(pGeometryNode->GetSceneObjectRef());
assert(pGeometry);
auto pMesh = pGeometry->GetMesh().lock();
if (!pMesh) return;
// Set the number of vertex properties.
auto vertexPropertiesCount = pMesh->GetVertexPropertiesCount();
// Set the number of vertices in the vertex array.
auto vertexCount = pMesh->GetVertexCount();
// Allocate an OpenGL vertex array object.
GLuint vao;
glGenVertexArrays(1, &vao);
// Bind the vertex array object to store all the buffers and vertex attributes we create here.
glBindVertexArray(vao);
GLuint buffer_id;
for (int32_t i = 0; i < vertexPropertiesCount; i++)
{
const SceneObjectVertexArray& v_property_array = pMesh->GetVertexPropertyArray(i);
auto v_property_array_data_size = v_property_array.GetDataSize();
auto v_property_array_data = v_property_array.GetData();
// Generate an ID for the vertex buffer.
glGenBuffers(1, &buffer_id);
// Bind the vertex buffer and load the vertex (position and color) data into the vertex buffer.
glBindBuffer(GL_ARRAY_BUFFER, buffer_id);
glBufferData(GL_ARRAY_BUFFER, v_property_array_data_size, v_property_array_data, GL_STATIC_DRAW);
glEnableVertexAttribArray(i);
switch (v_property_array.GetDataType()) {
case VertexDataType::kVertexDataTypeFloat1:
glVertexAttribPointer(i, 1, GL_FLOAT, false, 0, 0);
break;
case VertexDataType::kVertexDataTypeFloat2:
glVertexAttribPointer(i, 2, GL_FLOAT, false, 0, 0);
break;
case VertexDataType::kVertexDataTypeFloat3:
glVertexAttribPointer(i, 3, GL_FLOAT, false, 0, 0);
break;
case VertexDataType::kVertexDataTypeFloat4:
glVertexAttribPointer(i, 4, GL_FLOAT, false, 0, 0);
break;
case VertexDataType::kVertexDataTypeDouble1:
glVertexAttribPointer(i, 1, GL_DOUBLE, false, 0, 0);
break;
case VertexDataType::kVertexDataTypeDouble2:
glVertexAttribPointer(i, 2, GL_DOUBLE, false, 0, 0);
break;
case VertexDataType::kVertexDataTypeDouble3:
glVertexAttribPointer(i, 3, GL_DOUBLE, false, 0, 0);
break;
case VertexDataType::kVertexDataTypeDouble4:
glVertexAttribPointer(i, 4, GL_DOUBLE, false, 0, 0);
break;
default:
assert(0);
}
m_Buffers.push_back(buffer_id);
}
auto indexGroupCount = pMesh->GetIndexGroupCount();
GLenum mode;
switch(pMesh->GetPrimitiveType())
{
case PrimitiveType::kPrimitiveTypePointList:
mode = GL_POINTS;
break;
case PrimitiveType::kPrimitiveTypeLineList:
mode = GL_LINES;
break;
case PrimitiveType::kPrimitiveTypeLineStrip:
mode = GL_LINE_STRIP;
break;
case PrimitiveType::kPrimitiveTypeTriList:
mode = GL_TRIANGLES;
break;
case PrimitiveType::kPrimitiveTypeTriStrip:
mode = GL_TRIANGLE_STRIP;
break;
case PrimitiveType::kPrimitiveTypeTriFan:
mode = GL_TRIANGLE_FAN;
break;
default:
// ignore
continue;
}
for (decltype(indexGroupCount) i = 0; i < indexGroupCount; i++)
{
// Generate an ID for the index buffer.
glGenBuffers(1, &buffer_id);
const SceneObjectIndexArray& index_array = pMesh->GetIndexArray(i);
auto index_array_size = index_array.GetDataSize();
auto index_array_data = index_array.GetData();
// Bind the index buffer and load the index data into it.
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer_id);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_array_size, index_array_data, GL_STATIC_DRAW);
// Set the number of indices in the index array.
GLsizei indexCount = static_cast<GLsizei>(index_array.GetIndexCount());
GLenum type;
switch(index_array.GetIndexType())
{
case IndexDataType::kIndexDataTypeInt8:
type = GL_UNSIGNED_BYTE;
break;
case IndexDataType::kIndexDataTypeInt16:
type = GL_UNSIGNED_SHORT;
break;
case IndexDataType::kIndexDataTypeInt32:
type = GL_UNSIGNED_INT;
break;
default:
// not supported by OpenGL
cerr << "Error: Unsupported Index Type " << index_array << endl;
cerr << "Mesh: " << *pMesh << endl;
cerr << "Geometry: " << *pGeometry << endl;
continue;
}
m_Buffers.push_back(buffer_id);
size_t material_index = index_array.GetMaterialIndex();
std::string material_key = pGeometryNode->GetMaterialRef(material_index);
DrawBatchContext& dbc = *(new DrawBatchContext);
dbc.vao = vao;
dbc.mode = mode;
dbc.type = type;
dbc.counts.push_back(indexCount);
dbc.transform = pGeometryNode->GetCalculatedTransform();
dbc.material = scene.GetMaterial(material_key);
m_DrawBatchContext.push_back(std::move(dbc));
}
}
pGeometryNode = scene.GetNextGeometryNode();
}
return;
}
void OpenGLGraphicsManager::RenderBuffers()
{
static float rotateAngle = 0.0f;
// Update world matrix to rotate the model
rotateAngle += PI / 360;
//Matrix4X4f rotationMatrixY;
Matrix4X4f rotationMatrixZ;
//MatrixRotationY(rotationMatrixY, rotateAngle);
MatrixRotationZ(rotationMatrixZ, rotateAngle);
//MatrixMultiply(m_DrawFrameContext.m_worldMatrix, rotationMatrixZ, rotationMatrixY);
m_DrawFrameContext.m_worldMatrix = rotationMatrixZ;
// Generate the view matrix based on the camera's position.
CalculateCameraMatrix();
CalculateLights();
SetPerFrameShaderParameters();
for (auto dbc : m_DrawBatchContext)
{
// Set the color shader as the current shader program and set the matrices that it will use for rendering.
glUseProgram(m_shaderProgram);
SetPerBatchShaderParameters("modelMatrix", *dbc.transform);
if (dbc.material) {
Color color = dbc.material->GetBaseColor();
SetPerBatchShaderParameters("defuseColor", color.Value.rgb);
color = dbc.material->GetSpecularColor();
SetPerBatchShaderParameters("specularColor", color.Value.rgb);
Parameter param = dbc.material->GetSpecularPower();
SetPerBatchShaderParameters("specularPower", param.Value);
}
glBindVertexArray(dbc.vao);
auto indexBufferCount = dbc.counts.size();
const GLvoid ** pIndicies = new const GLvoid*[indexBufferCount];
memset(pIndicies, 0x00, sizeof(GLvoid*) * indexBufferCount);
// Render the vertex buffer using the index buffer.
glMultiDrawElements(dbc.mode, dbc.counts.data(), dbc.type, pIndicies, indexBufferCount);
delete[] pIndicies;
}
return;
}
void OpenGLGraphicsManager::CalculateCameraMatrix()
{
auto& scene = g_pSceneManager->GetSceneForRendering();
auto pCameraNode = scene.GetFirstCameraNode();
if (pCameraNode) {
m_DrawFrameContext.m_viewMatrix = *pCameraNode->GetCalculatedTransform();
InverseMatrix4X4f(m_DrawFrameContext.m_viewMatrix);
}
else {
// use default build-in camera
Vector3f position = { 0, -5, 0 }, lookAt = { 0, 0, 0 }, up = { 0, 0, 1 };
BuildViewMatrix(m_DrawFrameContext.m_viewMatrix, position, lookAt, up);
}
float fieldOfView = PI / 2.0f;
float nearClipDistance = 1.0f;
float farClipDistance = 100.0f;
if (pCameraNode) {
auto pCamera = scene.GetCamera(pCameraNode->GetSceneObjectRef());
// Set the field of view and screen aspect ratio.
fieldOfView = dynamic_pointer_cast<SceneObjectPerspectiveCamera>(pCamera)->GetFov();
nearClipDistance = pCamera->GetNearClipDistance();
farClipDistance = pCamera->GetFarClipDistance();
}
const GfxConfiguration& conf = g_pApp->GetConfiguration();
float screenAspect = (float)conf.screenWidth / (float)conf.screenHeight;
// Build the perspective projection matrix.
BuildPerspectiveFovRHMatrix(m_DrawFrameContext.m_projectionMatrix, fieldOfView, screenAspect, nearClipDistance, farClipDistance);
}
void OpenGLGraphicsManager::CalculateLights()
{
auto& scene = g_pSceneManager->GetSceneForRendering();
auto pLightNode = scene.GetFirstLightNode();
if (pLightNode) {
m_DrawFrameContext.m_lightPosition = { 0.0f, 0.0f, 0.0f };
TransformCoord(m_DrawFrameContext.m_lightPosition, *pLightNode->GetCalculatedTransform());
auto pLight = scene.GetLight(pLightNode->GetSceneObjectRef());
if (pLight) {
m_DrawFrameContext.m_lightColor = pLight->GetColor().Value;
}
}
else {
// use default build-in light
m_DrawFrameContext.m_lightPosition = { -1.0f, -5.0f, 0.0f};
m_DrawFrameContext.m_lightColor = { 1.0f, 1.0f, 1.0f, 1.0f };
}
}
bool OpenGLGraphicsManager::InitializeShader(const char* vsFilename, const char* fsFilename)
{
std::string vertexShaderBuffer;
std::string fragmentShaderBuffer;
int status;
// Load the vertex shader source file into a text buffer.
vertexShaderBuffer = g_pAssetLoader->SyncOpenAndReadTextFileToString(vsFilename);
if(vertexShaderBuffer.empty())
{
return false;
}
// Load the fragment shader source file into a text buffer.
fragmentShaderBuffer = g_pAssetLoader->SyncOpenAndReadTextFileToString(fsFilename);
if(fragmentShaderBuffer.empty())
{
return false;
}
// Create a vertex and fragment shader object.
m_vertexShader = glCreateShader(GL_VERTEX_SHADER);
m_fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
// Copy the shader source code strings into the vertex and fragment shader objects.
const char* _v_c_str = vertexShaderBuffer.c_str();
glShaderSource(m_vertexShader, 1, &_v_c_str, NULL);
const char* _f_c_str = fragmentShaderBuffer.c_str();
glShaderSource(m_fragmentShader, 1, &_f_c_str, NULL);
// Compile the shaders.
glCompileShader(m_vertexShader);
glCompileShader(m_fragmentShader);
// Check to see if the vertex shader compiled successfully.
glGetShaderiv(m_vertexShader, GL_COMPILE_STATUS, &status);
if(status != 1)
{
// If it did not compile then write the syntax error message out to a text file for review.
OutputShaderErrorMessage(m_vertexShader, vsFilename);
return false;
}
// Check to see if the fragment shader compiled successfully.
glGetShaderiv(m_fragmentShader, GL_COMPILE_STATUS, &status);
if(status != 1)
{
// If it did not compile then write the syntax error message out to a text file for review.
OutputShaderErrorMessage(m_fragmentShader, fsFilename);
return false;
}
// Create a shader program object.
m_shaderProgram = glCreateProgram();
// Attach the vertex and fragment shader to the program object.
glAttachShader(m_shaderProgram, m_vertexShader);
glAttachShader(m_shaderProgram, m_fragmentShader);
// Bind the shader input variables.
glBindAttribLocation(m_shaderProgram, 0, "inputPosition");
glBindAttribLocation(m_shaderProgram, 1, "inputNormal");
// Link the shader program.
glLinkProgram(m_shaderProgram);
// Check the status of the link.
glGetProgramiv(m_shaderProgram, GL_LINK_STATUS, &status);
if(status != 1)
{
// If it did not link then write the syntax error message out to a text file for review.
OutputLinkerErrorMessage(m_shaderProgram);
return false;
}
return true;
}