跟着cherno手搓游戏引擎【16】Camera和Uniform变量的封装

相机封装:

OrthographicCamera.h:

#pragma once
#include <glm/glm.hpp>
namespace YOTO {class OrthographicCamera{public:OrthographicCamera(float left,float right , float bottom,float top);const glm::vec3& GetPosition()const { return m_Position; }void SetPosition(const glm::vec3& position) { m_Position = position; RecalculateViewMatrix();}float GetRotation()const { return m_Rotation; }void SetRotation(float rotation) {m_Rotation = rotation; RecalculateViewMatrix();}const glm::mat4& GetProjectionMatrix()const { return m_ProjectionMatrix; }const glm::mat4& GetViewMatrix()const { return m_ViewMatrix; }const glm::mat4& GetViewProjectionMatrix()const { return m_ViewProjectionMatrix; }private:void RecalculateViewMatrix();private:glm::mat4 m_ProjectionMatrix;glm::mat4 m_ViewMatrix;glm::mat4 m_ViewProjectionMatrix;glm::vec3 m_Position = { 0.0f ,0.0f ,0.0f };float m_Rotation = 0.0f;};
}

OrthographicCamera.cpp: 

#include "ytpch.h"
#include "OrthographicCamera.h"
#include <glm/gtc/matrix_transform.hpp>
namespace YOTO {OrthographicCamera::OrthographicCamera(float left, float right, float bottom, float top):m_ProjectionMatrix(glm::ortho(left,right,bottom,top)),m_ViewMatrix(1.0f) {m_ViewProjectionMatrix = m_ProjectionMatrix * m_ViewMatrix;}void OrthographicCamera::RecalculateViewMatrix(){glm::mat4 transform = glm::translate(glm::mat4(1.0f), m_Position)*glm::rotate(glm::mat4(1.0f),glm::radians(m_Rotation),glm::vec3(0,0,1));m_ViewMatrix = glm::inverse(transform);m_ViewProjectionMatrix = m_ProjectionMatrix * m_ViewMatrix;}
}

Uniform的封装:

Shader.h:

#pragma once
#include <string>
#include <glm/glm.hpp>
namespace YOTO {class Shader {public:Shader(const std::string& vertexSrc, const std::string& fragmentSrc);~Shader();void Bind()const;void UnBind()const;void UploadUniformMat4(const std::string&name,  const glm::mat4 & matrix);private:uint32_t m_RendererID;}
;
}

Shader.cpp:

#include"ytpch.h"
#include "Shader.h"
#include <glad/glad.h>
#include <YOTO/Log.h>
#include<glm/gtc/type_ptr.hpp>
namespace YOTO {Shader::Shader(const std::string& vertexSrc, const std::string& fragmentSrc){// 1.1.创建顶点着色器对象GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);// Send the vertex shader source code to GL// Note that std::string's .c_str is NULL character terminated.// 1.2.附加顶点着色器源码到顶点着色器对象中const GLchar* source = vertexSrc.c_str();glShaderSource(vertexShader, 1, &source, 0);// 1.3.编译顶点着色器对象glCompileShader(vertexShader);// 1.4.检查是否编译成功GLint isCompiled = 0;glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &isCompiled);if (isCompiled == GL_FALSE) {// 1.4.2编译失败可以打印报错信息GLint maxLength = 0;glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &maxLength);// The maxLength includes the NULL characterstd::vector<GLchar> infoLog(maxLength);glGetShaderInfoLog(vertexShader, maxLength, &maxLength, &infoLog[0]);// We don't need the shader anymore.glDeleteShader(vertexShader);YT_CORE_ERROR("{0}", infoLog.data());YT_CORE_ASSERT(false, "Vertex shader compilation failure!");return;}// 片段着色器一样// 2.1.创建片段着色器对象GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);// Send the fragment shader source code to GL// Note that std::string's .c_str is NULL character terminated.// 2.2.附加片段着色器源码到片段着色器对象中source = fragmentSrc.c_str();glShaderSource(fragmentShader, 1, &source, 0);// 2.3.编译片段着色器对象glCompileShader(fragmentShader);// 2.4.检查是否编译成功glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &isCompiled);if (isCompiled == GL_FALSE) {// 2.4.2编译失败可以打印报错信息GLint maxLength = 0;glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &maxLength);// The maxLength includes the NULL characterstd::vector<GLchar> infoLog(maxLength);glGetShaderInfoLog(fragmentShader, maxLength, &maxLength, &infoLog[0]);// We don't need the shader anymore.glDeleteShader(fragmentShader);// Either of them. Don't leak shaders.glDeleteShader(vertexShader);YT_CORE_ERROR("{0}", infoLog.data());YT_CORE_ASSERT(false, "Fragment shader compilation failure!");return;}// Vertex and fragment shaders are successfully compiled.// Now time to link them together into a program.// Get a program object.// 3.1创建着色器程序对象m_RendererID = glCreateProgram();GLuint program = m_RendererID;// 3.2附加着色器对象给着色器程序对象glAttachShader(program, vertexShader);glAttachShader(program, fragmentShader);// 3.3链接着色器程序对象glLinkProgram(program);// 3.4可以检查链接是否成功// Note the different functions here: glGetProgram* instead of glGetShader*.GLint isLinked = 0;glGetProgramiv(program, GL_LINK_STATUS, (int*)&isLinked);if (isLinked == GL_FALSE) {GLint maxLength = 0;glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength);// The maxLength includes the NULL characterstd::vector<GLchar> infoLog(maxLength);glGetProgramInfoLog(program, maxLength, &maxLength, &infoLog[0]);// We don't need the program anymore.glDeleteProgram(program);// Don't leak shaders either.glDeleteShader(vertexShader);glDeleteShader(fragmentShader);YT_CORE_ERROR("{0}", infoLog.data());YT_CORE_ASSERT(false, "Shader link failure!");return;}// 4.删除着色器对象// Always detach shaders after a successful link.glDetachShader(program, vertexShader);glDetachShader(program, fragmentShader);}Shader::~Shader(){glDeleteProgram(m_RendererID);}void Shader::Bind() const{glUseProgram(m_RendererID);}void Shader::UnBind() const{glUseProgram(0);}void Shader::UploadUniformMat4(const std::string& name, const glm::mat4& matrix){GLint loacation= glGetUniformLocation(m_RendererID, name.c_str());glUniformMatrix4fv(loacation, 1, GL_FALSE,glm::value_ptr(matrix));}
}

进一步封装ShaderUniform:

Renderer.h:

#pragma once
#include"RenderCommand.h"
#include "OrthographicCamera.h"
#include"Shader.h"
namespace YOTO {class Renderer {public:static void BeginScene(OrthographicCamera &camera);static void EndScene();static void Submit(const std::shared_ptr<Shader>& shader, const std::shared_ptr<VertexArray>& vertexArray);inline static RendererAPI::API GetAPI() {return RendererAPI::GetAPI();}private:struct SceneData {glm::mat4 ViewProjectionMatrix;};static SceneData* m_SceneData;};}

Renderer.cpp:

#include"ytpch.h"
#include"Renderer.h"
namespace YOTO {Renderer::SceneData* Renderer::m_SceneData = new	Renderer::SceneData;void Renderer::BeginScene(OrthographicCamera& camera){m_SceneData->ViewProjectionMatrix = camera.GetViewProjectionMatrix();}void Renderer::EndScene(){}void Renderer::Submit( const std::shared_ptr<Shader>& shader,const std::shared_ptr<VertexArray>& vertexArray){shader->Bind();shader->UploadUniformMat4("u_ViewProjection", m_SceneData->ViewProjectionMatrix);vertexArray->Bind();RenderCommand::DrawIndexed(vertexArray);}
}

调用:

Application.h:

#pragma once
#include"Core.h"
#include"Event/Event.h"
#include"Event/ApplicationEvent.h"
#include "YOTO/Window.h"
#include"YOTO/LayerStack.h"
#include"YOTO/ImGui/ImGuiLayer.h"#include <YOTO/Renderer/Shader.h>
#include <YOTO/Renderer/Buffer.h>
#include <YOTO/Renderer/VertexArray.h>#include "YOTO/Renderer/OrthographicCamera.h"
namespace YOTO {class YOTO_API Application{public:Application();virtual ~Application();void Run();void OnEvent(Event &e);void PushLayer(Layer* layer);void PushOverlay(Layer* layer);inline static Application& Get() {return * s_Instance;}inline Window& GetWindow() { return *m_Window; }private:bool  OnWindowClosed(WindowCloseEvent& e);std::unique_ptr<Window>  m_Window;ImGuiLayer *  m_ImGuiLayer;bool m_Running = true;LayerStack m_LayerStack;//unsigned int m_VertexArray;std::shared_ptr<Shader> m_Shader;std::shared_ptr<VertexArray> m_VertexArray;std::shared_ptr<Shader> m_BlueShader;std::shared_ptr<VertexArray> m_SquareVA;OrthographicCamera m_Camera;private:static Application* s_Instance;};//在客户端定义Application* CreateApplication();
}

Application.cpp:

#include"ytpch.h"
#include "Application.h"#include"Log.h"
#include "YOTO/Renderer/Renderer.h"
#include"Input.h"namespace YOTO {
#define BIND_EVENT_FN(x) std::bind(&x, this, std::placeholders::_1)Application* Application::s_Instance = nullptr;Application::Application():m_Camera(-2.0f,2.0f,-2.0f,2.0f){YT_CORE_ASSERT(!s_Instance, "Application需要为空!")s_Instance = this;//智能指针m_Window = std::unique_ptr<Window>(Window::Creat());//设置回调函数m_Window->SetEventCallback(BIND_EVENT_FN(Application::OnEvent));//new一个Layer,放在最后层进行渲染m_ImGuiLayer = new ImGuiLayer();PushOverlay(m_ImGuiLayer);  //unsigned int id;//glGenBuffers(1, &id);uint32_t indices[3] = { 0,1,2 };float vertices[3 * 7] = {-0.5f,-0.5f,0.0f, 0.8f,0.2f,0.8f,1.0f,0.5f,-0.5f,0.0f,  0.2f,0.3f,0.8f,1.0f,0.0f,0.5f,0.0f,   0.8f,0.8f,0.2f,1.0f,};m_VertexArray.reset(VertexArray::Create());std::shared_ptr<VertexBuffer> m_VertexBuffer;m_VertexBuffer.reset(VertexBuffer::Create(vertices, sizeof(vertices)));{BufferLayout setlayout = {{ShaderDataType::Float3,"a_Position"},{ShaderDataType::Float4,"a_Color"}};m_VertexBuffer->SetLayout(setlayout);}m_VertexArray->AddVertexBuffer(m_VertexBuffer);std::shared_ptr<IndexBuffer>m_IndexBuffer;m_IndexBuffer.reset(IndexBuffer::Create(indices, sizeof(indices)/sizeof(uint32_t)));m_VertexArray->AddIndexBuffer(m_IndexBuffer);std::string vertexSource = R"(#version 330 corelayout(location = 0) in vec3 a_Position;layout(location = 1) in vec4 a_Color;uniform mat4 u_ViewProjection;out vec3 v_Position;out vec4 v_Color;void main(){v_Position=a_Position;v_Color=a_Color;gl_Position =u_ViewProjection*vec4( a_Position,1.0);})";//绘制颜色std::string fragmentSource = R"(#version 330 corelayout(location = 0) out vec4 color;in vec3 v_Position;in vec4 v_Color;void main(){color=vec4(v_Color);})";m_Shader.reset(new Shader(vertexSource, fragmentSource));///测试/m_SquareVA.reset(VertexArray::Create());float squareVertices[3 * 4] = {-0.5f,-0.5f,0.0f,0.5f,-0.5f,0.0f, 0.5f,0.5f,0.0f,-0.5f,0.5f,0.0f};std::shared_ptr<VertexBuffer> squareVB;squareVB.reset(VertexBuffer::Create(squareVertices, sizeof(squareVertices)));squareVB->SetLayout({{ShaderDataType::Float3,"a_Position"}});m_SquareVA->AddVertexBuffer(squareVB);uint32_t squareIndices[6] = { 0,1,2,2,3,0 };std::shared_ptr<IndexBuffer> squareIB; squareIB.reset((IndexBuffer::Create(squareIndices, sizeof(squareIndices) / sizeof(uint32_t))));m_SquareVA->AddIndexBuffer(squareIB);//测试:std::string BlueShaderVertexSource = R"(#version 330 corelayout(location = 0) in vec3 a_Position;uniform mat4 u_ViewProjection;out vec3 v_Position;void main(){v_Position=a_Position;gl_Position =u_ViewProjection*vec4( a_Position,1.0);})";//绘制颜色std::string BlueShaderFragmentSource = R"(#version 330 corelayout(location = 0) out vec4 color;in vec3 v_Position;void main(){color=vec4(0.2,0.3,0.8,1.0);})";m_BlueShader.reset(new Shader(BlueShaderVertexSource, BlueShaderFragmentSource));}Application::~Application() {}/// <summary>/// 所有的Window事件都会在这触发,作为参数e/// </summary>/// <param name="e"></param>void Application::OnEvent(Event& e) {//根据事件类型绑定对应事件EventDispatcher dispatcher(e);dispatcher.Dispatch<WindowCloseEvent>(BIND_EVENT_FN(Application::OnWindowClosed));//输出事件信息YT_CORE_INFO("Application:{0}",e);for (auto it = m_LayerStack.end(); it != m_LayerStack.begin();) {(*--it)->OnEvent(e);if (e.m_Handled)break;}}bool Application::OnWindowClosed(WindowCloseEvent& e) {m_Running = false;return true;}void Application::Run() {WindowResizeEvent e(1280, 720);if (e.IsInCategory(EventCategoryApplication)) {YT_CORE_TRACE(e);}if (e.IsInCategory(EventCategoryInput)) {YT_CORE_ERROR(e);}while (m_Running){RenderCommand::SetClearColor({0.2f, 0.2f, 0.2f, 1.0f});RenderCommand::Clear();m_Camera.SetPosition({0.5f,0.5f, 0.0f });m_Camera.SetRotation(45);Renderer::BeginScene(m_Camera);{/*	m_BlueShader->Bind();m_BlueShader->UploadUniformMat4("u_ViewProjection",m_Camera.GetViewProjectionMatrix());*/Renderer::Submit(m_BlueShader,m_SquareVA);/*	m_Shader->Bind();m_Shader->UploadUniformMat4("u_ViewProjection", m_Camera.GetViewProjectionMatrix());*/Renderer::Submit(m_Shader,m_VertexArray);Renderer::EndScene();}for (Layer* layer : m_LayerStack) {layer->OnUpdate();}//将ImGui的刷新放到APP中,与Update分开m_ImGuiLayer->Begin();for (Layer* layer : m_LayerStack) {layer->OnImGuiRender();}m_ImGuiLayer->End();m_Window->OnUpdate();}}void Application::PushLayer(Layer* layer) {m_LayerStack.PushLayer(layer);layer->OnAttach();}void Application::PushOverlay(Layer* layer) {m_LayerStack.PushOverlay(layer);layer->OnAttach();}
}

测试:

cool!

目前代码比较潦草,甚至有些地方没有注释。计划在渲染出第一个兰伯特模型时对代码架构进行总结。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/660108.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

对同一文件多次mmap

abstract 问&#xff1a;对同一个文件多次mmap&#xff0c;返回的地址相同吗? 答&#xff1a;不相同 code #ifdef __linux__#include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> …

Vue-49、Vue技术实现动画效果

1、首先&#xff0c;在Vue项目中的src/components文件夹下创建一个名为AnimatedBox.vue的文件。 2、编辑AnimatedBox.vue文件&#xff0c;添加以下代码&#xff1a; <template><div class"animated-box" click"toggle"><transition name&q…

【C++】STL优先级队列(priority_queue)

priority_queue 基本介绍 priority_queue就是优先级队列。其头文件就是queue&#xff0c;但是队列和优先级队列关系不大&#xff0c;两个是不同的数据结构。但二者都是适配器&#xff0c;容器适配器。 优先级队列中存放的数据是有优先级的。 其内部有以下成员方法&#xff0c…

使用post-css实现移动端适配

介绍移动端适配以及适配方案 适配原因 移动端不像PC端,有足够大的屏幕展示较多的内容不同的移动端设备&#xff0c;有不同屏幕宽度同样大小的页面元素在不同屏幕宽度设备展示时&#xff0c;布局就会错乱有些元素没有展示在可视范围内有些元素不能撑满整个屏幕&#xf…

【Linux】初始进程地址空间

最近&#xff0c;我发现了一个超级强大的人工智能学习网站。它以通俗易懂的方式呈现复杂的概念&#xff0c;而且内容风趣幽默。我觉得它对大家可能会有所帮助&#xff0c;所以我在此分享。点击这里跳转到网站。 目录 一、再谈fork二、程序地址空间2.1代码验证 三、虚拟地址&am…

成熟的汽车制造供应商协同平台 要具备哪些功能特性?

汽车行业是一个产业链长且“重”的行业&#xff0c;整个业务流程包括了研发、设计、采购、库存、生产、销售、售后等一系列环节&#xff0c;在每一个环节都涉及到很多信息交换的需求。对内要保证研发、采购、营销等业务环节信息流通高效安全&#xff0c;对外要与上、下游合作伙…

Python编程实验一:流程控制结构

目录 一、实验目的与要求 二、实验内容 三、主要程序清单和程序运行结果 第1题 第2题 第3题 第4题 四、实验结果分析与体会 一、实验目的与要求 &#xff08;1&#xff09;通过本次实验&#xff0c;学生应掌握多分支语句 if …elif…else结构的用法&#xff1b; &…

vue3/vue2中自定义指令不可输入小数点.

import { directive } from vueconst noDecimal {mounted(el) {el.addEventListener(keypress, (e) > {if (e.key .) {e.preventDefault() }})} }// 使用自定义指令 directive(no-decimal, noDecimal)使用 标签上添加 v-no-decimal <el-input…

重磅!讯飞星火V3.5正式发布,3大核心能力超GPT-4 Turbo!

1月30日&#xff0c;科大讯飞召开星火认知大模型V3.5升级发布会&#xff0c;这是国内首个基于全国产算力训练的多模态认知大模型。科大讯飞董事长刘庆峰先生、研究院院长刘聪先生出席了大会&#xff0c;并对最新产品进行了多维度解读。 讯飞星火V3.5的7大核心能力实现全面大幅…

【Python】P2 Python3 安装使用

目录 新手教程开发教程 本篇博客文章划分为两个主要部分&#xff1a; 【新手教程】旨在为 Python 编程的新手提供指导&#xff0c;适合于初学者入门&#xff0c;但不太适合用于开发大型项目&#xff1b;【开发教程】则面向那些已经有项目开发经验或者希望迅速提升开发技能的读…

BUUCTF-Real-[ThinkPHP]5-Rce

1、ThinkPHP检测工具 https://github.com/anx0ing/thinkphp_scan 漏洞检测 通过漏洞检测&#xff0c;我们发现存在rce漏洞&#xff01; 2、漏洞利用 ---- [!] Name: Thinkphp5 5.0.22/5.1.29 Remote Code Execution VulnerabilityScript: thinkphp5022_5129.pyUrl: http://n…

新春营销不间断,AI 整活更省心

新年、春节历来都是营销的大热节点&#xff0c;各种好物集、年货节、送礼清单比比皆是。这些新鲜玩法的背后是大量的品牌内容「弹药库」。 然而&#xff0c;品牌想在竞争激烈的新春季刷满存在感&#xff0c;并非易事。一方面&#xff0c;节日期间&#xff0c;消费者对于内容的审…

Tensorflow2.0笔记 - where,scatter_nd, meshgrid相关操作

本笔记记录tf.where进行元素位置查找&#xff0c;scatter_nd用于指派元素到tensor的特定位置&#xff0c;meshgrid用作绘图的相关操作。 import tensorflow as tf import numpy as np import matplotlib.pyplot as plttf.__version__#where操作查找元素位置 #输入的tensor是Tr…

【蓝桥杯冲冲冲】动态规划学习 [NOIP2003 提高组] 加分二叉树

【蓝桥杯冲冲冲】动态规划学习 [NOIP2003 提高组] 加分二叉树 蓝桥杯备赛 | 洛谷做题打卡day24 文章目录 蓝桥杯备赛 | 洛谷做题打卡day24[NOIP2003 提高组] 加分二叉树题目描述输入格式输出格式样例 #1样例输入 #1样例输出 #1 提示数据规模与约定思路 题解代码我的一些话 [NOI…

Python数据可视化库之holoviews使用详解

概要 数据可视化在各个领域中都起着至关重要的作用&#xff0c;无论是用于数据分析、科学研究、教育还是决策支持。Python作为一门强大的数据科学工具&#xff0c;拥有众多的可视化库。其中&#xff0c;HoloViews是一个备受欢迎的库&#xff0c;它可以轻松创建交互性可视化&am…

PE文件结构 安全分析与恶意软件研究 逆向工程 优化与性能调整 兼容性与移植性分析

了解PE&#xff08;Portable Executable&#xff0c;可移植可执行文件&#xff09;文件结构有多个用途 对于软件开发、安全分析、逆向工程等领域的专业人士来说尤其重要。PE文件格式是Windows操作系统中用于可执行文件、动态链接库&#xff08;DLLs&#xff09;、以及其他文件…

安全防御第五次作业

拓扑图及要求如下&#xff1a; 实验注意点&#xff1a; 先配置双机热备&#xff0c;再来配置安全策略和NAT两台双机热备的防火墙的接口号必须一致双机热备时&#xff0c;请确保vrrp配置的虚拟IP与下面的ip在同一网段如果其中一台防火墙有过配置&#xff0c;最好清空或重启&…

C语言指针学习(1)

前言 指针是C语言中一个重要概念&#xff0c;也是C语言的一个重要特色&#xff0c;正确而灵活地运用指针可以使程序简洁、紧凑、高效。每一个学习和使用C语言的人都应当深入的学习和掌握指针&#xff0c;也可以说不掌握指针就没有掌握C语言的精华。 一、什么是指针 想弄清楚什…

【Leetcode 514】自由之路 —— 动态规划

514. 自由之路 电子游戏“辐射4”中&#xff0c;任务 “通向自由” 要求玩家到达名为 “Freedom Trail Ring” 的金属表盘&#xff0c;并使用表盘拼写特定关键词才能开门。 给定一个字符串ring&#xff0c;表示刻在外环上的编码&#xff1b;给定另一个字符串key&#xff0c;表…

2024Node.js零基础教程(小白友好型),nodejs新手到高手,(三)NodeJS入门——http协议

033_HTTP协议_初识HTTP协议 hello&#xff0c;大家好&#xff0c;这个小节我们来认识一下 http协议。 http是几个单词的首字母拼写&#xff0c;全称为Hypertext Transfer Protocol 译为超文本传输协议&#xff0c;那么这个http协议是互联网上应用最广泛的协议之一。顺便说一下…