<basic.vert>

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
#version 430 core
 
layout(location = 0) in vec3 vertex_position;
layout(location = 1) in vec3 vertex_color;
layout(location = 2) in vec2 vertex_texture;
layout(location = 3) in vec3 vertex_normal;
 
out vec3 color;
out vec2 texCoord;
out vec3 normal;
out vec4 ambient;
out vec4 directional;
 
// Values that stay constant for the whole mesh.
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
 
uniform vec3 ambientColor;
uniform float ambientStrength;
 
uniform vec3 dirColor;
uniform float dirStrength;
uniform vec3 lightDirection;
 
void main()
{
    gl_Position = projection * view * model * vec4(vertex_position, 1.0f);
    color = vertex_color;
    texCoord = vertex_texture;
    normal = vertex_normal;
    // normal = mat3(transpose(inverse(model))) * vertex_normal; // Only needed if there's non-uniform scaling.
 
    // Calculate lighting.
    ambient = vec4(ambientColor, 1.0f) * ambientStrength;
 
    float dirFactor = max(dot(normalize(normal), normalize(lightDirection)), 0.0f);
    directional = vec4(dirColor, 1.0f) * dirStrength * dirFactor;
}
cs

 

<basic.frag>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#version 430 core
 
in vec3 color;
in vec2 texCoord;
in vec3 normal;
in vec4 ambient;
in vec4 directional;
out vec4 frag_color;
 
uniform sampler2D texture0;
 
void main()
{
    frag_color = texture(texture0, texCoord) * vec4(color, 1.0f) * (ambient + directional);
}
cs

 

<main.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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
#include <iostream>
#include <fstream>
 
// glew.h는 gl.h를 포함하기 전에 포함해야한다.
#include "GL/glew.h"
#include "GL/freeglut.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
 
using namespace std;
 
// 원하는 프레임 값
#define FPS 30
 
#define X_AXIS glm::vec3(1,0,0)
#define Y_AXIS glm::vec3(0,1,0)
#define Z_AXIS glm::vec3(0,0,1)
#define XY_AXIS glm::vec3(1,0.9,0)
#define YZ_AXIS glm::vec3(0,1,1)
#define XZ_AXIS glm::vec3(1,0,1)
#define XYZ_AXIS glm::vec3(1,1,1)
 
// Camera and transform variables.
glm::vec3 position, frontVec, worldUp, upVec, rightVec; // Set by function.
GLfloat pitch, yaw;
GLfloat moveSpeed = 0.1f;
GLfloat turnSpeed = 1.0f;
float rotAngle = 0.0f;
 
// Texture variables.
GLuint textureID;
GLint width, height, bitDepth;
GLuint gSampler;
 
// Mouse variables.
bool mouseFirst = true, mouseClicked = false;
int lastX, lastY;
 
// Light variables. Will eventually make OOP.
glm::vec3 ambientColor = glm::vec3(1.0f, 1.0f, 1.0f);
GLfloat ambientStrength = 0.1f;
 
glm::vec3 dirColor = glm::vec3(1.0f, 0.0f, 0.0f);
GLfloat dirStrength = 1.0f;
glm::vec3 lightDirection = glm::vec3(1.0f, 0.0f, 0.0f); // Actually more like origin.
 
 
GLuint programHandle;
GLuint vaoHandle;
GLuint modelID, viewID, projID;
glm::mat4 MVP, View, Projection;
GLuint setShader(const char* shaderType, const char* shaderName);
char* loadShaderAsString(std::string fileName);
 
float angle = 0.0f;
 
 
// Prototype
void timer(int);
void resetView();
void loadTexture(std::string filename);
void createBuffer();
void calculateView();
void keyDown(unsigned char key, int x, int y);
void keyDownSpecial(int key, int x, int y);
void mouseMove(int x, int y);
void mouseClick(int btn, int state, int x, int y);
void clean();
void CalcAverageNormals(GLshort* indices, unsigned indiceCount, GLfloat* vertices, unsigned verticeCount);
 
 
GLshort cube_indices[] = {
    // Front.
    012,
    230,
    // Right.
    456,
    674,
    // Back.
    8910,
    10118,
    // Left.
    121314,
    141512,
    // Top.
    161718,
    181916,
    // Bottom.
    202122,
    222320
};
 
 
GLfloat cube_vertices[] = {
    // Front.
    0.0f, 0.0f, 1.0f,        // 0.
    1.0f, 0.0f, 1.0f,        // 1.
    1.0f, 1.0f, 1.0f,        // 2.
    0.0f, 1.0f, 1.0f,        // 3.
    // Right.
    1.0f, 0.0f, 1.0f,        // 1. 4
    1.0f, 0.0f, 0.0f,        // 5. 5
    1.0f, 1.0f, 0.0f,        // 6. 6
    1.0f, 1.0f, 1.0f,        // 2. 7
    // Back.
    1.0f, 0.0f, 0.0f,        // 5. 8
    0.0f, 0.0f, 0.0f,        // 4. 9
    0.0f, 1.0f, 0.0f,        // 7. 10
    1.0f, 1.0f, 0.0f,        // 6. 11
    // Left.
    0.0f, 0.0f, 0.0f,        // 4. 12
    0.0f, 0.0f, 1.0f,        // 0. 13
    0.0f, 1.0f, 1.0f,        // 3. 14
    0.0f, 1.0f, 0.0f,        // 7. 15
    // Top.
    0.0f, 1.0f, 0.0f,        // 7. 16
    0.0f, 1.0f, 1.0f,        // 3. 17
    1.0f, 1.0f, 1.0f,        // 2. 18
    1.0f, 1.0f, 0.0f,        // 6. 19
    // Bottom.
    0.0f, 0.0f, 0.0f,        // 4. 20
    1.0f, 0.0f, 0.0f,        // 5. 21
    1.0f, 0.0f, 1.0f,        // 1. 22
    0.0f, 0.0f, 1.0f        // 0. 23
};
 
GLfloat cube_uvs[] = {
    // Front.
    0.0f, 0.0f,     // 0.
    1.0f, 0.0f,     // 1.
    1.0f, 1.0f,     // 2.
    0.0f, 1.0f,        // 3.
    // Right.
    0.0f, 0.0f,     // 1.
    1.0f, 0.0f,     // 5.
    1.0f, 1.0f,     // 6.
    0.0f, 1.0f,        // 2.
    // Back.
    0.0f, 0.0f,     // 5.
    1.0f, 0.0f,     // 4.
    1.0f, 1.0f,        // 7.
    0.0f, 1.0f,        // 6.
    // Left.
    0.0f, 0.0f,        // 4.
    1.0f, 0.0f,        // 0.
    1.0f, 1.0f,        // 3.
    0.0f, 1.0f,        // 7.
    // Top.
    0.0f, 0.0f,        // 7.
    1.0f, 0.0f,        // 3.
    1.0f, 1.0f,        // 2.
    0.0f, 1.0f,        // 6.
    // Bottom.
    0.0f, 0.0f,        // 4.
    1.0f, 0.0f,        // 5.
    1.0f, 1.0f,        // 1.
    0.0f, 1.0f        // 0.
};
 
GLfloat colors[] = {
    // Front.
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    // Right.
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    // Back.
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    // Left.
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    // Top.
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    // Bottom.
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f
};
 
GLfloat cube_normals[72= { 0, };
 
void init()
{
 
    // 1. 쉐이더 오브젝트를 생성한다.
    GLuint vertShader = setShader("vertex""basic.vert");
    GLuint fragShader = setShader("fragment""basic.frag");
 
    // 오브젝트 컴파일이 끝나면 OpenGL pipeline에 컴파일이 끝난 쉐이더를 등록 혹은 설치해야한다.
 
    // 1. 먼저 Program object를 생성한다.
    // 빈 프로그램 생성
    programHandle = glCreateProgram();
    if (0 == programHandle)
    {
        fprintf(stderr, "Error creating program object.\n");
        exit(1);
    }
 
    // 2. 쉐이더들을 프로그램에 붙인다.
    glAttachShader(programHandle, vertShader);
    glAttachShader(programHandle, fragShader);
 
    // 3. 프로그램을 링크한다. 연결
    glLinkProgram(programHandle);
 
    // 4. 링크 상태 확인
    GLint status;
    glGetProgramiv(programHandle, GL_LINK_STATUS, &status);
    if (GL_FALSE == status) {
        fprintf(stderr, "Failed to link shader program!\n");
        GLint logLen;
        glGetProgramiv(programHandle, GL_INFO_LOG_LENGTH,
            &logLen);
        if (logLen > 0)
        {
            char* log = (char*)malloc(logLen);
            GLsizei written;
            glGetProgramInfoLog(programHandle, logLen,
                &written, log);
            fprintf(stderr, "Program log: \n%s", log);
            free(log);
        }
    }
    // 5. 만약 링크가 성공했다면 프로그램을 OpenGL pipeline에 설치 한다.
    else
    {
        glUseProgram(programHandle);
    }
 
    // uniform 사용
    modelID = glGetUniformLocation(programHandle, "model");
    viewID = glGetUniformLocation(programHandle, "view");
    projID = glGetUniformLocation(programHandle, "projection");
    gSampler = glGetUniformLocation(programHandle, "texture0");
    assert(gSampler != 0xFFFFFFFF);
 
    glUniform1i(gSampler, 0);
 
    // Setting ambient light.
    glUniform3f(glGetUniformLocation(programHandle, "ambientColor"), ambientColor.x, ambientColor.y, ambientColor.z);
    glUniform1f(glGetUniformLocation(programHandle, "ambientStrength"), ambientStrength);
 
    // Setting directional light.
    glUniform3f(glGetUniformLocation(programHandle, "lightDirection"), lightDirection.x, lightDirection.y, lightDirection.z);
    glUniform3f(glGetUniformLocation(programHandle, "dirColor"), dirColor.x, dirColor.y, dirColor.z);
    glUniform1f(glGetUniformLocation(programHandle, "dirStrength"), dirStrength);
 
    ////loadTexture("Media/spheremap.png");
    //pTexture = new Texture(GL_TEXTURE_2D, "Media/die.png", GL_RGB);
    //pTexture->Bind(GL_TEXTURE0);
    //if (!pTexture->Load()) {
    //    exit(0);
    //}
 
 
    resetView();
 
    createBuffer();
    loadTexture("Media/die.png");
 
 
 
    // Enable depth testing and face culling.
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glFrontFace(GL_CCW);
    glCullFace(GL_BACK);
 
    // 타이머 스타트
    timer(0);
}
//---------------------------------------------------------------------
//
// transformModel
//
void transformObject(float scale, glm::vec3 rotationAxis, float rotationAngle, glm::vec3 translation) {
    glm::mat4 Model;
    Model = glm::mat4(1.0f);
    Model = glm::translate(Model, translation);
    Model = glm::rotate(Model, glm::radians(rotationAngle), rotationAxis);
    Model = glm::scale(Model, glm::vec3(scale));
    MVP = Projection * View * Model;
 
    calculateView();
    glUniformMatrix4fv(modelID, 1, GL_FALSE, &Model[0][0]);
    glUniformMatrix4fv(viewID, 1, GL_FALSE, &View[0][0]);
    glUniformMatrix4fv(projID, 1, GL_FALSE, &Projection[0][0]);
}
 
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 
    glBindVertexArray(vaoHandle);
    // Update the projection or view if perspective.
    Projection = glm::perspective(glm::radians(60.0f), 4.0f / 3.0f, 0.1f, 100.0f);
 
    transformObject(1.0f, Y_AXIS, rotAngle = -45, glm::vec3(0.0f, 0.0f, 0.0f));
    // 3번째 인자 - 버택스의 수
    //glDrawArrays(GL_QUADS, 0, 4);
 
    glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, 0);
 
    glutSwapBuffers(); // Now for a potentially smoother render.
}
 
void timer(int) {
    glutPostRedisplay();
    glutTimerFunc(1000 / FPS, timer, 0);
}
 
void resetView()
{
    position = glm::vec3(0.0f, 0.0f, 5.0f);
    frontVec = glm::vec3(0.0f, 0.0f, -1.0f);
    worldUp = glm::vec3(010);
    pitch = 0.0f;
    yaw = -90.0f;
}
 
void loadTexture(std::string filename)
{
    stbi_set_flip_vertically_on_load(true);
 
    //filename.c_str() to convert to constant char*
    //bitDepth:how many bit perpixel
    //unsigned char* image = stbi_load("Media/spheremap.png", &width, &height, &bitDepth, 0);
    unsigned char* image = stbi_load(filename.c_str(), &width, &height, &bitDepth, 0);
    if (!image) {
        cout << "Unable to load file!" << stbi_failure_reason() << endl;
 
        exit(0);
        // Could add a return too if you modify init.
    }
 
 
    //!Generate a handler for texture object
    glGenTextures(1&textureID);
 
 
    //!This tells openGL if the texture object is 1D, 2D, 3D, etc..
    glBindTexture(GL_TEXTURE_2D, textureID);
 
    /// @note: all texture objects cannot be available to the shader.
    /// That's why we have texture units sitting between texture objects and shaders.
    /// Then shaders samples from the texture unit.
    /// So between draw calls, we can point to a different texture unit.
    int textureUnits = 0;
    glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &textureUnits);
    cout << "The number of my GPU texture units: " << textureUnits;
 
    //! Load the texture object from CPU to GPU
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width,
        height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
 
    //! Configure the texture state
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
 
 
    //!Activate a texture unit!
    glActiveTexture(GL_TEXTURE0);
 
    //!Set the index of the texture unit into the sampler
    glUniform1i(glGetUniformLocation(programHandle, "texture0"), 0);
 
    glGenerateMipmap(GL_TEXTURE_2D);
 
    // Clean up. But we don't want to unbind the texture or we cannot use it.
    stbi_image_free(image);
}
 
void createBuffer()
{
 
    // 버퍼 오브젝트롤 설정하였기 때문에, 이것들을 vertex array obejct(VAO) 에 묶는다.
    // VAO 생성한다. (전역변수로 vaoHandle 필요)
    // Create and set-up the vertex array object
    glGenVertexArrays(1&vaoHandle);
    glBindVertexArray(vaoHandle);
 
 
    // 인덱스용 버퍼 오브젝트
    GLuint indexBufferObjec;
    glGenBuffers(1&indexBufferObjec);
    // GL_ELEMENT_ARRAY_BUFFER를 사용한다.
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObjec);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cube_indices), cube_indices, GL_STATIC_DRAW);
 
 
    // 포지션과 색상을 저장하기 위한 버퍼를 생성한다.
    // Create the buffer objects
    GLuint vboHandles[4];
    // 버퍼 3개생성.
    glGenBuffers(4, vboHandles);
    GLuint positionBufferHandle = vboHandles[0];
    GLuint colorBufferHandle = vboHandles[1];
    GLuint uvsBufferHandle = vboHandles[2];
    GLuint normals_vbo = vboHandles[3];
 
 
    // vertex
    glBindBuffer(GL_ARRAY_BUFFER, positionBufferHandle);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertices), cube_vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(03, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL);
    glEnableVertexAttribArray(0); // for Vertex position
 
    // Populate the color buffer
    // 색상 버퍼를 바인드한다.
    glBindBuffer(GL_ARRAY_BUFFER, colorBufferHandle);
    glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);
    glVertexAttribPointer(13, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL);
    glEnableVertexAttribArray(1); // for Vertex color
 
    // Now for the UV/ST values.
    glBindBuffer(GL_ARRAY_BUFFER, uvsBufferHandle);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_uvs), cube_uvs, GL_STATIC_DRAW);
    glVertexAttribPointer(22, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL);
    glEnableVertexAttribArray(2);
 
 
    CalcAverageNormals(cube_indices, 36, cube_vertices, 72);
    // Uncomment for DirectionalLight example.
    glBindBuffer(GL_ARRAY_BUFFER, normals_vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_normals), cube_normals, GL_STATIC_DRAW);
    glVertexAttribPointer(33, GL_FLOAT, GL_FALSE, 00);
    glEnableVertexAttribArray(3);
 
 
 
 
}
 
void calculateView()
{
    frontVec.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
    frontVec.y = sin(glm::radians(pitch));
    frontVec.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
    frontVec = glm::normalize(frontVec);
    rightVec = glm::normalize(glm::cross(frontVec, worldUp));
    upVec = glm::normalize(glm::cross(rightVec, frontVec));
 
    View = glm::lookAt(position, position + frontVec, upVec);
}
 
void keyDown(unsigned char key, int x, int y)
{
    switch (key)
    {
        case 'w':
            position += frontVec * moveSpeed;
            break;
        case 's':
            position -= frontVec * moveSpeed;
            break;
        case 'a':
            position -= rightVec * moveSpeed;
            break;
        case 'd':
            position += rightVec * moveSpeed;
            break;
        case ' ':
            resetView();
            break;
    }
}
 
void keyDownSpecial(int key, int x, int y)
{
    switch (key)
    {
        case GLUT_KEY_UP:
            pitch -= turnSpeed;
            break;
        case GLUT_KEY_DOWN:
            pitch += turnSpeed;
            break;
        case GLUT_KEY_LEFT:
            yaw += turnSpeed;
            break;
        case GLUT_KEY_RIGHT:
            yaw -= turnSpeed;
            break;
    }
}
 
void mouseMove(int x, int y)
{
    //cout << "Mouse pos: " << x << "," << y << endl;
    if (mouseClicked)
    {
        pitch -= (GLfloat)((y - lastY) * 0.1);
        yaw += (GLfloat)((x - lastX) * 0.1);
        lastY = y;
        lastX = x;
    }
}
 
void mouseClick(int btn, int state, int x, int y)
{
    /*cout << "Clicked: " << (btn == 0 ? "left " : "right ") << (state == 0 ? "down " : "up ") <<
        "at " << x << "," << y << endl;*/
    if (state == 0)
    {
        lastX = x;
        lastY = y;
        mouseClicked = true;
        glutSetCursor(GLUT_CURSOR_NONE);
        cout << "Mouse clicked." << endl;
    }
    else
    {
        mouseClicked = false;
        glutSetCursor(GLUT_CURSOR_INHERIT);
        cout << "Mouse released." << endl;
    }
}
 
void clean()
{
    cout << "Cleaning up!" << endl;
    glDeleteTextures(1&textureID);
}
 
 
int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
 
    //윈도우 사이즈 변경
    glutInitWindowSize(1024720);
 
    // top-left corner 초기 포지션으로 초기화
    glutInitWindowPosition(00);
 
    // 윈도우창 생성
    glutCreateWindow("Dice");
 
 
    // glew를 초기화 해준다. opengl을 사용하기위해서
    GLenum err = glewInit();
    // glewInit()을 함으로써 모든 OpenGL라이브러리를 찾고 모든 사용가능한 함수포인터를 초기화한다.
 
    if (GLEW_OK != err)
    {
        fprintf(stderr, "Error initializing GLEW: %s\n",
            glewGetErrorString(err));
    }
 
    // to compile shader
    init();
    glutDisplayFunc(display);
 
    glutKeyboardFunc(keyDown);
    glutSpecialFunc(keyDownSpecial);
    glutMouseFunc(mouseClick);
    //glutPassiveMotionFunc(mouseMove); // or...
    glutMotionFunc(mouseMove); // Requires click to register.
    atexit(clean); // This GLUT function calls specified function before terminating program. Useful!
 
    // glut의 이벤트 프로세싱 loop을 시작.
    glutMainLoop();
 
    return 0;
}
 
 
 
GLuint setShader(const char* shaderType, const char* shaderName)
{
    GLuint shaderObj;
    if (strcmp(shaderType, "vertex"== 0)
    {
        shaderObj = glCreateShader(GL_VERTEX_SHADER);
    }
    else if (strcmp(shaderType, "fragment"== 0)
    {
        shaderObj = glCreateShader(GL_FRAGMENT_SHADER);
    }
 
 
    if (0 == shaderObj)
    {
        fprintf(stderr, "Error creating shader obj.\n");
        exit(1);
    }
 
 
    // 2. 쉐이더 소스코드를 쉐이더 오브젝트로 복사한다.
    const GLchar* shaderCode = loadShaderAsString(shaderName);
    // 소스 배열에 여러 소스코드를 담을 수 있다.
    // 배열에 소스코드를 담은후.
    const GLchar* codeArray[] = { shaderCode };
    // vertShader object로 codeArray를 복사한다.
    // 첫번째 인자는 쉐이더 오브젝트, 두번째 인자는 소스코드의 총 개수 여기서는 shaderCode 한개만 들어가서 1
    // 세번째 인자는 코드를 넣은 배열, 네번째 인자는 각 소스코드의 길이를 넣은 int배열이다 여기서는 null character를 넣어서 자동으로 확인되기때무에 NULL을 넣었다.
    glShaderSource(shaderObj, 1, codeArray, NULL);
 
    // 3. 쉐이더를 컴파일 한다.
    glCompileShader(shaderObj);
 
 
    // 4. 컴파일 완료 확인.
    GLint result;
    glGetShaderiv(shaderObj, GL_COMPILE_STATUS, &result);
    if (GL_FALSE == result)
    {
        fprintf(stderr, "shader compilation failed!\n");
        GLint logLen;
        glGetShaderiv(shaderObj, GL_INFO_LOG_LENGTH, &logLen);
        if (logLen > 0)
        {
            char* log = (char*)malloc(logLen);
            GLsizei written;
            glGetShaderInfoLog(shaderObj, logLen, &written, log);
            fprintf(stderr, "Shader log:\n%s", log);
            free(log);
        }
    }
 
    return shaderObj;
}
 
char* loadShaderAsString(std::string fileName)
{
    // Initialize input stream.
    std::ifstream inFile(fileName.c_str(), std::ios::binary);
 
    // Determine shader file length and reserve space to read it in.
    inFile.seekg(0std::ios::end);
    int fileLength = inFile.tellg();
    char* fileContent = (char*)malloc((fileLength + 1* sizeof(char));
 
    // Read in shader file, set last character to NUL, close input stream.
    inFile.seekg(0std::ios::beg);
    inFile.read(fileContent, fileLength);
    fileContent[fileLength] = '\0';
    inFile.close();
 
    return fileContent;
}
 
void CalcAverageNormals(GLshort* indices, unsigned indiceCount, GLfloat* vertices, unsigned verticeCount)
{
    // Popular shape_normals so we can use [].
    /*for (int i = 0; i < verticeCount; i++)
        shape_normals.push_back(0);
    shape_normals.shrink_to_fit();*/
    // Calculate the normals of each triangle first.
    for (unsigned i = 0; i < indiceCount; i += 3)
    {
        unsigned in0 = indices[i] * 3;
        unsigned in1 = indices[i + 1* 3;
        unsigned in2 = indices[i + 2* 3;
        glm::vec3 v1(vertices[in1] - vertices[in0], vertices[in1 + 1- vertices[in0 + 1], vertices[in1 + 2- vertices[in0 + 2]);
        glm::vec3 v2(vertices[in2] - vertices[in0], vertices[in2 + 1- vertices[in0 + 1], vertices[in2 + 2- vertices[in0 + 2]);
        glm::vec3 normal = glm::cross(v1, v2);
        normal = glm::normalize(normal); // Finally becomes a unit vector.
 
        // Now populate the normal values for each vertex of the triangle.
        cube_normals[in0] += normal.x;    cube_normals[in0 + 1+= normal.y;    cube_normals[in0 + 2+= normal.z;
        cube_normals[in1] += normal.x;    cube_normals[in1 + 1+= normal.y;    cube_normals[in1 + 2+= normal.z;
        cube_normals[in2] += normal.x;    cube_normals[in2 + 1+= normal.y;    cube_normals[in2 + 2+= normal.z;
    }
    // Normalize each of the new normal vectors.
    for (unsigned i = 0; i < 72; i += 3)
    {
        glm::vec3 vec(cube_normals[i], cube_normals[i + 1], cube_normals[i + 2]);
        vec = glm::normalize(vec);
        cube_normals[i] = vec.x; cube_normals[i + 1= vec.y; cube_normals[i + 2= vec.z;
    }
}
 
cs

 

<결과>

<소스코드>

https://github.com/woonhak-kong/OpenGL_Practice16_directional_light

'OpenGL' 카테고리의 다른 글

opengl 주사위 만들기  (0) 2021.11.16
Opengl Texture  (0) 2021.11.07
opengl dynamic polygon  (0) 2021.10.16
opengl 카메라 이동  (0) 2021.10.02
opengl perspective  (0) 2021.10.02

+ Recent posts