3.1: Texture (3D)
Complete Source Code:
Main.cpp
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <iostream>
#include <vector>
#include <string>
#include "Shader.h"
using namespace std;
using namespace glm;
// main functions
void Initialize();
void Render();
void CleanUp();
// callbacks
void cursor_position_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
// variables
GLFWwindow* window = nullptr;
GLuint program = 0;
GLuint vertexshader = 0;
GLuint fragmentshader = 0;
GLuint vertexarray = 0;
GLuint vertexbuffer = 0;
GLuint texture = 0;
// structures
struct Vertex {
vec3 Position;
vec2 TexCoord;
};
struct {
vec3 Position{ 2, 0, 5 };
vec3 Forward{ 0, 0, -1 };
vec3 Up{ 0, 1, 0 };
} Camera;
int main(void)
{
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
/* Set callbacks */
glfwSetCursorPosCallback(window, cursor_position_callback);
glfwSetScrollCallback(window, scroll_callback);
/* Initialize GLEW */
if (glewInit() != GLEW_OK)
{
glfwTerminate();
return -1;
}
Initialize();
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
Render();
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
CleanUp();
glfwTerminate();
return 0;
}
void Initialize()
{
// settings
glClearColor(0.3f, 0.3f, 0.3f, 0);
glEnable(GL_DEPTH_TEST);
// create all objects
program = glCreateProgram();
vertexshader = glCreateShader(GL_VERTEX_SHADER);
fragmentshader = glCreateShader(GL_FRAGMENT_SHADER);
glGenVertexArrays(1, &vertexarray);
glGenBuffers(1, &vertexbuffer);
glGenTextures(1, &texture);
// shader source code
string vertexshader_source = {
"#version 450 core\n"
"in layout (location = 0) vec3 in_position;"
"in layout (location = 1) vec2 in_texcoord;"
"uniform mat4 MVP = mat4(1);"
"out vec2 texcoord;"
"void main() {"
"gl_Position = MVP * vec4(in_position, 1);"
"texcoord = in_texcoord;"
"}"
};
string fragmentshader_source = {
"#version 450 core\n"
"in vec2 texcoord;"
"uniform sampler3D tex1;"
"uniform float depth = 0.0f;"
"out layout (location = 0) vec4 out_color;"
"void main() {"
"out_color = texture(tex1, vec3(texcoord, depth));"
"}"
};
// compile shaders and link program
CompileShader(vertexshader, vertexshader_source);
CompileShader(fragmentshader, fragmentshader_source);
LinkProgram(program, { vertexshader, fragmentshader });
// setup vertexarray
glBindVertexArray(vertexarray);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, false, sizeof(Vertex), (void*)(sizeof(float) * 0));
glVertexAttribPointer(1, 2, GL_FLOAT, false, sizeof(Vertex), (void*)(sizeof(float) * 3));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindVertexArray(0);
// setup vertexbuffer
vector<Vertex> vertices = {
{ { -1, -1, 0 },{ 0, 0 } },
{ { +1, -1, 0 },{ 1, 0 } },
{ { +1, +1, 0 },{ 1, 1 } },
{ { -1, +1, 0 },{ 0, 1 } },
};
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// setup texture
unsigned int texturewidth = 2;
unsigned int textureheight = 3;
unsigned int texturedepth = 4;
unsigned char texturedata[] = {
// 1st layer (red / cyan)
0x50, 0x00, 0x00, 0xFF, 0x00, 0x50, 0x50, 0xFF,
0xA0, 0x00, 0x00, 0xFF, 0x00, 0xA0, 0xA0, 0xFF,
0xFF, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF,
// 2nd layer (green / magenta)
0x00, 0x50, 0x00, 0xFF, 0x50, 0x00, 0x50, 0xFF,
0x00, 0xA0, 0x00, 0xFF, 0xA0, 0x00, 0xA0, 0xFF,
0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF,
// 3rd layer (blue / yellow)
0x00, 0x00, 0x50, 0xFF, 0x50, 0x50, 0x00, 0xFF,
0x00, 0x00, 0xA0, 0xFF, 0xA0, 0xA0, 0x00, 0xFF,
0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF,
// 4th layer (black / grey / white)
0x00, 0x00, 0x00, 0xFF, 0x30, 0x30, 0x30, 0xFF,
0x60, 0x60, 0x60, 0xFF, 0x90, 0x90, 0x90, 0xFF,
0xB0, 0xB0, 0xB0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
};
glBindTexture(GL_TEXTURE_3D, texture);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA8, texturewidth, textureheight, texturedepth, 0, GL_RGBA, GL_UNSIGNED_BYTE, texturedata);
glBindTexture(GL_TEXTURE_3D, 0);
// connect texture to sampler in fragmentshader
unsigned int texture_unit = 2;
int location = glGetUniformLocation(program, "tex1");
glProgramUniform1i(program, location, texture_unit);
glBindTextureUnit(texture_unit, texture);
}
void Render()
{
// camera matrix:
mat4 ViewProjection =
perspective(radians(45.0f), 1.33f, 0.1f, 100.0f) *
lookAt(Camera.Position, Camera.Position + Camera.Forward, Camera.Up);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(program);
glBindVertexArray(vertexarray);
// draw 4 quads:
for (float depth = 0.0f; depth < 1.0f; depth += 0.25f)
{
// set quad position
int location = glGetUniformLocation(program, "MVP");
glProgramUniformMatrix4fv(program, location, 1, false, value_ptr(ViewProjection * translate(vec3(0, 0, depth * 3))));
// set texture layer
location = glGetUniformLocation(program, "depth");
glUniform1f(location, depth);
// draw textured quad
glDrawArrays(GL_QUADS, 0, 4);
}
glBindVertexArray(0);
glUseProgram(0);
}
void CleanUp()
{
// destroy all abjects
glDeleteProgram(program);
glDeleteShader(vertexshader);
glDeleteShader(fragmentshader);
glDeleteVertexArrays(1, &vertexarray);
glDeleteBuffers(1, &vertexbuffer);
glDeleteTextures(1, &texture);
}
void cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
{
static double xpos_previous = xpos, ypos_previous = ypos;
// delta
double xpos_delta = xpos - xpos_previous;
double ypos_delta = ypos - ypos_previous;
// rotate camera
float angle = xpos_delta * -0.05f;
Camera.Forward = rotate(Camera.Forward, angle, Camera.Up);
xpos_previous = xpos;
ypos_previous = ypos;
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
// move camera
if (yoffset > 0)
Camera.Position += Camera.Forward * 0.5f;
if (yoffset < 0)
Camera.Position -= Camera.Forward * 0.5f;
}
Shader.h
#pragma once
#include <string>
#include <list>
// shader functions
std::string LoadTextFile(const std::string& filepath);
std::string ShaderTypeName(unsigned int shader);
bool CompileShader(unsigned int shader, const std::string& sourcecode);
std::string ShaderInfoLog(unsigned int shader);
bool LinkProgram(unsigned int program, const std::list<unsigned int>& shaderlist);
std::string ProgramInfoLog(unsigned int program);
Shader.cpp
#include "Shader.h"
#include <iostream>
#include <fstream>
#include <GL/glew.h>
std::string LoadTextFile(const std::string & filepath)
{
std::string result(""), line;
std::fstream f(filepath, std::ios::in);
while (f.good())
{
std::getline(f, line);
result += line + '\n';
}
return result;
}
std::string ShaderTypeName(unsigned int shader)
{
if (glIsShader(shader))
{
int type;
glGetShaderiv(shader, GL_SHADER_TYPE, &type);
if (type == GL_VERTEX_SHADER)
return "Vertex Shader";
if (type == GL_TESS_CONTROL_SHADER)
return "Tessellation Control Shader";
if (type == GL_TESS_EVALUATION_SHADER)
return "Tessellation Evaluation Shader";
if (type == GL_GEOMETRY_SHADER)
return "Geometry Shader";
if (type == GL_FRAGMENT_SHADER)
return "Fragment Shader";
if (type == GL_COMPUTE_SHADER)
return "Compute Shader";
}
return "invalid shader";
}
bool CompileShader(unsigned int shader, const std::string& sourcecode)
{
if (!glIsShader(shader))
{
std::cout << "ERROR: shader compilation failed, no valid shader specified" << std::endl;
return false;
}
if (sourcecode.empty())
{
std::cout << "ERROR: shader compilation failed, no source code specified (" << ShaderTypeName(shader) << ")" << std::endl;
return false;
}
// array of source code components
const char* sourcearray[] = { sourcecode.c_str() };
// set source code
glShaderSource(shader, 1, sourcearray, NULL);
// compile shaders
glCompileShader(shader);
// check compile status
int status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
// successfully compiled shader
if (status == GL_TRUE)
return true;
// show compile errors
std::cout << "ERROR: shader compilation failed (" << ShaderTypeName(shader) << ")" << std::endl << ShaderInfoLog(shader) << std::endl;
return false;
}
std::string ShaderInfoLog(unsigned int shader)
{
if (glIsShader(shader))
{
int logsize;
char infolog[1024] = { 0 };
glGetShaderInfoLog(shader, 1024, &logsize, infolog);
return std::string(infolog);
}
return "invalid shader";
}
bool LinkProgram(unsigned int program, const std::list<unsigned int>& shaderlist)
{
if (!glIsProgram(program))
{
std::cout << "ERROR: shader linking failed, no valid program specified" << std::endl;
return false;
}
// attach all shaders to the program
for (auto& shader : shaderlist)
{
if (glIsShader(shader))
glAttachShader(program, shader);
}
// link program
glLinkProgram(program);
// detach all shaders again
for (auto& shader : shaderlist)
{
if (glIsShader(shader))
glDetachShader(program, shader);
}
int status;
glGetProgramiv(program, GL_LINK_STATUS, &status);
// successfully linked program
if (status == GL_TRUE)
return true;
// show link errors
std::cout << "ERROR: shader linking failed" << std::endl << ProgramInfoLog(program) << std::endl;
return false;
}
std::string ProgramInfoLog(unsigned int program)
{
if (glIsProgram(program))
{
int logsize;
char infolog[1024] = { 0 };
glGetProgramInfoLog(program, 1024, &logsize, infolog);
return std::string(infolog);
}
return "invalid program";
}