From ca2835943ca4327ad08b54af480e0c6333df201f Mon Sep 17 00:00:00 2001 From: talha Date: Mon, 22 Apr 2024 03:38:29 +0500 Subject: Completed main levels to progress to text-rendering and 2d development. - Only lessons left are geometry shaders and anti-aliasing - will get to those later on soon - need to do text rendering now --- source/lessons/uniform buffer objects/main.cpp | 1405 ++++++++++++++++++++++++ 1 file changed, 1405 insertions(+) create mode 100644 source/lessons/uniform buffer objects/main.cpp (limited to 'source/lessons/uniform buffer objects/main.cpp') diff --git a/source/lessons/uniform buffer objects/main.cpp b/source/lessons/uniform buffer objects/main.cpp new file mode 100644 index 0000000..889536f --- /dev/null +++ b/source/lessons/uniform buffer objects/main.cpp @@ -0,0 +1,1405 @@ +#include +#include +#include +#include +#include +#include +#include + +#define STB_IMAGE_IMPLEMENTATION +#include "stb_image.h" + +/* @lookup: +* - understand kernals, how they work and how they affect post processing +* - Check to see why it is necessary to do glBindTexture() +* - understand the difference between binding textures, and activating a texture unit +* - I do not understand how floating point numbers work, so I should probably look into that. +* - The normal matrix calculation in the fragment shader for the object affected by light has been mainly copied. +* I have tried to understand the formula, and whilst it made some sense, it is not fully clear to me, and I cannot picture it yet. +* Revisit the derivation for the normal matrix some time in the future. +* - Lookup the derivation of the formula for reflecting a vector about a normal. I am doing that for specular lighting, but the learnopengl tutorial +* just uses a glsl reflect formula, and at the time of writing it is also very late so I am not in the mood or position to look into it at present. +* - One of the things I have observed with specular lights is that the circle/specular highlight follows the camera (me) when I move. I would like to figure +* out a way by which this does not happen and it remains fixed on the object, at the angle at which it hits. All of this will be made complicated by the fact +* that ofcourse everything is actually happening from the cameras' perspective. I would still love to figure this out. +*/ + +typedef uint8_t u8; +typedef uint16_t u16; +typedef uint32_t u32; +typedef uint64_t u64; + +typedef int8_t s8; +typedef int16_t s16; +typedef int32_t s32; +typedef int64_t s64; + +typedef float r32; +typedef double r64; + +typedef u8 b8; + +#include "math.h" + +// =========== Shader Loading ============= + +unsigned int gl_create_vertex_shader(char* vertex_shader_source) +{ + unsigned int vertex_shader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL); + glCompileShader(vertex_shader); + + int success; + char info_log[512]; + glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success); + if (!success) + { + glGetShaderInfoLog(vertex_shader, 512, NULL, info_log); + printf("================================\n"); + printf("vertex shader compilation failed:\n%s\n", info_log); + } + + return vertex_shader; +} + +unsigned int gl_create_fragment_shader(char* fragment_shader_source) +{ + unsigned int fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL); + glCompileShader(fragment_shader); + + int success; + char info_log[512]; + glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success); + if (!success) + { + glGetShaderInfoLog(fragment_shader, 512, NULL, info_log); + printf("================================\n"); + printf("fragment shader compilation failed:\n%s\n", info_log); + } + + return fragment_shader; +} + +unsigned int gl_create_shader_program(unsigned int vertex_shader, unsigned int fragment_shader) +{ + unsigned int shader_program = glCreateProgram(); + + glAttachShader(shader_program, vertex_shader); + glAttachShader(shader_program, fragment_shader); + glLinkProgram(shader_program); + + int success; + char info_log[512]; + glGetProgramiv(shader_program, GL_LINK_STATUS, &success); + if (!success) + { + glGetProgramInfoLog(shader_program, 512, NULL, info_log); + printf("================================\n"); + printf("shader program linking failed:\n%s\n", info_log); + } + + glDeleteShader(vertex_shader); + glDeleteShader(fragment_shader); + + return shader_program; +} + +unsigned int gl_shader_program(char* vertex_shader_source, char* fragment_shader_source) +{ + unsigned int vertex_shader = gl_create_vertex_shader(vertex_shader_source); + unsigned int fragment_shader = gl_create_fragment_shader(fragment_shader_source); + unsigned int shader_program = gl_create_shader_program(vertex_shader, fragment_shader); + + return shader_program; +} + +Mat4 camera_create4m(Vec3 camera_pos, Vec3 camera_look, Vec3 camera_up) +{ + // @note: We do this because this allows the camera to have the axis it looks at + // inwards be the +z axis. + // If we did not do this, then the inward axis the camera looks at would be negative. + // I am still learning from learnopengl.com but I imagine that this was done for conveniences' sake. + Vec3 camera_forward_dir = normalize3v(subtract3v(camera_pos, camera_look)); + Vec3 camera_right_dir = normalize3v(cross_multiply3v(camera_up, camera_forward_dir)); + Vec3 camera_up_dir = normalize3v(cross_multiply3v(camera_forward_dir, camera_right_dir)); + + Mat4 res = lookat4m(camera_up_dir, camera_forward_dir, camera_right_dir, camera_pos); + + return res; +} + +Vec3 camera_look_around(r32 angle_pitch, r32 angle_yaw) +{ + Vec3 camera_look = {0.0}; + camera_look.x = cosf(angle_yaw) * cosf(angle_pitch); + camera_look.y = sinf(angle_pitch); + camera_look.z = sinf(angle_yaw) * cosf(angle_pitch); + camera_look = normalize3v(camera_look); + + return camera_look; +} + +s32 gl_load_texture(u32 texture_id, const char* path) +{ + s32 width, height, nrChannels; + unsigned char *data = stbi_load(path, &width, &height, &nrChannels, 0); + if (data) + { + GLenum format; + if (nrChannels == 1) + format = GL_RED; + else if (nrChannels == 3) + format = GL_RGB; + else if (nrChannels == 4) + format = GL_RGBA; + + glBindTexture(GL_TEXTURE_2D, texture_id); + glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); + glGenerateMipmap(GL_TEXTURE_2D); + + 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_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + stbi_image_free(data); + } + else + { + printf("failed to load image texture at path: %s", path); + stbi_image_free(data); + } + + return texture_id; +} + +// =================== Model Loading ======================== +// This section contains a whole host of things: +// 1. classes +// 2. std::vectors +// 3. std::strings +// that I have only used as a glue for I did not know if I had the model loading setup properly. +// @todo: replace these things eventually. For now the goal is to complete learnopengl + +s32 TextureFromFile(const char* filepath, std::string directory) +{ + // @note: this function is stupid as it already became outdated as I needed to tweak the parameters + // for wrapping. Either those become function parameters (Which makes sense I guess) or I look at + // exactly what steps I am reusing and just make that a function so the function is called fewer times. + // + // I am guessing this won't look good from a design point of view for all those jobs and postings, even if + // this may be the simpler and faster thing to do, albeit at the cost of typing. + std::string filename = std::string(filepath); + filename = directory + '/' + filename; + + u32 texid; + glGenTextures(1, &texid); + + s32 width, height, nrChannels; + unsigned char *data = stbi_load(filename.c_str(), &width, &height, &nrChannels, 0); + if (data) + { + GLenum format; + if (nrChannels == 1) + format = GL_RED; + else if (nrChannels == 3) + format = GL_RGB; + else if (nrChannels == 4) + format = GL_RGBA; + + glBindTexture(GL_TEXTURE_2D, texid); + glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); + glGenerateMipmap(GL_TEXTURE_2D); + + 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_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + stbi_image_free(data); + } + else + { + printf("failed to load image texture at path: %s", filepath); + stbi_image_free(data); + } + + return texid; +} + +enum TextureType { TextureDiffuse=0, TextureSpecular }; + +struct Vertex { + Vec3 position; + Vec3 normal; + Vec2 texture; +}; + +struct Texture { + u32 id; + enum TextureType type; + std::string fname; +}; + +class Mesh { + public: + std::vector vertices; + std::vector indices; + std::vector textures; + + u32 vao; + u32 vbo; + u32 ebo; + + Mesh(std::vector vertices, std::vector indices, std::vector textures) + { + this->vertices = vertices; + this->indices = indices; + this->textures = textures; + + // setup mesh shader stuff + glGenVertexArrays(1, &vao); + glGenBuffers(1, &vbo); + glGenBuffers(1, &ebo); + + glBindVertexArray(vao); + + glBindBuffer(GL_ARRAY_BUFFER, vbo); + glBufferData(GL_ARRAY_BUFFER, this->vertices.size() * sizeof(struct Vertex), &(this->vertices[0]), GL_STATIC_DRAW); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(u32), &(this->indices[0]), GL_STATIC_DRAW); + + // position + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); + // normal + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, normal)); + // texture + glEnableVertexAttribArray(2); + glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, texture)); + + glBindVertexArray(0); + } + + void draw(u32 shader_program) + { + glUseProgram(shader_program); + + u32 diffuse_num = 1; + u32 specular_num = 1; + char tex_unit_name[64]; + // set shininess + s32 mat_shine_loc = glGetUniformLocation(shader_program, "material.shininess"); + glUniform1f(mat_shine_loc, 32.0f); + + for (u32 i=0; i loaded_textures; + std::vector meshes; + std::string directory; + + void load_model(std::string path); + void process_node(aiNode *node, const aiScene *scene); + Mesh process_mesh(aiMesh *mesh, const aiScene *scene); + std::vector load_material_textures(aiMaterial *mat, aiTextureType type, TextureType type_name); +}; + +void Model::draw(u32 shader_program) +{ + for (int i=0; i < meshes.size(); i++) + { + meshes[i].draw(shader_program); + } +} + +void Model::load_model(std::string path) +{ + Assimp::Importer import; + const aiScene *scene = import.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs); + + if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) + { + printf("error loading model :%s\n", import.GetErrorString()); + return; + } + + directory = path.substr(0, path.find_last_of('/')); + process_node(scene->mRootNode, scene); +} + +void Model::process_node(aiNode *node, const aiScene *scene) +{ + for (int i=0; i < node->mNumMeshes; i++) + { + aiMesh *mesh = scene->mMeshes[node->mMeshes[i]]; + meshes.push_back(process_mesh(mesh, scene)); + } + + for (int i=0; imNumChildren; i++) + { + process_node(node->mChildren[i], scene); + } +} + +Mesh Model::process_mesh(aiMesh *mesh, const aiScene *scene) +{ + std::vector vertices; + std::vector indices; + std::vector textures; + + for (u32 i=0; i < mesh->mNumVertices; i++) + { + Vec3 position; + position.x = mesh->mVertices[i].x; + position.y = mesh->mVertices[i].y; + position.z = mesh->mVertices[i].z; + + Vec3 normal; + normal.x = mesh->mNormals[i].x; + normal.y = mesh->mNormals[i].y; + normal.z = mesh->mNormals[i].z; + + Vec2 texture = {0, 0}; + if (mesh->mTextureCoords[0]) + { + texture.x = mesh->mTextureCoords[0][i].x; + texture.y = mesh->mTextureCoords[0][i].y; + } + + struct Vertex vertex; + vertex.position = position; + vertex.normal = normal; + vertex.texture = texture; + + vertices.push_back(vertex); + } + // process indices + for (u32 i = 0; i < mesh->mNumFaces; i++) + { + aiFace face = mesh->mFaces[i]; + for(u32 j = 0; j < face.mNumIndices; j++) + { + indices.push_back(face.mIndices[j]); + } + } + // process material + if (mesh->mMaterialIndex >= 0) + { + aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex]; + std::vector diffuse_maps = load_material_textures(material, aiTextureType_DIFFUSE, TextureDiffuse); + textures.insert(textures.end(), diffuse_maps.begin(), diffuse_maps.end()); + std::vector specular_maps = load_material_textures(material, aiTextureType_SPECULAR, TextureSpecular); + textures.insert(textures.end(), specular_maps.begin(), specular_maps.end()); + } + + return Mesh(vertices, indices, textures); +} + +std::vector Model::load_material_textures(aiMaterial *mat, aiTextureType type, TextureType tex_type) +{ + std::vector textures; + for(u32 i=0; iGetTextureCount(type); i++) + { + bool load_texture = true; + aiString str; + mat->GetTexture(type, i, &str); + const char* fname = str.C_Str(); + + for (s32 j=0; j