link : http://www.opengl-tutorial.org/kr/intermediate-tutorials/tutorial-16-shadow-mapping/
Tutorial 15에서는 정적 조명을 포함하는 라이트 맵을 만드는 법을 배웠다.
매우 멋진 그림자를 생성하지만 애니메이션 모델은 처리하지 않는다.
그림자 맵은 현재 (2016년 기준) 동적 그림자를 만드는 방법이다.
그들에 대한 좋은 점은 일하기가 상당히 쉽다는 것이다. 나쁜 점은 제대로 작동하기가 대단히 어렵다는 것이다.
이 튜토리얼에서는 먼저 기본 알고리즘을 소개하고, 단점을 확인한 다음 더 나은 결과를 얻기 위해
몇가지 기술을 구현한다.
Basic shadowmap
기본 그림자 맵 알고리즘은 두 단계로 구성된다. 먼저, 장면은 빛의 관점에서 렌더링된다. 오직 각 단편의 깊이만 계산된다.
다음으로, 씬은 평소와 같이 렌더링되지만 현재의 fragment가 그림자 안에 있다는 것을 보기 위한 추가 테스트가 있다.
"being in the shadow" 테스트는 아주 간단하다. 현재 샘플이 같은 지점의 그림자 맵보다 빛에서 멀어지면
장면에서 빛에 더 가까운 물체가 들어있음으 ㄹ의미한다. 즉, 현재 조각이 그림자에 있다는 것이다.
Rendering the shadow map
이 튜토리얼에서는 지향성 조명, 즉 모든 광선이 평행으로 간주 될 수 있는 매우 먼 조명을 고려한다.
이와 같이 그림자 맵 렌더링은 직교 투영 행렬로 수행된다. 정사영 행렬은 일반적인 투시 투영 행렬과 비슷하지만,
원근감을 고려하지 않는다는 점을 제외하고는 카메라가 원거리에 있는지 또는 근거리에 있는지에 따라 객체가 동일하게 보인다.
Setting up the rendertarget and the MVP matrix
튜토리얼 14부터는 나중에 쉐이더에서 장면에 액세스하기 위해 장면을 텍스처로 렌더링하는 방법을 알고 있다.
여기에서는 그림자 맵을 포함하기 위해 1024x1024 16비트 깊이 텍스처를 사용한다.
16비트는 일반적으로 그림자 맵에 충분하다. 이 값으로 자유롭게 실험해보아라.
우리는 나중에 깊이 샘플링을 해야하기 때문에 깊이 렌더 버퍼가 아니라 깊이 텍스처를 사용한다.
// The framebuffer, which regroups 0, 1, or more textures, and 0 or 1 depth buffer.
GLuint FramebufferName = 0;
glGenFramebuffers(1, &FramebufferName);
glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);
// Depth texture. Slower than a depth buffer, but you can sample it later in your shader
GLuint depthTexture;
glGenTextures(1, &depthTexture);
glBindTexture(GL_TEXTURE_2D, depthTexture);
glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT16, 1024, 1024, 0,GL_DEPTH_COMPONENT, GL_FLOAT, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0);
glDrawBuffer(GL_NONE); // No color buffer is drawn to.
// Always check that our framebuffer is ok
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
return false;
라이트의 관점에서 장면을 렌더링하는데 사용되는 MVP행렬은 다음과 같이 계산된다.
1) 투영 행렬은 각각 X,Y,Z축의 축 정렬 상자 (-10,10), (-10,10), (-10,20)에 있는 모든 것을 포함하는 직교 행렬이다.
이 값들은 우리의 전체 *visible *scene이 항상 보이도록 만들어진다.
자세한 내용은 Going Further 섹션을 참조해라.
2) View matrix는 카메라 공간에서 빛의 방향이 -Z라고 생각하는 세계를 회전시킨다.
3) 모델 행렬은 원하는 것이다.
glm::vec3 lightInvDir = glm::vec3(0.5f,2,2);
// Compute the MVP matrix from the light's point of view
glm::mat4 depthProjectionMatrix = glm::ortho<float>(-10,10,-10,10,-10,20);
glm::mat4 depthViewMatrix = glm::lookAt(lightInvDir, glm::vec3(0,0,0), glm::vec3(0,1,0));
glm::mat4 depthModelMatrix = glm::mat4(1.0);
glm::mat4 depthMVP = depthProjectionMatrix * depthViewMatrix * depthModelMatrix;
// Send our transformation to the currently bound shader,
// in the "MVP" uniform
glUniformMatrix4fv(depthMatrixID, 1, GL_FALSE, &depthMVP[0][0])
The shaders
이 pass 중에 사용된 쉐이더는 매우 간단하다. vertex shader는 단순히 동질적인 좌표로 vertex의 위치를 계산하는
pass-through shader이다.
#version 330 core
// Input vertex data, different for all executions of this shader.
layout(location = 0) in vec3 vertexPosition_modelspace;
// Values that stay constant for the whole mesh.
uniform mat4 depthMVP;
void main(){
gl_Position = depthMVP * vec4(vertexPosition_modelspace,1);
}
The fragment shader is just as simple : it simply writes the depth of the fragment at location 0 (i.e. in our depth texture).
#version 330 core
// Ouput data
layout(location = 0) out float fragmentdepth;
void main(){
// Not really needed, OpenGL does it anyway
fragmentdepth = gl_FragCoord.z;
}
그림자 맵 렌더링은 일반적으로 깊이와 색상 대신 낮은 정밀도 깊이만 기록도기 때문에 일반적으로 일반 렌더링보다
두 배 이상 빠르다. 메모리 대역폭은 종종 GPU에서 가장 큰 성능 문제이다.
Using the shadow map
Basic shader
다시 usual shader로 돌아가자. 우리가 계산하는 각 fragment마다 그림자 맵 뒤에 있는지 여부를 테스트해야한다.
이를 위해, 우리는 shadowmap을 생성할 때 사용한 것과 동일한 공간에서 현재 fragment의 위치를 계산해야한다.
그래서 우리는 usual MVP 행렬로 한 번 변환하고, 또 다른 시간은 depthMVP 행렬로 변환해야한다.
여기에는 약간의 트릭이 있다. vertex의 위치에 depthMVP를 곱하면 [-1,1]에 있는 균일한 좌표를 얻을 수 있다.
텍스처 샘플링은 [0,1]에서 수행되어야한다.
예를 들어, 화면 중앙의 단편은 동 질적 좌표로 (0,0)에 있다. 하지만 텍스처의 중간을 샘플링해야하므로 UV는 (0.5, 0.5)이어야 한다.
이것은 fragment shader에서 패치 좌표를 직접 미세 조정하면 해결할 수 있다.
그러나 균직 좌표에 다음 좌표를 곱하는 것이 더 효율적이다. 좌표를 2로 나누기만 하면 된다.
: (대각선 : [-1, 1] -> [-0.5, 0.5]) 그리고 이들을 변환한다 (the lower row : [-0.5, 0.5] -> [0,1])
glm::mat4 biasMatrix(
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0
);
glm::mat4 depthBiasMVP = biasMatrix*depthMVP;
이제 vertex shader를 작성할 수 있다. 이전과 같지만 1대신 2의 자리를 출력한다.
1) gl_Position은 현재 카메라에서 본 정점의 위치이다.
2) ShadowCoord는 마지막 카메라에서 본 정점의 위치이다.
// Output position of the vertex, in clip space : MVP * position
gl_Position = MVP * vec4(vertexPosition_modelspace,1);
// Same, but with the light's view matrix
ShadowCoord = DepthBiasMVP * vec4(vertexPosition_modelspace,1);
fragment shader는 매우 간단하다.
1) texture (shadowMap, ShadowCoord.xy) .z는 빛과 가장 가까운 occluder 사이의 거리이다.
2) ShadowCoord.z는 빛과 현재 조각 사이의 거리이다.
현재 조각이 가장 가까운 occluder보다 멀다면, 이는 우리가 그림자에 있음을 의미한다.
float visibility = 1.0;
if ( texture( shadowMap, ShadowCoord.xy ).z < ShadowCoord.z){
visibility = 0.5;
}
이 지식을 사용해 음영을 수정하면 된다. 물론 주변 색은 변경되지 않는다.
color =
// Ambient : simulates indirect lighting
MaterialAmbientColor +
// Diffuse : "color" of the object
visibility * MaterialDiffuseColor * LightColor * LightPower * cosTheta+
// Specular : reflective highlight, like a mirror
visibility * MaterialSpecularColor * LightColor * LightPower * pow(cosAlpha,5);
Problems
Shadow ance
가장 명백한 문제는 shadow acne이다.
이 현상은 간단한 이미지로 쉽게 설명된다.
이 문제에 대한 일반적인 "fix"는 오류 마진을 추가하는 것이다.
즉, 현재 조각의 깊이가 실제로는 lightmap 값에서 멀리 떨어져있는 경우에만 음영 처리한다. bias(편향성)을 추가해 이렇게 한다.
float bias = 0.005;
float visibility = 1.0;
if ( texture( shadowMap, ShadowCoord.xy ).z < ShadowCoord.z-bias){
visibility = 0.5;
}
그 결과는 훨씬 좋아졌다.
그러나 우리가 편견때문에 지상과 벽 사이의 인공물이 더 나빠졌다는 것을 알 수 있다.
게다가 0.005의 바이어스는 너무 많이 보이지만 곡면에는 충분하지 않다.
일부 인공물은 원통과 구면에 남아있따.
일반적인 접근법은 기울기에 따라 bias를 수정하는 것이다.
float bias = 0.005*tan(acos(cosTheta)); // cosTheta is dot( n,l ), clamped between 0 and 1
bias = clamp(bias, 0,0.01);
굴곡된 표면에서도 shadow acne이 사라졌다.
기하학에 따라 작동하지 않을 수도 있는 또 다른 트릭은 그림자 맵에서 뒷면만 렌더링하는 것이다.
이것은 우리에게 두꺼운 벽을 가진 특별한 기하학을 강요하지만 적어도 여드름은 그림자에 있는 표면에 있게된다.
그림자 맵을 렌더링할 때 앞ㅈ쪽 삼각형을 cull해라.
// We don't use bias in the shader, but instead we draw back faces,
// which are already separated from the front faces by a small distance
// (if your geometry is made this way)
glCullFace(GL_FRONT); // Cull front-facing triangles -> draw only back-facing triangles
그리고 scene을 렌더링 할 때 정상 렌더링을 해라. (backface culling)
glCullFace(GL_BACK); // Cull back-facing triangles -> draw only front-facing triangles
이 방법은 bias외에도 코드에서 사용된다.
Peter Panning
더 이상 shadow acne는 없다. 하지만 우리는 여전히 잘못된 음영을 가지고 있다. (벽이 날아다니는 것처럼 보인다)
실제로 bias를 추가하는 것은 효과가 나빴다.
이 방법은 매우 간단하다 : 얇은 형상만 피해라. 여기에는 두 가지 이점이 있다.
1) Peter Panning을 해결한다. 기하학이 bias보다 더 깊으므로 모든 것이 설정되어 있다.
2) 라이트 맵을 렌더링 할 때 backface culling을 켤 수 있다. 벽의 폴리곤이 빛을 향하게되어 배면 컬링으로 렌더링되지
않을 다른면을 가릴 수 있기 때문이다. 단점은 렌더링 할 삼각형이 더 많다는 것이다. (프레임당 2번)
Aliasing
이 두 가지 트릭을 사용하더라도 그림자 테두리에 여전히 aliasing이 있음을 알 수 있다.
즉, 한 픽셀은 흰색이고 그 다음 픽셀은 매끄러운 전환없이 검은색이다.
PCF
이를 개선하는 가장 쉬운 방법은 그림자 맵의 샘플러 유형을 sampler2DShadow로 변경하는 것이다.
결과는 그림자 맵을 한 번 샘플링 할 때 실제로 하드웨어가 인접한 texel을 샘플링하고,
모두에 대한 비교를 수행하고 비교 결과의 bilinear 필터링을 사용해 [0,1]에 float를 반환한다.
예를 들어, 0.5는 2개의 샘플이 그림자에 있고 2개의 샘플이 빛에 있음을 의미한다.
필터링된 깊이 맵의 단일 샘플링과 동일하지 않다. 비교는 항상 true 또는 false를 반환한다.
PCF는 4 "true or false"의 보간법을 제공한다.
보시다시피 그림자 테두리는 부드럽지만 그림자 맵의 texel은 계속 볼 수 있다.
Poisson Sampling
이것을 다루기 쉬운 방법은 그림자 맵을 한번이 아닌 N번 샘플하는 것이다.
PCF와 함께 사용하면 N이 작더라도 아주 좋은 결과를 얻을 수 있다.
for (int i=0;i<4;i++){
if ( texture( shadowMap, ShadowCoord.xy + poissonDisk[i]/700.0 ).z < ShadowCoord.z-bias ){
visibility-=0.2;
}
}
poissonDisk is a constant array defines for instance as follows :
vec2 poissonDisk[4] = vec2[](
vec2( -0.94201624, -0.39906216 ),
vec2( 0.94558609, -0.76890725 ),
vec2( -0.094184101, -0.92938870 ),
vec2( 0.34495938, 0.29387760 )
);
이렇게하면 얼마나 많은 그림자 맵 샘플이 통과할 것인가에 따라 생성된 조각이 다소 어두워진다.
Stratified Poisson Sampling
각 픽셀에 대해 다른 샘플을 선택해 이 밴딩을 제거 할 수 있다. 두 가지 주요 방법이 있다. (계층화된 포이즌 또는 회전된 포이즌)
계층화된 것은 다른 샘플을 선택한다. 회전은 항상 동일하지만 임의의 회전을 사용하므로 모양이 달라진다.
이 튜토리얼에서는 계층화된 버전만 설명한다.
이전 버전과의 유일한 차이점은 poissonDisk에 임의 색인을 사용해 색인을 생성한다는 것이다.
for (int i=0;i<4;i++){
int index = // A random number between 0 and 15, different for each pixel (and each i !)
visibility -= 0.2*(1.0-texture( shadowMap, vec3(ShadowCoord.xy + poissonDisk[index]/700.0, (ShadowCoord.z-bias)/ShadowCoord.w) ));
}
We can generate a random number with a code like this, which returns a random number in [0,1[ :
float dot_product = dot(seed4, vec4(12.9898,78.233,45.164,94.673));
return fract(sin(dot_product) * 43758.5453);
우리의 경우, seed4는 i(4개의 다른 위치에서 샘플링 할 수 있도록)와 다른 것의 조합이 될 것이다.
gl_FragCoord(화면상의 픽셀의 위치)나 Position_worldspace를 사용할 수 있다.
// - A random sample, based on the pixel's screen location.
// No banding, but the shadow moves with the camera, which looks weird.
int index = int(16.0*random(gl_FragCoord.xyy, i))%16;
// - A random sample, based on the pixel's position in world space.
// The position is rounded to the millimeter to avoid too much aliasing
//int index = int(16.0*random(floor(Position_worldspace.xyz*1000.0), i))%16;
이렇게하면 시각적 노이즈를 희생하면서 위의 그림과 같은 패턴이 사라진다.
Going further
이러한 모든 트릭을 사용하더라도 그림자가 개선 될 수 있는 많은 방법이 있다. 다음은 가장 일반적인 것이다.
Early bailing
각 단편에 대해 16개의 샘플을 얻는 대신 4개의 먼 샘플을 취한다. 그들 모두가 빛이나 그림자 속에 있다면,
16개의 샘플 모두가 같은 결과를 가져올 것이라고 생각할 수 있다. 일부가 다른 경우, 아마도 그림자 경계에 있으므로
16개의 샘플이 필요하다.
Spot lights
spotlight를 다루는 것은 거의 변화가 없다. 가장 확실한 방법은 orthographic projection matrix를 원근 투영 행렬로 변경하는 것이다.
glm::vec3 lightPos(5, 20, 20);
glm::mat4 depthProjectionMatrix = glm::perspective<float>(glm::radians(45.0f), 1.0f, 2.0f, 50.0f);
glm::mat4 depthViewMatrix = glm::lookAt(lightPos, lightPos-lightInvDir, glm::vec3(0,1,0));
똑같은 것이지만, 정사각형 절두체 대신에 원근 절두체를 가지고 있다.
perspective-dive를 설명하기 위해 texture2Dproj를 사용한다 (튜토리얼 4 참조)
두번째 단계는 쉐이더의 관점을 고려하는 것이다.
GLSL에서 이 작업을 수행하는 두 가지 방법이 있다. 두 번째 메서드는 내장된 textureProj 함수를 사용하지만
두 메서드 모두 정확히 동일한 결과를 생성한다.
if ( texture( shadowMap, (ShadowCoord.xy/ShadowCoord.w) ).z < (ShadowCoord.z-bias)/ShadowCoord.w )
if ( textureProj( shadowMap, ShadowCoord.xyw ).z < (ShadowCoord.z-bias)/ShadowCoord.w )
Combination of serveral lights
알고리즘은 여러 라이트를 처리하지만 그림자 맵을 생성하려면 각 라이트가 장면을 추가로 렌더링해야한다.
그림자를 적용할 때 엄청난 양의 메모리가 필요하며 매우 빠르게 대역폭을 제한할 수 있다.
Exponential shadow maps
지수 그림자 맵은 그림자에 있지만 밝은면 근처의 조각이 실제로 "somewhere in the middle"것으로 가정해 앨리어싱을
제한하려고 시도하낟. 이것은 bias와 관련이 있다. 단, 테스트가 더 이상 바이너리가 아니라는 점을 제외하면 점등 표면까지의
거리가 멀어질수록 조각이 어두워지고 어두워진다.
이것은 부정행위이며 분명히 두 개체가 겹칠 때 인공물이 나타날 수 있다.
Light-space perspective Shadow Maps
LiSPSM은 카메라 근처의 정밀도를 높이기 위해 조명 투영행렬을 조정한다. 이것은 "dueling frustra"의 경우 특히 중요하다.
방향을 바라보았지만 반대쪽 방향의 스포트라이트가 보인다. 빛 근처, 즉 사용자와 멀리 떨어져있는 그림자 맵 정밀도가 많으며
카메라 근처에서 가장 낮은 해상도를 필요로 한다.
그러나 LiSPM은 구현하기 까다롭다. 구현에 대한 자세한 내용은 참고 자료를 참조해라.
Cascaded shadow maps
CSM은 LiSPSM과 완전히 똑같은 문제를 다루지만 다른 방식으로 다루고 있다.
view frustum의 여러 부분에 대해 (2-4) 개의 표준 쉐도우 맵을 사용한다.
첫 번째 미터는 첫 번째 미터를 다루므로 아주 작은 영역에 대해 훌륭한 해상도를 얻을 수 있다.
다음 그림자 맵은 멀리있는 객체를 처리한다. 마지막 그림자 맵은 장면의 큰 부분을 다루지만 원근감 때문에 가장 가까운 영역보다
시각적으로 중요하지 않다.
와... 어찌어찌 성공은 했는데 너무나도 긴 여정이었다. 복습 때 가장 유심히 다시 봐야할 부분이다.
1) DepthRTT.fragmentshader
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #version 330 core //output layout(location = 0) out float fragmentdepth; void main(){ fragmentdepth = gl_FragCoord.z; }#version 330 core //output layout(location = 0) out float fragmentdepth; void main(){ fragmentdepth = gl_FragCoord.z; } | cs |
2) DepthRTT.vertexshader
1 2 3 4 5 6 7 8 9 10 11 | #version 330 core //이 쉐이더의 모든 실행에 대해 다른 버텍스 데이터를 입력하십시오 layout(location = 0) in vec3 vertexPosition_modelspace; //전체 메쉬에 대해 일정하게 유지되는 값 uniform mat4 depthMVP; void main(){ gl_Position = depthMVP * vec4(vertexPosition_modelspace,1); } | cs |
3) Passthrough.vertexshader
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #version 330 core // Input vertex data, different for all executions of this shader. layout(location = 0) in vec3 vertexPosition_modelspace; // Output data ; will be interpolated for each fragment. out vec2 UV; void main(){ gl_Position = vec4(vertexPosition_modelspace,1); UV = (vertexPosition_modelspace.xy+vec2(1,1))/2.0; } | cs |
4) ShadowMapping.fragmentshader
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 | #version 330 core // vertex shader에서 보간된 값 in vec2 UV; in vec3 Position_worldspace; in vec3 Normal_cameraspace; in vec3 EyeDirection_cameraspace; in vec3 LightDirection_cameraspace; in vec4 ShadowCoord; // output data layout(location = 0) out vec3 color; // 전체 메시에서 일정하게 유지되는 값 uniform sampler2D myTextureSampler; uniform mat4 MV; uniform vec3 LightPosition_worldspace; uniform sampler2DShadow shadowMap; vec2 poissonDisk[16] = vec2[]( vec2( -0.94201624, -0.39906216 ), vec2( 0.94558609, -0.76890725 ), vec2( -0.094184101, -0.92938870 ), vec2( 0.34495938, 0.29387760 ), vec2( -0.91588581, 0.45771432 ), vec2( -0.81544232, -0.87912464 ), vec2( -0.38277543, 0.27676845 ), vec2( 0.97484398, 0.75648379 ), vec2( 0.44323325, -0.97511554 ), vec2( 0.53742981, -0.47373420 ), vec2( -0.26496911, -0.41893023 ), vec2( 0.79197514, 0.19090188 ), vec2( -0.24188840, 0.99706507 ), vec2( -0.81409955, 0.91437590 ), vec2( 0.19984126, 0.78641367 ), vec2( 0.14383161, -0.14100790 ) ); // vec3와 int에 기반된 랜덤 숫자를 리턴 float random(vec3 seed, int i){ vec4 seed4 = vec4(seed,i); float dot_product = dot(seed4, vec4(12.9898,78.233,45.164,94.673)); return fract(sin(dot_product)*43758.5453); } void main(){ // 빛 방사 특성 vec3 LightColor = vec3(1,1,1); float LightPower = 1.0f; // Material properties vec3 MaterialDiffuseColor = texture(myTextureSampler, UV).rgb; vec3 MaterialAmbientColor = vec3(0.1,0.1,0.1) * MaterialDiffuseColor; vec3 MaterialSpecularColor = vec3(0.3,0.3,0.3); // 빛까지의 거리 // float distance = length( LightPosition_worldspace - Position_worldspace ); // 카메라 공간에서 계산된 조각의 normal vec3 n = normalize( Normal_cameraspace ); // 빛의 방향 (조각에서 빛까지의) vec3 l = normalize( LightDirection_cameraspace ); // Cosine of the angle between the normal and the light direction, // clamped above 0 // - light is at the vertical of the triangle -> 1 // - light is perpendiular to the triangle -> 0 // - light is behind the triangle -> 0 float cosTheta = clamp( dot( n,l ), 0,1 ); // Eye vector (카메라를 향한) vec3 E = normalize(EyeDirection_cameraspace); // 삼각형이 빛을 반사하는 방향 vec3 R = reflect(-l,n); // Cosine of the angle between the Eye vector and the Reflect vector, // clamped to 0 // - Looking into the reflection -> 1 // - Looking elsewhere -> < 1 float cosAlpha = clamp( dot( E,R ), 0,1 ); float visibility = 1.0; // 고정된 bias, or... float bias = 0.005; // ...variable bias // float bias = 0.005*tan(acos(cosTheta)); // bias = clamp(bias, 0,0.01); // shadow map 4 times 샘플링 for(int i=0;i<4;i++){ int index = i; visibility -= 0.2*(1.0-texture( shadowMap, vec3(ShadowCoord.xy + poissonDisk[index]/700.0, (ShadowCoord.z-bias)/ShadowCoord.w))); } // for spot lights, 두 개중에 하나를 써라 // if ( texture( shadowMap, (ShadowCoord.xy/ShadowCoord.w) ).z < (ShadowCoord.z-bias)/ShadowCoord.w ) // if ( textureProj( shadowMap, ShadowCoord.xyw ).z < (ShadowCoord.z-bias)/ShadowCoord.w ) color = // Ambient(주변환경) : 간접 조명을 시뮬레이트하다 MaterialAmbientColor + // Diffuse : object의 색깔 visibility * MaterialDiffuseColor * LightColor * LightPower * cosTheta+ // Specular : 거울처럼 highlight를 반사 visibility * MaterialSpecularColor * LightColor * LightPower * pow(cosAlpha,5); } | cs |
5) SHadowMapping.vertexshader
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 | #version 330 core // 이 쉐이더의 모든 실행에 대해 다른 버텍스 쉐이더를 입력하십시오 layout(location = 0) in vec3 vertexPosition_modelspace; layout(location = 1) in vec2 vertexUV; layout(location = 2) in vec3 vertexNormal_modelspace; // Output data ; 각 단편에 보간될 out vec2 UV; out vec3 Position_worldspace; out vec3 Normal_cameraspace; out vec3 EyeDirection_cameraspace; out vec3 LightDirection_cameraspace; out vec4 ShadowCoord; // 전체 메쉬에서 일정하게 유지될 값 uniform mat4 MVP; uniform mat4 V; uniform mat4 M; uniform vec3 LightInvDirection_worldspace; uniform mat4 DepthBiasMVP; void main(){ // vertex의 output position, clip 공간에서 : MVP * position gl_Position = MVP * vec4(vertexPosition_modelspace, 1); ShadowCoord = DepthBiasMVP * vec4(vertexPosition_modelspace,1); // vertex의 position, 월드스페이스에서 : M * position Position_worldspace = (M * vec4(vertexPosition_modelspace,1)).xyz; // 정점에서 카메라 공간으로 이동하는 벡터이다. // 카메라 공간에서 카메라는 (0,0,0)에 있다. EyeDirection_cameraspace = vec3(0,0,0) - (V * M * vec4(vertexPosition_modelspace,1)).xyz; // 정점에서 라이트로 가는 벡터, 카메라 공간에서 LightDirection_cameraspace = (V*vec4(LightInvDirection_worldspace,0)).xyz; // Normal of the vertex, 카메라 공간에서 Normal_cameraspace = ( V * M * vec4(vertexNormal_modelspace,0)).xyz; UV = vertexUV; } | cs |
6) SimpleTexture.fragmentshader
1 2 3 4 5 6 7 8 9 10 11 12 | #version 330 core // Ouput data layout(location = 0) out vec4 color; uniform sampler2D texture; in vec2 UV; void main(){ color = texture(texture, UV); } | cs |
7) source.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 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 | #include <stdio.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <map> #include <GL/glew.h> #include <glfw3.h> #include <GL/glew.h> GLFWwindow* window; #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> using namespace glm; #define FOURCC_DXT1 0x31545844 // Equivalent to "DXT1" in ASCII #define FOURCC_DXT3 0x33545844 // Equivalent to "DXT3" in ASCII #define FOURCC_DXT5 0x35545844 // Equivalent to "DXT5" in ASCII GLuint LoadShaders(const char *, const char *); GLuint loadBMP_custom(const char *); GLuint loadDDS(const char *); bool loadOBJ( const char *, std::vector<glm::vec3> &, std::vector<glm::vec2> &, std::vector<glm::vec3> &); void indexVBO( std::vector<glm::vec3> & , std::vector<glm::vec2> & , std::vector<glm::vec3> & , std::vector<unsigned short> & , std::vector<glm::vec3> & , std::vector<glm::vec2> & , std::vector<glm::vec3> & ); void indexVBO_TBN( std::vector<glm::vec3> &, std::vector<glm::vec2> &, std::vector<glm::vec3> &, std::vector<glm::vec3> &, std::vector<glm::vec3> &, std::vector<unsigned short> &, std::vector<glm::vec3> &, std::vector<glm::vec2> &, std::vector<glm::vec3> &, std::vector<glm::vec3> &, std::vector<glm::vec3> & ); //mouse-keyboard input void computeMatricesFromInputs(); glm::mat4 getViewMatrix(); glm::mat4 getProjectionMatrix(); glm::mat4 ViewMatrix; glm::mat4 ProjectionMatrix; glm::mat4 getViewMatrix() { return ViewMatrix; } glm::mat4 getProjectionMatrix() { return ProjectionMatrix; } struct PackedVertex { glm::vec3 position; glm::vec2 uv; glm::vec3 normal; bool operator<(const PackedVertex that) const { return memcmp((void*)this, (void*)&that, sizeof(PackedVertex))>0; }; }; bool is_near(float v1, float v2) { return fabs(v1 - v2) < 0.01f; } bool getSimilarVertexIndex_fast( PackedVertex & packed, std::map<PackedVertex, unsigned short> & VertexToOutIndex, unsigned short & result ) { std::map<PackedVertex, unsigned short>::iterator it = VertexToOutIndex.find(packed); if (it == VertexToOutIndex.end()) { return false; } else { result = it->second; return true; } } bool getSimilarVertexIndex( glm::vec3 & in_vertex, glm::vec2 & in_uv, glm::vec3 & in_normal, std::vector<glm::vec3> & out_vertices, std::vector<glm::vec2> & out_uvs, std::vector<glm::vec3> & out_normals, unsigned short & result ) { // Lame linear search for (unsigned int i = 0; i<out_vertices.size(); i++) { if ( is_near(in_vertex.x, out_vertices[i].x) && is_near(in_vertex.y, out_vertices[i].y) && is_near(in_vertex.z, out_vertices[i].z) && is_near(in_uv.x, out_uvs[i].x) && is_near(in_uv.y, out_uvs[i].y) && is_near(in_normal.x, out_normals[i].x) && is_near(in_normal.y, out_normals[i].y) && is_near(in_normal.z, out_normals[i].z) ) { result = i; return true; } } // No other vertex could be used instead. // Looks like we'll have to add it to the VBO. return false; } void computeTangentBasis( //inputs std::vector<glm::vec3> &, std::vector<glm::vec2> &, std::vector<glm::vec3> &, //outputs std::vector<glm::vec3> &, std::vector<glm::vec3> & ); //text2D unsigned int Text2DTextureID; unsigned int Text2DVertexBufferID; unsigned int Text2DUVBufferID; unsigned int Text2DShaderID; unsigned int Text2DUniformID; void initText2D(const char *); void printText2D(const char *, int, int, int); void cleanupText2D(); //포지션 초기화 glm::vec3 position = glm::vec3(0, 0, 5); float horizontalAngle = 3.14f; float verticalAngle = 0.0f; float initialFoV = 45.0f; float speed = 3.0f; float mouseSpeed = 0.005f; void APIENTRY DebugOutputCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { printf("OpenGL Debug Output message : "); if (source == GL_DEBUG_SOURCE_API_ARB) printf("Source : API; "); else if (source == GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB) printf("Source : WINDOW_SYSTEM; "); else if (source == GL_DEBUG_SOURCE_SHADER_COMPILER_ARB) printf("Source : SHADER_COMPILER; "); else if (source == GL_DEBUG_SOURCE_THIRD_PARTY_ARB) printf("Source : THIRD_PARTY; "); else if (source == GL_DEBUG_SOURCE_APPLICATION_ARB) printf("Source : APPLICATION; "); else if (source == GL_DEBUG_SOURCE_OTHER_ARB) printf("Source : OTHER; "); if (type == GL_DEBUG_TYPE_ERROR_ARB) printf("Type : ERROR; "); else if (type == GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB) printf("Type : DEPRECATED_BEHAVIOR; "); else if (type == GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB) printf("Type : UNDEFINED_BEHAVIOR; "); else if (type == GL_DEBUG_TYPE_PORTABILITY_ARB) printf("Type : PORTABILITY; "); else if (type == GL_DEBUG_TYPE_PERFORMANCE_ARB) printf("Type : PERFORMANCE; "); else if (type == GL_DEBUG_TYPE_OTHER_ARB) printf("Type : OTHER; "); if (severity == GL_DEBUG_SEVERITY_HIGH_ARB) printf("Severity : HIGH; "); else if (severity == GL_DEBUG_SEVERITY_MEDIUM_ARB) printf("Severity : MEDIUM; "); else if (severity == GL_DEBUG_SEVERITY_LOW_ARB) printf("Severity : LOW; "); //break point를 여기에 설정해라, 당신의 디버거는 프로그램을 멈출 것이다 //callstack은 바로 너에게 offending call을 보여줄 것이다 printf("Mesage : %s\n", message); } int main() { // Initialise GLFW if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); getchar(); return -1; } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Open a window and create its OpenGL context window = glfwCreateWindow(1024, 768, "QBOT_opengl", NULL, NULL); if (window == NULL) { fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n"); getchar(); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); int windowWidth = 1024; int windowHeight = 768; glfwGetFramebufferSize(window, &windowWidth, &windowHeight); // Initialize GLEW glewExperimental = true; if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); getchar(); glfwTerminate(); return -1; } // Example 1: /*if (GLEW_AMD_seamless_cubemap_per_texture) { printf("The GL_AMD_seamless_cubemap_per_texture is present, (but we're not goint to use it)\n"); //이제 glTexParameterf를 TEXTURE_CUBE_MAP_SEAMLESS_ARB 매개 변수와 함께 호출하는 것이 합법적이다 //분명히 이 코드는 AMD가 아닌 하드웨어에서는 실표할 것이기 때문에 테스트해야한다 } // Example 2: if (GLEW_ARB_debug_output) { printf("The OpenGL implementation provides debug output. Let's use it!\n"); glDebugMessageCallbackARB(&DebugOutputCallback, NULL); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); } else { printf("ARB_debug_output unavailable. You have to use glGetError() and/or gDebugger to catch mistakes.\n"); }*/ // Ensure we can capture the escape key being pressed below glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // Set the mouse at the center of the screen glfwPollEvents(); glfwSetCursorPos(window, 1024 / 2, 768 / 2); // Dark blue background glClearColor(0.0f, 0.0f, 0.4f, 0.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); //Shader를 불러온다. //GLuint programID = LoadShaders("NormalMapping.vertexshader", "NormalMapping.fragmentshader"); //GLuint programID = LoadShaders("StandardShadingRTT.vertexshader", "StandardShadingRTT.fragmentshader"); //GLuint programID = LoadShaders("TransformVertexShader.vertexshader", "TextureFragmentShaderLOD.fragmentshader"); GLuint depthProgramID = LoadShaders("DepthRTT.vertexshader", "DepthRTT.fragmentshader"); //매트릭스ID 추가 // GLuint MatrixID = glGetUniformLocation(programID, "MVP"); // GLuint ViewMatrixID = glGetUniformLocation(programID, "V"); // GLuint ModelMatrixID = glGetUniformLocation(programID, "M"); // GLuint ModelView3x3MatrixID = glGetUniformLocation(programID, "MV3x3"); GLuint depthMatrixID = glGetUniformLocation(depthProgramID, "depthMVP"); //어떠한 두 가지의 함수를 사용해서 텍스처를 불러온다 //GLuint Texture = loadBMP_custom("uvtemplate.bmp"); //GLuint Texture = loadDDS("uvmap.DDS"); //GLuint DiffuseTexture = loadDDS("diffuse.DDS"); //GLuint NormalTexture = loadBMP_custom("normal.bmp"); //GLuint SpecularTexture = loadDDS("specular.DDS"); GLuint Texture = loadDDS("uvmap.DDS"); //GLuint TextureID = glGetUniformLocation(programID, "myTextureSampler"); //GLuint DiffuseTextureID = glGetUniformLocation(programID, "DiffuseTextureSampler"); //GLuint NormalTextureID = glGetUniformLocation(programID, "NormalTextureSampler"); //GLuint SpecularTextureID = glGetUniformLocation(programID, "SpecularTextureSampler"); //우리의 .obj file을 읽는다 std::vector<glm::vec3> vertices; std::vector<glm::vec2> uvs; std::vector<glm::vec3> normals; bool res = loadOBJ("room_thickwalls.obj", vertices, uvs, normals); /* std::vector<glm::vec3> tangents; std::vector<glm::vec3> bitangents; computeTangentBasis( vertices, uvs, normals, // input tangents, bitangents // output ); */ std::vector<unsigned short> indices; std::vector<glm::vec3> indexed_vertices; std::vector<glm::vec2> indexed_uvs; std::vector<glm::vec3> indexed_normals; indexVBO(vertices, uvs, normals, indices, indexed_vertices, indexed_uvs, indexed_normals); //std::vector<glm::vec3> indexed_tangents; //std::vector<glm::vec3> indexed_bitangents; /*indexVBO_TBN( vertices, uvs, normals, tangents, bitangents, indices, indexed_vertices, indexed_uvs, indexed_normals, indexed_tangents, indexed_bitangents );*/ GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_vertices.size() * sizeof(glm::vec3), &indexed_vertices[0], GL_STATIC_DRAW); GLuint uvbuffer; glGenBuffers(1, &uvbuffer); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_uvs.size() * sizeof(glm::vec2), &indexed_uvs[0], GL_STATIC_DRAW); GLuint normalbuffer; glGenBuffers(1, &normalbuffer); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_normals.size() * sizeof(glm::vec3), &indexed_normals[0], GL_STATIC_DRAW); /* GLuint tangentbuffer; glGenBuffers(1, &tangentbuffer); glBindBuffer(GL_ARRAY_BUFFER, tangentbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_tangents.size() * sizeof(glm::vec3), &indexed_tangents[0], GL_STATIC_DRAW); GLuint bitangentbuffer; glGenBuffers(1, &bitangentbuffer); glBindBuffer(GL_ARRAY_BUFFER, bitangentbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_bitangents.size() * sizeof(glm::vec3), &indexed_bitangents[0], GL_STATIC_DRAW); */ // Generate a buffer for the indices as well GLuint elementbuffer; glGenBuffers(1, &elementbuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned short), &indices[0], GL_STATIC_DRAW); //glUseProgram(programID); //GLuint LightID = glGetUniformLocation(programID, "LightPosition_worldspace"); // render to texture // framebuffer, 0,1 or 더 많은 텍스처로 재그룹된다. 그리고 0 or 1 깊이 버퍼 GLuint FramebufferName = 0; glGenFramebuffers(1, &FramebufferName); glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); //GLuint renderedTexture; //glGenTextures(1, &renderedTexture); //glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); //새롭게 만들어진 텍스처를 "bind" : 모든 미래 텍스처 기능들은 이 텍스처에 수정 //glBindTexture(GL_TEXTURE_2D, renderedTexture); //비어있는 이미지를 OpenGL에 준다 (마지막 0은 비어있음을 의미) /* glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, windowWidth, windowHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); //Poor filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); //The depth buffer GLuint depthrenderbuffer; glGenRenderbuffers(1, &depthrenderbuffer); glBindRenderbuffer(GL_RENDERBUFFER, depthrenderbuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, windowWidth, windowHeight); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthrenderbuffer); */ //// Alternative : Depth texture. Slower, but you can sample it later in your shader GLuint depthTexture; glGenTextures(1, &depthTexture); glBindTexture(GL_TEXTURE_2D, depthTexture); glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT24, 1024, 1024, 0,GL_DEPTH_COMPONENT, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0); //bound framebuffer에는 색이 없다, 깊이 뿐이다 glDrawBuffer(GL_NONE); // framebuffer가 ok인지 항상 체크한다 if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) return false; // "renderedTexture" 우리의 색을 입힌다 //glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, renderedTexture, 0); //// Depth texture alternative : //glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0); // Set the list of draw buffers. /*GLenum DrawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, DrawBuffers); // "1" is the size of DrawBuffers */ // The fullscreen quad's FBO static const GLfloat g_quad_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, }; GLuint quad_vertexbuffer; glGenBuffers(1, &quad_vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW); // Create and compile our GLSL program from the shaders GLuint quad_programID = LoadShaders("Passthrough.vertexshader", "SimpleTexture.fragmentshader"); GLuint texID = glGetUniformLocation(quad_programID, "texture"); //GLuint timeID = glGetUniformLocation(quad_programID, "time"); // 쉐이더의 GLSL 프로그램을 만들고 컴파일한다 GLuint programID = LoadShaders("ShadowMapping.vertexshader", "ShadowMapping.fragmentshader"); // "myTextureSampler" uniform의 handle을 얻는다 GLuint TextureID = glGetUniformLocation(programID, "myTextureSampler"); GLuint MatrixID = glGetUniformLocation(programID, "MVP"); GLuint ViewMatrixID = glGetUniformLocation(programID, "V"); GLuint ModelMatrixID = glGetUniformLocation(programID, "M"); GLuint DepthBiasID = glGetUniformLocation(programID, "DepthBiasMVP"); GLuint ShadowMapID = glGetUniformLocation(programID, "shadowMap"); GLuint lightInvDirID = glGetUniformLocation(programID, "LightInvDirection_worldspace"); //little text library를 초기화 //initText2D("Holstein.DDS"); //speed computation double lastTime = glfwGetTime(); int nbFrames = 0; //enable blending //glEnable(GL_BLEND); //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); do { //속도 측정 double currentTime = glfwGetTime(); nbFrames++; if (currentTime - lastTime >= 1.0) { printf("%f ms/frame\n", 1000.0 / double(nbFrames)); nbFrames = 0; lastTime += 1.0; } // framebuffer에 render한다 glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); glViewport(0, 0, 1024, 1024); //전체 framebuffer에 렌더, 왼쪽아래부터 오른쪽 위까지 완료 // 쉐이더에서 bias를 사용하지 않고 대신에 faces를 그린다 // 이미 작은면으로 전면에서 분리되어있다. glEnable(GL_CULL_FACE); glCullFace(GL_BACK); // 뒤쪽을 향한 삼각형을 뒤틀어서 -> 앞쪽을 향한 삼각형만 그린다 // Clear the screen. It's not mentioned before Tutorial 02, but it can cause flickering, so it's there nonetheless. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(depthProgramID); glm::vec3 lightInvDir = glm::vec3(0.5f, 2, 2); // 뷰의 빛 위치로부터 MVP matrix를 검사해라 glm::mat4 depthProjectionMatrix = glm::ortho<float>(-10, 10, -10, 10, -10, 20); glm::mat4 depthViewMatrix = glm::lookAt(lightInvDir, glm::vec3(0, 0, 0), glm::vec3(0, 1, 0)); glm::mat4 depthModelMatrix = glm::mat4(1.0); glm::mat4 depthMVP = depthProjectionMatrix * depthViewMatrix * depthModelMatrix; //glm::vec3 lightPos = glm::vec3(4, 4, 4); //glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z); // 텍스처 유닛 0에 있는 텍스처를 바인드 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Texture); glUniform1i(TextureID, 0); // //텍스처 유닛0에 있는 텍스처를 바인딩한다. /* glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, DiffuseTexture); glUniform1i(DiffuseTextureID, 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, NormalTexture); glUniform1i(NormalTextureID, 1); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, SpecularTexture); glUniform1i(SpecularTextureID, 2); */ glUniformMatrix4fv(depthMatrixID, 1, GL_FALSE, &depthMVP[0][0]); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer( 0, //0번째 속성. 0이 될 특별한 이유는 없지만 쉐이더의 레이아웃과 반드시 맞춰야함 3, //크기(size) GL_FLOAT, //타입(type) GL_FALSE, //정규화(normalized)? 0, //다음 요소까지의 간격(stride) (void*)0 //배열 버퍼의 오프셋(offset) ); /* //2nd 속성 버퍼 : UVs glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0 ); /* //3rd 속성 버퍼 : normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glVertexAttribPointer( 2, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 );*/ /* // 4th attribute buffer : tangents glEnableVertexAttribArray(3); glBindBuffer(GL_ARRAY_BUFFER, tangentbuffer); glVertexAttribPointer( 3, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 5th attribute buffer : bitangents glEnableVertexAttribArray(4); glBindBuffer(GL_ARRAY_BUFFER, bitangentbuffer); glVertexAttribPointer( 4, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); */ // Index 버퍼 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); // 삼각형 그리기 glDrawElements( GL_TRIANGLES, //mode indices.size(), //count GL_UNSIGNED_SHORT, //type (void*)0 //element array buffer offset ); //glDrawArrays(GL_TRIANGLES, 0, vertices.size()); glDisableVertexAttribArray(0); //glDisableVertexAttribArray(1); //glDisableVertexAttribArray(2); //glDisableVertexAttribArray(3); //glDisableVertexAttribArray(4); // 스크린에 Render한다 glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, windowWidth, windowHeight); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(programID); //키보드와 마우스 인풋으로부터의 MVP 매트릭스를 계산한다 computeMatricesFromInputs(); glm::mat4 ProjectionMatrix = getProjectionMatrix(); glm::mat4 ViewMatrix = getViewMatrix(); glm::mat4 ModelMatrix = glm::mat4(1.0); //glm::mat4 ModelViewMatrix = ViewMatrix * ModelMatrix; //glm::mat3 ModelView3x3Matrix = glm::mat3(ModelViewMatrix); glm::mat4 MVP = ProjectionMatrix*ViewMatrix*ModelMatrix; glm::mat4 biasMatrix( 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0 ); glm::mat4 depthBiasMVP = biasMatrix*depthMVP; //transformation을 현재 쉐이더에 보냄 glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix[0][0]); glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]); glUniformMatrix4fv(DepthBiasID, 1, GL_FALSE, &depthBiasMVP[0][0]); //glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]); //glUniformMatrix3fv(ModelView3x3MatrixID, 1, GL_FALSE, &ModelView3x3Matrix[0][0]); glUniform3f(lightInvDirID, lightInvDir.x, lightInvDir.y, lightInvDir.z); // Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Texture); // Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(TextureID, 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, depthTexture); glUniform1i(ShadowMapID, 1); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer( 0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 2nd attribute buffer : UVs glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glVertexAttribPointer( 1, // attribute 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 3rd attribute buffer : normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glVertexAttribPointer( 2, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); // Draw the triangles ! glDrawElements( GL_TRIANGLES, // mode indices.size(), // count GL_UNSIGNED_SHORT, // type (void*)0 // element array buffer offset ); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); // Render only on a corner of the window (or we we won't see the real rendering...) glViewport(0, 0, 512, 512); // Use our shader glUseProgram(quad_programID); // Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, depthTexture); // Set our "renderedTexture" sampler to user Texture Unit 0 glUniform1i(texID, 0); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer); glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Draw the triangle ! // You have to disable GL_COMPARE_R_TO_TEXTURE above in order to see anything ! //glDrawArrays(GL_TRIANGLES, 0, 6); // 2*3 indices starting at 0 -> 2 triangles glDisableVertexAttribArray(0); //char text[256]; //sprintf(text, "%.2f sec", glfwGetTime()); //printText2D(text, 10, 500, 60); //////////////////////////////////////////////////////// // DEBUG ONLY !!! // Don't use this in real code !! //////////////////////////////////////////////////////// /* glMatrixMode(GL_PROJECTION); glLoadMatrixf((const GLfloat*)&ProjectionMatrix[0]); glMatrixMode(GL_MODELVIEW); glm::mat4 MV = ViewMatrix * ModelMatrix; glLoadMatrixf((const GLfloat*)&MV[0]); glUseProgram(0); // normals glColor3f(0, 0, 1); glBegin(GL_LINES); for (unsigned int i = 0; i<indices.size(); i++) { glm::vec3 p = indexed_vertices[indices[i]]; glVertex3fv(&p.x); glm::vec3 o = glm::normalize(indexed_normals[indices[i]]); p += o*0.1f; glVertex3fv(&p.x); } glEnd(); // tangents glColor3f(1, 0, 0); glBegin(GL_LINES); for (unsigned int i = 0; i<indices.size(); i++) { glm::vec3 p = indexed_vertices[indices[i]]; glVertex3fv(&p.x); glm::vec3 o = glm::normalize(indexed_tangents[indices[i]]); p += o*0.1f; glVertex3fv(&p.x); } glEnd(); // bitangents glColor3f(0, 1, 0); glBegin(GL_LINES); for (unsigned int i = 0; i<indices.size(); i++) { glm::vec3 p = indexed_vertices[indices[i]]; glVertex3fv(&p.x); glm::vec3 o = glm::normalize(indexed_bitangents[indices[i]]); p += o*0.1f; glVertex3fv(&p.x); } glEnd(); // light pos glColor3f(1, 1, 1); glBegin(GL_LINES); glVertex3fv(&lightPos.x); lightPos += glm::vec3(1, 0, 0)*0.1f; glVertex3fv(&lightPos.x); lightPos -= glm::vec3(1, 0, 0)*0.1f; glVertex3fv(&lightPos.x); lightPos += glm::vec3(0, 1, 0)*0.1f; glVertex3fv(&lightPos.x); glEnd(); */ //스크린에 렌더 /* glBindFramebuffer(GL_FRAMEBUFFER, 0); //전체 framebuffer에 렌더, 왼쪽 아래부터 오른쪽 위 코너까지 완료 glViewport(0, 0, windowWidth, windowHeight); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(quad_programID); //텍스쳐 0에서 텍스처 바인드 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, renderedTexture); glUniform1i(texID, 0); glUniform1f(timeID, (float)(glfwGetTime()*10.0f)); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer); glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Draw the triangles ! glDrawArrays(GL_TRIANGLES, 0, 6); // 2*3 indices starting at 0 -> 2 triangles glDisableVertexAttribArray(0); */ // Swap buffersz glfwSwapBuffers(window); glfwPollEvents(); } // Check if the ESC key was pressed or the window was closed while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0); // Cleanup VBO and shader glDeleteBuffers(1, &vertexbuffer); glDeleteBuffers(1, &uvbuffer); glDeleteBuffers(1, &normalbuffer); glDeleteBuffers(1, &elementbuffer); glDeleteProgram(programID); glDeleteProgram(depthProgramID); glDeleteProgram(quad_programID); glDeleteTextures(1, &Texture); glDeleteFramebuffers(1, &FramebufferName); glDeleteTextures(1, &depthTexture); glDeleteBuffers(1, &quad_vertexbuffer); glDeleteVertexArrays(1, &VertexArrayID); // Close OpenGL window and terminate GLFW glfwTerminate(); return 0; } GLuint LoadShaders(const char * vertex_file_path, const char * fragment_file_path) { //쉐이더 생성 GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER); GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); //버텍스 쉐이더 코드를 파일에서 읽기 std::string VertexShaderCode; std::ifstream VertexShaderStream(vertex_file_path, std::ios::in); if (VertexShaderStream.is_open()) { std::stringstream sstr; sstr << VertexShaderStream.rdbuf(); VertexShaderCode = sstr.str(); VertexShaderStream.close(); } else { printf("파일 %s를 읽을 수 없음. 정확한 디렉토리를 사용 중입니까?\n", vertex_file_path); getchar(); return 0; } //프래그먼트 쉐이더 코드를 파일에서 읽기 std::string FragmentShaderCode; std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in); if (FragmentShaderStream.is_open()) { std::stringstream sstr; sstr << FragmentShaderStream.rdbuf(); FragmentShaderCode = sstr.str(); FragmentShaderStream.close(); } GLint Result = GL_FALSE; int InfoLogLength; //버텍스 쉐이더를 컴파일 printf("Compiling shader : %s\n", vertex_file_path); char const * VertexSourcePointer = VertexShaderCode.c_str(); glShaderSource(VertexShaderID, 1, &VertexSourcePointer, NULL); glCompileShader(VertexShaderID); //버텍스 쉐이더를 검사 glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { std::vector<char> VertexShaderErrorMessage(InfoLogLength + 1); glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]); printf("%s\n", &VertexShaderErrorMessage[0]); } //프래그먼트 쉐이더를 컴파일 printf("Compiling shader : %s", fragment_file_path); char const * FragmentSourcePointer = FragmentShaderCode.c_str(); glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer, NULL); glCompileShader(FragmentShaderID); //프래그먼트 쉐이더를 검사 glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { std::vector<char> FragmentShaderErrorMessage(InfoLogLength + 1); glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]); printf("%s\n", &FragmentShaderErrorMessage[0]); } //프로그램에 링크 printf("Linking program\n"); GLuint ProgramID = glCreateProgram(); glAttachShader(ProgramID, VertexShaderID); glAttachShader(ProgramID, FragmentShaderID); glLinkProgram(ProgramID); //프로그램 검사 glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result); glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { std::vector<char> ProgramErrorMessage(InfoLogLength + 1); glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]); printf("%s\n", &ProgramErrorMessage[0]); } glDetachShader(ProgramID, VertexShaderID); glDetachShader(ProgramID, FragmentShaderID); glDeleteShader(VertexShaderID); glDeleteShader(FragmentShaderID); return ProgramID; } GLuint loadBMP_custom(const char * imagepath) { printf("Reading image %s\n", imagepath); //BMP파일의 헤더에서 데이터를 읽는다 unsigned char header[54]; unsigned int dataPos; unsigned int imageSize; unsigned int width, height; //실제 RGB 데이터 unsigned char * data; //파일을 연다 FILE * file = fopen(imagepath, "rb"); if (!file) { printf("%s는 열수 없다. 경로가 맞는지 확인해라.\n", imagepath); getchar(); return 0; } //헤더를 읽는다, i.e. the 54 first bytes //만약 54 bytes보다 적게 읽혔으면 문제 발생 if (fread(header, 1, 54, file) != 54) { printf("BMP 파일이 아니다\n"); return 0; } //A BMP 파일은 항상 "BM"으로 시작한다. if (header[0] != 'B' || header[1] != 'M') { printf("BMP 파일이 아니다\n"); return 0; } //24pp file임을 확인한다. if (*(int*)&(header[0x1e]) != 0 || *(int*)&(header[0x1C]) != 24) { printf("BMP 파일이 아니다\n"); return 0; } //이미지에 대한 정보를 읽는다. dataPos = *(int*)&(header[0x0A]); imageSize = *(int*)&(header[0x22]); width = *(int*)&(header[0x12]); height = *(int*)&(header[0x16]); //몇몇 BMP 파일들은 포맷이 놓쳐졌다, 놓쳐진 정보를 추측해라 if (imageSize == 0) imageSize = width*height * 3; // 3 : one byte for each Red-Green-Blue component if (dataPos == 0) dataPos = 54; //BMP 헤더는 항상 이 형식 //버퍼를 생성한다 data = new unsigned char[imageSize]; //파일의 버퍼에 있는 실제 데이터를 읽는다 fread(data, 1, imageSize, file); //모든 것은 현재 메모리에 있다, 파일을 닫는다 fclose(file); //openGL 텍스처를 만든다 GLuint textureID; glGenTextures(1, &textureID); //새로이 만들어진 텍스처를 바인딩한다. glBindTexture(GL_TEXTURE_2D, textureID); //이미지를 OpenGL에게 넘긴다 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data); delete[] data; // trilinear(삼선형) 필터링 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); return textureID; } GLuint loadDDS(const char * imagepath) { unsigned char header[124]; FILE *fp; //파일을 연다 fp = fopen(imagepath, "rb"); if (fp == NULL) { printf("%s는 열 수 없다. 경로를 확인해라\n", imagepath); getchar(); return 0; } //파일의 타입을 확인한다 char filecode[4]; fread(filecode, 1, 4, fp); if (strncmp(filecode, "DDS ", 4) != 0) { fclose(fp); return 0; } //surface desc를 얻는다 fread(&header, 124, 1, fp); unsigned int height = *(unsigned int*)&(header[8]); unsigned int width = *(unsigned int*)&(header[12]); unsigned int linearSize = *(unsigned int*)&(header[16]); unsigned int mipMapCount = *(unsigned int*)&(header[24]); unsigned int fourCC = *(unsigned int*)&(header[80]); unsigned char * buffer; unsigned int bufsize; bufsize = mipMapCount > 1 ? linearSize * 2 : linearSize; buffer = (unsigned char*)malloc(bufsize * sizeof(unsigned char)); fread(buffer, 1, bufsize, fp); fclose(fp); unsigned int components = (fourCC == FOURCC_DXT1) ? 3 : 4; unsigned int format; switch (fourCC) { case FOURCC_DXT1: format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; break; case FOURCC_DXT3: format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break; case FOURCC_DXT5: format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; break; default: free(buffer); return 0; } //하나의 OpenGL 텍스처를 생성한다 GLuint textureID; glGenTextures(1, &textureID); //새로이 만들어진 텍스처를 바인딩한다 glBindTexture(GL_TEXTURE_2D, textureID); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); unsigned int blockSize = (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16; unsigned int offset = 0; //밉맵을 불러온다 for (unsigned int level = 0; level < mipMapCount && (width || height); ++level) { unsigned int size = ((width + 3) / 4)*((height + 3) / 4)*blockSize; glCompressedTexImage2D(GL_TEXTURE_2D, level, format, width, height, 0, size, buffer + offset); offset += size; width /= 2; height /= 2; //Non-Power-Of-Two 텍스처를 사용합니다. //이 코드는 혼란을 줄이기 위해 웹 페이지에는 포함되어 있지 않습니다. if (width < 1)width = 1; if (height < 1) height = 1; } free(buffer); return textureID; } bool loadOBJ( const char * path, std::vector<glm::vec3> & out_vertices, std::vector<glm::vec2> & out_uvs, std::vector<glm::vec3> & out_normals ) { printf("OBJ 파일 로딩중 %s...\n", path); std::vector<unsigned int> vertexIndices, uvIndices, normalIndices; std::vector<glm::vec3> temp_vertices; std::vector <glm::vec2> temp_uvs; std::vector<glm::vec3> temp_normals; FILE * file = fopen(path, "r"); if (file == NULL) { printf("파일 경로를 확인하세요!\n"); getchar(); return false; } while (1) { char lineHeader[128]; //첫번째 라인의 첫번째 단어를 읽는다 int res = fscanf(file, "%s", lineHeader); if (res == EOF) break; //else : 라인의 헤더를 parse if (strcmp(lineHeader, "v") == 0) { glm::vec3 vertex; fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z); temp_vertices.push_back(vertex); } else if (strcmp(lineHeader, "vt") == 0) { glm::vec2 uv; fscanf(file, "%f %f\n", &uv.x, &uv.y); uv.y = -uv.y; //우리가 DDS texture만을 이용할 것이므로 V의 좌표를 반대로 바꾸어준다. 만약 TGA or BMP 로더를 사용하면 이 것을 제거해라. temp_uvs.push_back(uv); } else if (strcmp(lineHeader, "vn") == 0) { glm::vec3 normal; fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z); temp_normals.push_back(normal); } else if (strcmp(lineHeader, "f") == 0) { std::string vertex1, vertex2, vertex3; unsigned int vertexIndex[3], uvIndex[3], normalIndex[3]; int matches = fscanf(file,"%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]); if (matches != 9) { printf("파일을 읽을수없다."); return false; } vertexIndices.push_back(vertexIndex[0]); vertexIndices.push_back(vertexIndex[1]); vertexIndices.push_back(vertexIndex[2]); uvIndices.push_back(uvIndex[0]); uvIndices.push_back(uvIndex[1]); uvIndices.push_back(uvIndex[2]); normalIndices.push_back(normalIndex[0]); normalIndices.push_back(normalIndex[1]); normalIndices.push_back(normalIndex[2]); } else { //나머지 라인을 먹는다. char stupidBuffer[1000]; fgets(stupidBuffer, 1000, file); } } //각 삼각형의 각 꼭지점 for (unsigned int i = 0; i < vertexIndices.size(); i++) { //속성의 인덱스를 가져온다 unsigned int vertexIndex = vertexIndices[i]; unsigned int uvIndex = uvIndices[i]; unsigned int normalIndex = normalIndices[i]; //인덱스에서 속성을 가져온다 glm::vec3 vertex = temp_vertices[vertexIndex - 1]; glm::vec2 uv = temp_uvs[uvIndex - 1]; glm::vec3 normal = temp_normals[normalIndex - 1]; //버퍼에 속성을 넣는다 out_vertices.push_back(vertex); out_uvs.push_back(uv); out_normals.push_back(normal); } return true; } void indexVBO( std::vector<glm::vec3> & in_vertices, std::vector<glm::vec2> & in_uvs, std::vector<glm::vec3> & in_normals, std::vector<unsigned short> & out_indices, std::vector<glm::vec3> & out_vertices, std::vector<glm::vec2> & out_uvs, std::vector<glm::vec3> & out_normals ) { std::map<PackedVertex, unsigned short> VertexToOutIndex; //각 input vertex를 위해 for (unsigned int i = 0; i < in_vertices.size(); i++) { PackedVertex packed = { in_vertices[i], in_uvs[i], in_normals[i] }; //out_XXXX에서 비슷한 vertex를 찾는다 unsigned short index; bool found = getSimilarVertexIndex_fast(packed, VertexToOutIndex, index); if (found) { //비슷한 vertex가 VBO에 이미 있다면 대신 사용한다 out_indices.push_back(index); } else { //아니라면 이것은 아웃풋 데이터 추가가 필요하다 out_vertices.push_back(in_vertices[i]); out_uvs.push_back(in_uvs[i]); out_normals.push_back(in_normals[i]); unsigned short newindex = (unsigned short)out_vertices.size() - 1; out_indices.push_back(newindex); VertexToOutIndex[packed] = newindex; } } } void indexVBO_TBN( std::vector<glm::vec3> & in_vertices, std::vector<glm::vec2> & in_uvs, std::vector<glm::vec3> & in_normals, std::vector<glm::vec3> & in_tangents, std::vector<glm::vec3> & in_bitangents, std::vector<unsigned short> & out_indices, std::vector<glm::vec3> & out_vertices, std::vector<glm::vec2> & out_uvs, std::vector<glm::vec3> & out_normals, std::vector<glm::vec3> & out_tangents, std::vector<glm::vec3> & out_bitangents ) { //각 input vertex를 위해 for (unsigned int i = 0; i < in_vertices.size(); i++) { //out_XXXX 에서 비슷한 vertex를 찾는다 unsigned short index; bool found = getSimilarVertexIndex(in_vertices[i], in_uvs[i], in_normals[i], out_vertices, out_uvs, out_normals, index); if (found) { //비슷한 vertex가 이미 VBO에 있으면, 이것을 대신 사용 out_indices.push_back(index); //tangents와 bitangents의 평균을 한다 out_tangents[index] += in_tangents[i]; out_bitangents[index] += in_bitangents[i]; } else { // 만약 아니라면, output data에서 추가한다 out_vertices.push_back(in_vertices[i]); out_uvs.push_back(in_uvs[i]); out_normals.push_back(in_normals[i]); out_tangents.push_back(in_tangents[i]); out_bitangents.push_back(in_bitangents[i]); out_indices.push_back((unsigned short)out_vertices.size() - 1); } } } void computeMatricesFromInputs() { //glfwGetTime은 한번만 호출된다. static double lastTime = glfwGetTime(); //현재와 마지막 프레임의 시간 차를 계산한다. double currentTime = glfwGetTime(); float deltaTime = float(currentTime - lastTime); //마우스의 위치를 얻는다. double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); //다음 프레임의 마우스 위치를 리셋한다. glfwSetCursorPos(window, 1024 / 2, 768 / 2); horizontalAngle += mouseSpeed * float(1024 / 2 - xpos); verticalAngle += mouseSpeed * float(768 / 2 - ypos); //Direction : Spherical 좌표 to Cartesian 좌표 변환 glm::vec3 direction( cos(verticalAngle)*sin(horizontalAngle), sin(verticalAngle), cos(verticalAngle)*cos(horizontalAngle) ); //Right vector glm::vec3 right = glm::vec3( sin(horizontalAngle - 3.14f / 2.0f), 0, cos(horizontalAngle - 3.14f / 2.0f) ); //Up vector glm::vec3 up = glm::cross(right, direction); //앞으로 이동 if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) { position += direction*deltaTime*speed; } //뒤로 이동 if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) { position -= direction*deltaTime*speed; } //오른쪽로 Strafe if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) { position += right*deltaTime*speed; } //왼쪽으로 Strafe if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) { position -= right*deltaTime*speed; } float FoV = initialFoV; ProjectionMatrix = glm::perspective(FoV, 4.0f / 3.0f, 0.1f, 100.0f); ViewMatrix = glm::lookAt( position, //camera here position + direction, //and looks here up // Head is up ); //다음 프레임을 위해 lastTime = currentTime; } void computeTangentBasis( //inputs std::vector<glm::vec3> & vertices, std::vector<glm::vec2> & uvs, std::vector<glm::vec3> & normals, //outputs std::vector<glm::vec3> & tangents, std::vector<glm::vec3> & bitangents ) { for (unsigned int i = 0; i < vertices.size(); i += 3) { //shortcuts for vertices glm::vec3 & v0 = vertices[i + 0]; glm::vec3 & v1 = vertices[i + 1]; glm::vec3 & v2 = vertices[i + 2]; //shortcuts for UVs glm::vec2 & uv0 = uvs[i + 0]; glm::vec2 & uv1 = uvs[i + 1]; glm::vec2 & uv2 = uvs[i + 2]; //edges of the triangle : position delta glm::vec3 deltaPos1 = v1 - v0; glm::vec3 deltaPos2 = v2 - v0; //UV delta glm::vec2 deltaUV1 = uv1 - uv0; glm::vec2 deltaUV2 = uv2 - uv0; float r = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV1.y * deltaUV2.x); glm::vec3 tangent = (deltaPos1 * deltaUV2.y - deltaPos2 * deltaUV1.y)*r; glm::vec3 bitangent = (deltaPos2 * deltaUV1.x - deltaPos1*deltaUV2.x)*r; //삼각형의 모든 세개의 정점을 위해 같은 tangent를 세팅한다. //그것들은 곧 병합될겉이다 tangents.push_back(tangent); tangents.push_back(tangent); tangents.push_back(tangent); //binormals를 위한 같은 것 bitangents.push_back(bitangent); bitangents.push_back(bitangent); bitangents.push_back(bitangent); } // "Going Further" 봐라 for (unsigned int i = 0; i < vertices.size(); i += 1) { glm::vec3 & n = normals[i]; glm::vec3 & t = tangents[i]; glm::vec3 & b = bitangents[i]; //Gram-Schmidt orthogonalize t = glm::normalize(t - n*glm::dot(n, t)); //handedness 계산 if (glm::dot(glm::cross(n, t), b) < 0.0f) { t = t*-1.0f; } } } void initText2D(const char * texturePath) { //텍스쳐 초기화 Text2DTextureID = loadDDS(texturePath); //VBO 초기화 glGenBuffers(1, &Text2DVertexBufferID); glGenBuffers(1, &Text2DUVBufferID); //Shader 초기화 Text2DShaderID = LoadShaders("TextVertexShader.vertexshader", "TextVertexShader.fragmentshader"); //uniforms' IDs 초기화 Text2DUniformID = glGetUniformLocation(Text2DShaderID, "myTextureSampler"); } void printText2D(const char * text, int x, int y, int size) { unsigned int length = strlen(text); //buffer 채우기 std::vector<glm::vec2> vertices; std::vector<glm::vec2> UVs; for (unsigned int i = 0; i < length; i++) { glm::vec2 vertex_up_left = glm::vec2(x + i*size, y + size); glm::vec2 vertex_up_right = glm::vec2(x + i*size+size, y + size); glm::vec2 vertex_down_right = glm::vec2(x + i*size+size, y); glm::vec2 vertex_down_left = glm::vec2(x + i*size, y); vertices.push_back(vertex_up_left); vertices.push_back(vertex_down_left); vertices.push_back(vertex_up_right); vertices.push_back(vertex_down_right); vertices.push_back(vertex_up_right); vertices.push_back(vertex_down_left); char character = text[i]; float uv_x = (character % 16) / 16.0f; float uv_y = (character / 16) / 16.0f; glm::vec2 uv_up_left = glm::vec2(uv_x, uv_y); glm::vec2 uv_up_right = glm::vec2(uv_x + 1.0f / 16.0f, uv_y); glm::vec2 uv_down_right = glm::vec2(uv_x+1.0f/16.0f, (uv_y+1.0f/16.0f)); glm::vec2 uv_down_left = glm::vec2(uv_x, (uv_y+1.0f/16.0f)); UVs.push_back(uv_up_left); UVs.push_back(uv_down_left); UVs.push_back(uv_up_right); UVs.push_back(uv_down_right); UVs.push_back(uv_up_right); UVs.push_back(uv_down_left); glBindBuffer(GL_ARRAY_BUFFER, Text2DVertexBufferID); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec2), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, Text2DUVBufferID); glBufferData(GL_ARRAY_BUFFER, UVs.size() * sizeof(glm::vec2), &UVs[0], GL_STATIC_DRAW); // Bind shader glUseProgram(Text2DShaderID); // Bind texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Text2DTextureID); // Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(Text2DUniformID, 0); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, Text2DVertexBufferID); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); // 2nd attribute buffer : UVs glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, Text2DUVBufferID); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Draw call glDrawArrays(GL_TRIANGLES, 0, vertices.size()); glDisable(GL_BLEND); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); } } void cleanupText2D() { // Delete buffers glDeleteBuffers(1, &Text2DVertexBufferID); glDeleteBuffers(1, &Text2DUVBufferID); // Delete texture glDeleteTextures(1, &Text2DTextureID); // Delete shader glDeleteProgram(Text2DShaderID); } | cs |
'Game > Graphics' 카테고리의 다른 글
OpenGL-Tutorial 18 : Billboards (0) | 2018.07.04 |
---|---|
OpenGL-Tutorial 17 : Rotations (2) | 2018.07.03 |
OpenGL-Tutorial 15 : Lightmaps (0) | 2018.07.02 |
OpenGL-Tutorial 14 : Render To Texture (0) | 2018.07.01 |
OpenGL-Tutorial 13 : Normal Mapping (0) | 2018.06.29 |