当前位置: 首页 > news >正文

跟着cherno手搓游戏引擎【22】CameraController、Resize

前置:

YOTO.h: 

#pragma once//用于YOTO APP#include "YOTO/Application.h"
#include"YOTO/Layer.h"
#include "YOTO/Log.h"#include"YOTO/Core/Timestep.h"#include"YOTO/Input.h"
#include"YOTO/KeyCode.h"
#include"YOTO/MouseButtonCodes.h"
#include "YOTO/OrthographicCameraController.h"#include"YOTO/ImGui/ImGuiLayer.h"//Renderer
#include"YOTO/Renderer/Renderer.h"
#include"YOTO/Renderer/RenderCommand.h"#include"YOTO/Renderer/Buffer.h"
#include"YOTO/Renderer/Shader.h"
#include"YOTO/Renderer/Texture.h"
#include"YOTO/Renderer/VertexArray.h"#include"YOTO/Renderer/OrthographicCamera.h"//入口点
#include"YOTO/EntryPoint.h"

 添加方法:

OrthographicCamera.h:

#pragma once
#include <glm/glm.hpp>
namespace YOTO {class OrthographicCamera{public:OrthographicCamera(float left, float right, float bottom, float top);void SetProjection(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::SetProjection(float left, float right, float bottom, float top) {m_ProjectionMatrix = glm::ortho(left, right, bottom, top);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;}
}

封装控制类:

OrthographicCameraController.h: 

#pragma once
#include "YOTO/Renderer/OrthographicCamera.h"
#include"YOTO/Core/Timestep.h"
#include "YOTO/Event/ApplicationEvent.h"
#include "YOTO/Event/MouseEvent.h"
namespace YOTO {class OrthographicCameraController {public:OrthographicCameraController(float aspectRatio, bool rotation=false );//0,1280void OnUpdate(Timestep ts);void OnEvent(Event& e);OrthographicCamera& GetCamera() {return m_Camera;}const OrthographicCamera& GetCamera()const  {return m_Camera;}private:bool OnMouseScrolled(MouseScrolledEvent &e);bool OnWindowResized(WindowResizeEvent& e);private:float m_AspectRatio;//横纵比float m_ZoomLevel = 1.0f;OrthographicCamera m_Camera;bool m_Rotation;glm::vec3 m_CameraPosition = {0.0f,0.0f,0.0f};float m_CameraRotation = 0.0f;float m_CameraTranslationSpeed = 1.0f, m_CameraRotationSpeed = 180.0f;};
}

 OrthographicCameraController.cpp: 

#include "ytpch.h"
#include "OrthographicCameraController.h"
#include"YOTO/Input.h"
#include <YOTO/KeyCode.h>
namespace YOTO {OrthographicCameraController::OrthographicCameraController(float aspectRatio, bool rotation):m_AspectRatio(aspectRatio),m_Camera(-m_AspectRatio*m_ZoomLevel,m_AspectRatio*m_ZoomLevel,-m_ZoomLevel,m_ZoomLevel),m_Rotation(rotation){}void OrthographicCameraController::OnUpdate(Timestep ts){if (Input::IsKeyPressed(YT_KEY_A)) {m_CameraPosition.x -= m_CameraTranslationSpeed * ts;}else if (Input::IsKeyPressed(YT_KEY_D)) {m_CameraPosition.x += m_CameraTranslationSpeed * ts;}if (Input::IsKeyPressed(YT_KEY_S)) {m_CameraPosition.y -= m_CameraTranslationSpeed * ts;}else if (Input::IsKeyPressed(YT_KEY_W)) {m_CameraPosition.y += m_CameraTranslationSpeed * ts;}if (m_Rotation) {if (Input::IsKeyPressed(YT_KEY_Q)) {m_CameraRotation += m_CameraRotationSpeed * ts;}else if (Input::IsKeyPressed(YT_KEY_E)) {m_CameraRotation -= m_CameraRotationSpeed * ts;}m_Camera.SetRotation(m_CameraRotation);}m_Camera.SetPosition(m_CameraPosition);m_CameraTranslationSpeed = m_ZoomLevel;}void OrthographicCameraController::OnEvent(Event& e){EventDispatcher dispatcher(e);dispatcher.Dispatch<MouseScrolledEvent>(YT_BIND_EVENT_FN(OrthographicCameraController::OnMouseScrolled));dispatcher.Dispatch<WindowResizeEvent>(YT_BIND_EVENT_FN(OrthographicCameraController::OnWindowResized));}bool OrthographicCameraController::OnMouseScrolled(MouseScrolledEvent& e){m_ZoomLevel -= e.GetYOffset()*0.5f;m_ZoomLevel = std::max(m_ZoomLevel, 0.25f);m_Camera.SetProjection(-m_AspectRatio * m_ZoomLevel, m_AspectRatio * m_ZoomLevel, -m_ZoomLevel, m_ZoomLevel);return false;}bool OrthographicCameraController::OnWindowResized(WindowResizeEvent& e){m_AspectRatio = (float)e.GetWidth()/(float) e.GetHeight();m_Camera.SetProjection(-m_AspectRatio * m_ZoomLevel, m_AspectRatio * m_ZoomLevel, -m_ZoomLevel, m_ZoomLevel);return false;}
}

SandboxApp.cpp:

#include<YOTO.h>
#include "imgui/imgui.h"
#include<stdio.h>
#include <glm/gtc/matrix_transform.hpp>
#include <Platform/OpenGL/OpenGLShader.h>
#include <glm/gtc/type_ptr.hpp>class ExampleLayer:public YOTO::Layer
{
public:ExampleLayer():Layer("Example"),  m_CameraController(1280.0f/720.0f,true){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(YOTO::VertexArray::Create());YOTO::Ref<YOTO::VertexBuffer> m_VertexBuffer;m_VertexBuffer.reset(YOTO::VertexBuffer::Create(vertices, sizeof(vertices)));{YOTO::BufferLayout setlayout = {{YOTO::ShaderDataType::Float3,"a_Position"},{YOTO::ShaderDataType::Float4,"a_Color"}};m_VertexBuffer->SetLayout(setlayout);}m_VertexArray->AddVertexBuffer(m_VertexBuffer);YOTO::Ref<YOTO::IndexBuffer>m_IndexBuffer;m_IndexBuffer.reset(YOTO::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;uniform mat4 u_Transform;out vec3 v_Position;out vec4 v_Color;void main(){v_Position=a_Position;v_Color=a_Color;gl_Position =u_ViewProjection *u_Transform* 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=(YOTO::Shader::Create("VertexPosColor", vertexSource, fragmentSource));///测试/m_SquareVA.reset(YOTO::VertexArray::Create());float squareVertices[5 * 4] = {-0.5f,-0.5f,0.0f, 0.0f,0.0f,0.5f,-0.5f,0.0f,  1.0f,0.0f,0.5f,0.5f,0.0f,   1.0f,1.0f,-0.5f,0.5f,0.0f,  0.0f,1.0f,};YOTO::Ref<YOTO::VertexBuffer> squareVB;squareVB.reset(YOTO::VertexBuffer::Create(squareVertices, sizeof(squareVertices)));squareVB->SetLayout({{YOTO::ShaderDataType::Float3,"a_Position"},{YOTO::ShaderDataType::Float2,"a_TexCoord"}});m_SquareVA->AddVertexBuffer(squareVB);uint32_t squareIndices[6] = { 0,1,2,2,3,0 };YOTO::Ref<YOTO::IndexBuffer> squareIB;squareIB.reset((YOTO::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;uniform mat4 u_Transform;out vec3 v_Position;void main(){v_Position=a_Position;gl_Position =u_ViewProjection*u_Transform*vec4( a_Position,1.0);})";//绘制颜色std::string BlueShaderFragmentSource = R"(#version 330 corelayout(location = 0) out vec4 color;in vec3 v_Position;uniform vec3 u_Color;void main(){color=vec4(u_Color,1.0);})";m_BlueShader=(YOTO::Shader::Create("FlatColor", BlueShaderVertexSource, BlueShaderFragmentSource));auto textureShader=	m_ShaderLibrary.Load("assets/shaders/Texture.glsl");m_Texture=YOTO::Texture2D::Create("assets/textures/Checkerboard.png");m_ChernoLogo= YOTO::Texture2D::Create("assets/textures/ChernoLogo.png");std::dynamic_pointer_cast<YOTO::OpenGLShader>(textureShader)->Bind();std::dynamic_pointer_cast<YOTO::OpenGLShader>(textureShader)->UploadUniformInt("u_Texture", 0);}void OnImGuiRender() override {ImGui::Begin("设置");ImGui::ColorEdit3("正方形颜色", glm::value_ptr(m_SquareColor));ImGui::End();}void OnUpdate(YOTO::Timestep ts)override {//updatem_CameraController.OnUpdate(ts);//YT_CLIENT_TRACE("delta time {0}s ({1}ms)", ts.GetSeconds(), ts.GetMilliseconds());//RenderYOTO::RenderCommand::SetClearColor({ 0.2f, 0.2f, 0.2f, 1.0f });YOTO::RenderCommand::Clear();YOTO::Renderer::BeginScene(m_CameraController.GetCamera());{static glm::mat4 scale = glm::scale(glm::mat4(1.0f), glm::vec3(0.1f)); glm::vec4  redColor(0.8f, 0.3f, 0.3f, 1.0f);glm::vec4  blueColor(0.2f, 0.3f, 0.8f, 1.0f);/*		YOTO::MaterialRef material = new YOTO::MaterialRef(m_FlatColorShader);YOTO::MaterialInstaceRef mi = new YOTO::MaterialInstaceRef(material);mi.setValue("u_Color",redColor);mi.setTexture("u_AlbedoMap", texture);squreMesh->SetMaterial(mi);*/std::dynamic_pointer_cast<YOTO::OpenGLShader>(m_BlueShader)->Bind();std::dynamic_pointer_cast<YOTO::OpenGLShader>(m_BlueShader)->UploadUniformFloat3("u_Color",m_SquareColor);for (int y = 0; y < 20; y++) {for (int x = 0; x <20; x++){glm::vec3 pos(x * 0.105f,y* 0.105f, 0.0);glm::mat4 transform = glm::translate(glm::mat4(1.0f), pos) * scale;/*	if (x % 2 == 0) {m_BlueShader->UploadUniformFloat4("u_Color", redColor);}else {m_BlueShader->UploadUniformFloat4("u_Color", blueColor);}*/YOTO::Renderer::Submit(m_BlueShader, m_SquareVA, transform);}}auto textureShader = m_ShaderLibrary.Get("Texture");m_Texture->Bind();YOTO::Renderer::Submit(textureShader, m_SquareVA, glm::scale(glm::mat4(1.0f), glm::vec3(1.5f)));m_ChernoLogo->Bind();YOTO::Renderer::Submit(textureShader, m_SquareVA, glm::scale(glm::mat4(1.0f), glm::vec3(1.5f)));//YOTO::Renderer::Submit(m_Shader, m_VertexArray);}	YOTO::Renderer::EndScene();//YOTO::Renderer3D::BeginScene(m_Scene);//YOTO::Renderer2D::BeginScene(m_Scene);}void OnEvent(YOTO::Event& e)override {m_CameraController.OnEvent(e);/*if (event.GetEventType() == YOTO::EventType::KeyPressed) {YOTO:: KeyPressedEvent& e = (YOTO::KeyPressedEvent&)event;YT_CLIENT_TRACE("ExampleLayer:{0}",(char)e.GetKeyCode());if (e.GetKeyCode()==YT_KEY_TAB) {YT_CLIENT_INFO("ExampleLayerOnEvent:TAB按下了");}}*///YT_CLIENT_TRACE("SandBoxApp:测试event{0}", event);}private:YOTO::ShaderLibrary m_ShaderLibrary;YOTO::Ref<YOTO::Shader> m_Shader;YOTO::Ref<YOTO::VertexArray> m_VertexArray;YOTO::Ref<YOTO::Shader> m_BlueShader;YOTO::Ref<YOTO::VertexArray> m_SquareVA;YOTO::Ref<YOTO::Texture2D> m_Texture,m_ChernoLogo;YOTO::OrthographicCameraController m_CameraController;glm::vec3 m_SquareColor = { 0.2f,0.3f,0.7f };};class Sandbox:public YOTO::Application
{
public:Sandbox(){PushLayer(new ExampleLayer());//PushLayer(new YOTO::ImGuiLayer());}~Sandbox() {}private:};YOTO::Application* YOTO::CreateApplication() {printf("helloworld");return new Sandbox();
}

测试:

 cool

修改:

添加修改视口的方法:

Render.h:

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

Render.cpp: 

#include"ytpch.h"
#include"Renderer.h"
#include <Platform/OpenGL/OpenGLShader.h>
namespace YOTO {Renderer::SceneData* Renderer::m_SceneData = new	Renderer::SceneData;void Renderer::Init(){RenderCommand::Init();}void Renderer::OnWindowResize(uint32_t width, uint32_t height){RenderCommand::SetViewport(0, 0, width, height);}void Renderer::BeginScene(OrthographicCamera& camera){m_SceneData->ViewProjectionMatrix = camera.GetViewProjectionMatrix();}void Renderer::EndScene(){}void Renderer::Submit(const Ref<Shader>& shader, const Ref<VertexArray>& vertexArray, const glm::mat4& transform){shader->Bind();std::dynamic_pointer_cast<OpenGLShader>(shader)->UploadUniformMat4("u_ViewProjection", m_SceneData->ViewProjectionMatrix);std::dynamic_pointer_cast<OpenGLShader>(shader)->UploadUniformMat4("u_Transform", transform);/*	mi.Bind();*/vertexArray->Bind();RenderCommand::DrawIndexed(vertexArray);}
}

RenderCommand.h:

#pragma once
#include"RendererAPI.h"
namespace YOTO {class RenderCommand{public:inline static void Init() {s_RendererAPI->Init();}inline static void SetViewport(uint32_t x, uint32_t y, uint32_t width, uint32_t height) {s_RendererAPI->SetViewport(x,y,width,height);}inline static void SetClearColor(const glm::vec4& color) {s_RendererAPI->SetClearColor(color);}inline static void Clear() {s_RendererAPI->Clear();}inline static void DrawIndexed(const Ref<VertexArray>& vertexArray) {s_RendererAPI->DrawIndexed(vertexArray);}private:static RendererAPI* s_RendererAPI;};}

RenderAPI.h:

#pragma once
#include<glm/glm.hpp>
#include "VertexArray.h"
namespace YOTO {class RendererAPI{public:enum class API {None = 0,OpenGL = 1};public:virtual void Init() = 0;virtual void SetClearColor(const glm::vec4& color)=0;virtual void SetViewport(uint32_t x, uint32_t y, uint32_t width, uint32_t height) = 0;virtual void Clear() = 0;virtual void DrawIndexed(const Ref<VertexArray>& vertexArray)=0;inline static API GetAPI() { return s_API; }private:static API s_API;};
}

OpenGLRenderAPI.h:

#pragma once
#include"YOTO/Renderer/RendererAPI.h"
namespace YOTO {class OpenGLRendererAPI:public RendererAPI{public:virtual void Init()override;virtual void SetViewport(uint32_t x, uint32_t y, uint32_t width, uint32_t height) override;virtual void SetClearColor(const glm::vec4& color)override;virtual void Clear()override;virtual void DrawIndexed(const Ref<VertexArray>& vertexArray) override;};
}

OpenGLRenderAPI.cpp: 

#include "ytpch.h"
#include "OpenGLRendererAPI.h"
#include <glad/glad.h>
namespace YOTO {void OpenGLRendererAPI::Init(){//启用混合glEnable(GL_BLEND);//设置混合函数glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);}void OpenGLRendererAPI::SetViewport(uint32_t x, uint32_t y, uint32_t width, uint32_t height){glViewport(x, y, width, height);}void OpenGLRendererAPI::SetClearColor(const glm::vec4& color){glClearColor(color.r, color.g, color.b, color.a);}void OpenGLRendererAPI::Clear(){glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);}void OpenGLRendererAPI::DrawIndexed(const Ref<VertexArray>& vertexArray){glDrawElements(GL_TRIANGLES, vertexArray->GetIndexBuffer()->GetCount(), GL_UNSIGNED_INT, nullptr);}
}

OrthographicCameraController.h: 

#pragma once
#include "YOTO/Renderer/OrthographicCamera.h"
#include"YOTO/Core/Timestep.h"
#include "YOTO/Event/ApplicationEvent.h"
#include "YOTO/Event/MouseEvent.h"
namespace YOTO {class OrthographicCameraController {public:OrthographicCameraController(float aspectRatio, bool rotation=false );//0,1280void OnUpdate(Timestep ts);void OnEvent(Event& e);OrthographicCamera& GetCamera() {return m_Camera;}const OrthographicCamera& GetCamera()const  {return m_Camera;}float  GetZoomLevel() { return m_ZoomLevel; }void SetZoomLevel(float level) { m_ZoomLevel = level; }private:bool OnMouseScrolled(MouseScrolledEvent &e);bool OnWindowResized(WindowResizeEvent& e);private:float m_AspectRatio;//横纵比float m_ZoomLevel = 1.0f;OrthographicCamera m_Camera;bool m_Rotation;glm::vec3 m_CameraPosition = {0.0f,0.0f,0.0f};float m_CameraRotation = 0.0f;float m_CameraTranslationSpeed = 1.0f, m_CameraRotationSpeed = 180.0f;};
}

OrthographicCameraController.cpp:  

#include "ytpch.h"
#include "OrthographicCameraController.h"
#include"YOTO/Input.h"
#include <YOTO/KeyCode.h>
namespace YOTO {OrthographicCameraController::OrthographicCameraController(float aspectRatio, bool rotation):m_AspectRatio(aspectRatio),m_Camera(-m_AspectRatio*m_ZoomLevel,m_AspectRatio*m_ZoomLevel,-m_ZoomLevel,m_ZoomLevel),m_Rotation(rotation){}void OrthographicCameraController::OnUpdate(Timestep ts){if (Input::IsKeyPressed(YT_KEY_A)) {m_CameraPosition.x -= m_CameraTranslationSpeed * ts;}else if (Input::IsKeyPressed(YT_KEY_D)) {m_CameraPosition.x += m_CameraTranslationSpeed * ts;}if (Input::IsKeyPressed(YT_KEY_S)) {m_CameraPosition.y -= m_CameraTranslationSpeed * ts;}else if (Input::IsKeyPressed(YT_KEY_W)) {m_CameraPosition.y += m_CameraTranslationSpeed * ts;}if (m_Rotation) {if (Input::IsKeyPressed(YT_KEY_Q)) {m_CameraRotation += m_CameraRotationSpeed * ts;}else if (Input::IsKeyPressed(YT_KEY_E)) {m_CameraRotation -= m_CameraRotationSpeed * ts;}m_Camera.SetRotation(m_CameraRotation);}m_Camera.SetPosition(m_CameraPosition);m_CameraTranslationSpeed = m_ZoomLevel;}void OrthographicCameraController::OnEvent(Event& e){EventDispatcher dispatcher(e);dispatcher.Dispatch<MouseScrolledEvent>(YT_BIND_EVENT_FN(OrthographicCameraController::OnMouseScrolled));dispatcher.Dispatch<WindowResizeEvent>(YT_BIND_EVENT_FN(OrthographicCameraController::OnWindowResized));}bool OrthographicCameraController::OnMouseScrolled(MouseScrolledEvent& e){m_ZoomLevel -= e.GetYOffset()*0.5f;m_ZoomLevel = std::max(m_ZoomLevel, 0.25f);m_Camera.SetProjection(-m_AspectRatio * m_ZoomLevel, m_AspectRatio * m_ZoomLevel, -m_ZoomLevel, m_ZoomLevel);return false;}bool OrthographicCameraController::OnWindowResized(WindowResizeEvent& e){m_AspectRatio = (float)e.GetWidth()/(float) e.GetHeight();m_Camera.SetProjection(-m_AspectRatio * m_ZoomLevel, m_AspectRatio * m_ZoomLevel, -m_ZoomLevel, m_ZoomLevel);return false;}
}

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/Core/Timestep.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);bool  OnWindowResize(WindowResizeEvent& e);private:std::unique_ptr<Window>  m_Window;ImGuiLayer* m_ImGuiLayer;bool m_Running = true;bool m_Minimized = false;LayerStack m_LayerStack;Timestep m_Timestep;float m_LastFrameTime = 0.0f;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"
#include <GLFW/glfw3.h>namespace YOTO {
#define BIND_EVENT_FN(x) std::bind(&x, this, std::placeholders::_1)Application* Application::s_Instance = nullptr;Application::Application(){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));m_Window->SetVSync(false);Renderer::Init();//new一个Layer,放在最后层进行渲染m_ImGuiLayer = new ImGuiLayer();PushOverlay(m_ImGuiLayer);	}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));dispatcher.Dispatch<WindowResizeEvent>(BIND_EVENT_FN(Application::OnWindowResize));//输出事件信息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;}bool Application::OnWindowResize(WindowResizeEvent& e){if (e.GetWidth()==0||e.GetHeight()==0) {m_Minimized = true;return false;}m_Minimized = false;//调整视口Renderer::OnWindowResize(e.GetWidth(), e.GetHeight());return false;}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){float time = (float)glfwGetTime();//window平台Timestep timestep = time - m_LastFrameTime;m_LastFrameTime = time;if (!m_Minimized) {for (Layer* layer : m_LayerStack) {layer->OnUpdate(timestep);}}	//将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();}
}

SandboxApp.cpp:

#include<YOTO.h>
#include "imgui/imgui.h"
#include<stdio.h>
#include <glm/gtc/matrix_transform.hpp>
#include <Platform/OpenGL/OpenGLShader.h>
#include <glm/gtc/type_ptr.hpp>class ExampleLayer:public YOTO::Layer
{
public:ExampleLayer():Layer("Example"),  m_CameraController(1280.0f/720.0f,true){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(YOTO::VertexArray::Create());YOTO::Ref<YOTO::VertexBuffer> m_VertexBuffer;m_VertexBuffer.reset(YOTO::VertexBuffer::Create(vertices, sizeof(vertices)));{YOTO::BufferLayout setlayout = {{YOTO::ShaderDataType::Float3,"a_Position"},{YOTO::ShaderDataType::Float4,"a_Color"}};m_VertexBuffer->SetLayout(setlayout);}m_VertexArray->AddVertexBuffer(m_VertexBuffer);YOTO::Ref<YOTO::IndexBuffer>m_IndexBuffer;m_IndexBuffer.reset(YOTO::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;uniform mat4 u_Transform;out vec3 v_Position;out vec4 v_Color;void main(){v_Position=a_Position;v_Color=a_Color;gl_Position =u_ViewProjection *u_Transform* 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=(YOTO::Shader::Create("VertexPosColor", vertexSource, fragmentSource));///测试/m_SquareVA.reset(YOTO::VertexArray::Create());float squareVertices[5 * 4] = {-0.5f,-0.5f,0.0f, 0.0f,0.0f,0.5f,-0.5f,0.0f,  1.0f,0.0f,0.5f,0.5f,0.0f,   1.0f,1.0f,-0.5f,0.5f,0.0f,  0.0f,1.0f,};YOTO::Ref<YOTO::VertexBuffer> squareVB;squareVB.reset(YOTO::VertexBuffer::Create(squareVertices, sizeof(squareVertices)));squareVB->SetLayout({{YOTO::ShaderDataType::Float3,"a_Position"},{YOTO::ShaderDataType::Float2,"a_TexCoord"}});m_SquareVA->AddVertexBuffer(squareVB);uint32_t squareIndices[6] = { 0,1,2,2,3,0 };YOTO::Ref<YOTO::IndexBuffer> squareIB;squareIB.reset((YOTO::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;uniform mat4 u_Transform;out vec3 v_Position;void main(){v_Position=a_Position;gl_Position =u_ViewProjection*u_Transform*vec4( a_Position,1.0);})";//绘制颜色std::string BlueShaderFragmentSource = R"(#version 330 corelayout(location = 0) out vec4 color;in vec3 v_Position;uniform vec3 u_Color;void main(){color=vec4(u_Color,1.0);})";m_BlueShader=(YOTO::Shader::Create("FlatColor", BlueShaderVertexSource, BlueShaderFragmentSource));auto textureShader=	m_ShaderLibrary.Load("assets/shaders/Texture.glsl");m_Texture=YOTO::Texture2D::Create("assets/textures/Checkerboard.png");m_ChernoLogo= YOTO::Texture2D::Create("assets/textures/ChernoLogo.png");std::dynamic_pointer_cast<YOTO::OpenGLShader>(textureShader)->Bind();std::dynamic_pointer_cast<YOTO::OpenGLShader>(textureShader)->UploadUniformInt("u_Texture", 0);}void OnImGuiRender() override {ImGui::Begin("设置");ImGui::ColorEdit3("正方形颜色", glm::value_ptr(m_SquareColor));ImGui::End();}void OnUpdate(YOTO::Timestep ts)override {//updatem_CameraController.OnUpdate(ts);//YT_CLIENT_TRACE("delta time {0}s ({1}ms)", ts.GetSeconds(), ts.GetMilliseconds());//RenderYOTO::RenderCommand::SetClearColor({ 0.2f, 0.2f, 0.2f, 1.0f });YOTO::RenderCommand::Clear();YOTO::Renderer::BeginScene(m_CameraController.GetCamera());{static glm::mat4 scale = glm::scale(glm::mat4(1.0f), glm::vec3(0.1f)); glm::vec4  redColor(0.8f, 0.3f, 0.3f, 1.0f);glm::vec4  blueColor(0.2f, 0.3f, 0.8f, 1.0f);/*		YOTO::MaterialRef material = new YOTO::MaterialRef(m_FlatColorShader);YOTO::MaterialInstaceRef mi = new YOTO::MaterialInstaceRef(material);mi.setValue("u_Color",redColor);mi.setTexture("u_AlbedoMap", texture);squreMesh->SetMaterial(mi);*/std::dynamic_pointer_cast<YOTO::OpenGLShader>(m_BlueShader)->Bind();std::dynamic_pointer_cast<YOTO::OpenGLShader>(m_BlueShader)->UploadUniformFloat3("u_Color",m_SquareColor);for (int y = 0; y < 20; y++) {for (int x = 0; x <20; x++){glm::vec3 pos(x * 0.105f,y* 0.105f, 0.0);glm::mat4 transform = glm::translate(glm::mat4(1.0f), pos) * scale;/*	if (x % 2 == 0) {m_BlueShader->UploadUniformFloat4("u_Color", redColor);}else {m_BlueShader->UploadUniformFloat4("u_Color", blueColor);}*/YOTO::Renderer::Submit(m_BlueShader, m_SquareVA, transform);}}auto textureShader = m_ShaderLibrary.Get("Texture");m_Texture->Bind();YOTO::Renderer::Submit(textureShader, m_SquareVA, glm::scale(glm::mat4(1.0f), glm::vec3(1.5f)));m_ChernoLogo->Bind();YOTO::Renderer::Submit(textureShader, m_SquareVA, glm::scale(glm::mat4(1.0f), glm::vec3(1.5f)));//YOTO::Renderer::Submit(m_Shader, m_VertexArray);}	YOTO::Renderer::EndScene();//YOTO::Renderer3D::BeginScene(m_Scene);//YOTO::Renderer2D::BeginScene(m_Scene);}void OnEvent(YOTO::Event& e)override {m_CameraController.OnEvent(e);if (e.GetEventType() == YOTO::EventType::WindowResize) {auto& re = (YOTO::WindowResizeEvent&)e;/*		float zoom = re.GetWidth() / 1280.0f;m_CameraController.SetZoomLevel(zoom);*/}}private:YOTO::ShaderLibrary m_ShaderLibrary;YOTO::Ref<YOTO::Shader> m_Shader;YOTO::Ref<YOTO::VertexArray> m_VertexArray;YOTO::Ref<YOTO::Shader> m_BlueShader;YOTO::Ref<YOTO::VertexArray> m_SquareVA;YOTO::Ref<YOTO::Texture2D> m_Texture,m_ChernoLogo;YOTO::OrthographicCameraController m_CameraController;glm::vec3 m_SquareColor = { 0.2f,0.3f,0.7f };};class Sandbox:public YOTO::Application
{
public:Sandbox(){PushLayer(new ExampleLayer());//PushLayer(new YOTO::ImGuiLayer());}~Sandbox() {}private:};YOTO::Application* YOTO::CreateApplication() {printf("helloworld");return new Sandbox();
}

添加了新功能,修改窗口大小在OnEvent中。

相关文章:

跟着cherno手搓游戏引擎【22】CameraController、Resize

前置&#xff1a; YOTO.h: #pragma once//用于YOTO APP#include "YOTO/Application.h" #include"YOTO/Layer.h" #include "YOTO/Log.h"#include"YOTO/Core/Timestep.h"#include"YOTO/Input.h" #include"YOTO/KeyCod…...

微信小程序(四十二)wechat-http拦截器

注释很详细&#xff0c;直接上代码 上一篇 新增内容&#xff1a; 1.wechat-http请求的封装 2.wechat-http请求的拦截器的用法演示 源码&#xff1a; utils/http.js import http from "wechat-http"//设置全局默认请求地址 http.baseURL "https://live-api.ith…...

tomcat部署zrlog

1.下载zrlog包&#xff0c;并添加到虚拟机中 1)进入/opt/apache-tomcat-8.5.90/webapps目录 cd /opt/apache-tomcat-8.5.90/webapps2)下载zrlog包 wget http://dl.zrlog.com/release/zrlog-1.7.1-baaecb9-release.war 3)重命名包 mv zrlog-1.7.1-baaecb9-release zrblog 2…...

Ubuntu Desktop 开机数字小键盘

Ubuntu Desktop 开机数字小键盘 1. 开机数字小键盘References 1. 开机数字小键盘 一般情况下&#xff0c;Ubuntu 开机后小键盘区是控制方向键而非数字键&#xff0c;每次开机后若用到数字键都需要按下 NumLock 键。 References [1] Yongqiang Cheng, https://yongqiang.blog…...

树莓派编程基础与硬件控制

1.编程语言 Python 是一种泛用型的编程语言&#xff0c;可以用于大量场景的程序开发中。根据基于谷歌搜 索指数的 PYPL&#xff08;程序语言流行指数&#xff09;统计&#xff0c;Python 是 2019 年 2 月全球范围内最为流行 的编程语言 相比传统的 C、Java 等编程语言&#x…...

autojs通过正则表达式获取带有数字的text内容

视频连接 视频连接 参考 参考 var ctextMatches(/\d/).findOne()console.log("当前金币"c.text()) // 获取当前金币UiSelector.textMatches(reg) reg {string} | {Regex} 要满足的正则表达式。 为当前选择器附加控件"text需要满足正则表达式reg"的条件。 …...

Android java基础_类的继承

一.Android Java基础_类的继承 先封装一个persion类&#xff0c;在persion的基础上定义Student类&#xff0c;并基础persion类。 子类能访问父类的成员函数。 class Person {private int age;public void setAge(int age) {if (age < 0 || age > 200)age 0;else {thi…...

nginx stream proxy 模块的ssl连接源码分析

目录 1. 源起2. 分析验证环境的配置3. 源码分析3.1 代理模块的请求入口点分析3.2 发起与上游服务器的连接3.3 连接回调3.4 TCP连接建立成功后为上下游数据透传做准备3.5 TCP连接的ssl上下文初始化3.6 ssl握手成功后的处理3.7 连接数据的收与发1. 源起 我一直来对ssl建立连接的过…...

C#面:Static Nested Class 和 Inner Class 有什么不同

这是两种不同的类嵌套方式。 Static Nested Class &#xff1a; 是一个静态嵌套类&#xff0c;它是在外部类中定义的一个静态类。它可以访问外部类的静态成员和方法&#xff0c;但不能直接访问外部类的非静态成员和方法。静态嵌套类可以独立于外部类实例化&#xff0c;即可以…...

LeetCode、208. 实现 Trie (前缀树)【中等,自定义数据结构】

文章目录 前言LeetCode、208. 实现 Trie (前缀树)【中等&#xff0c;自定义数据结构】题目链接与分类思路 资料获取 前言 博主介绍&#xff1a;✌目前全网粉丝2W&#xff0c;csdn博客专家、Java领域优质创作者&#xff0c;博客之星、阿里云平台优质作者、专注于Java后端技术领…...

java数据结构与算法刷题-----LeetCode151. 反转字符串中的单词

java数据结构与算法刷题目录&#xff08;剑指Offer、LeetCode、ACM&#xff09;-----主目录-----持续更新(进不去说明我没写完)&#xff1a;https://blog.csdn.net/grd_java/article/details/123063846 解题思路 这道题&#xff0c;可以理解为&#xff0c;将字符串颠倒&#xf…...

《Java 简易速速上手小册》第8章:Java 性能优化(2024 最新版)

文章目录 8.1 性能评估工具 - 你的性能探测仪8.1.1 基础知识8.1.2 重点案例&#xff1a;使用 VisualVM 监控应用性能8.1.3 拓展案例 1&#xff1a;使用 JProfiler 分析内存泄漏8.1.4 拓展案例 2&#xff1a;使用 Gatling 进行 Web 应用压力测试 8.2 JVM 调优 - 魔法引擎的调校8…...

mysql全国省市县三级联动创表sql(一)

1. 建表sql CREATE TABLE province (id VARCHAR ( 32 ) PRIMARY KEY COMMENT 主键,code CHAR ( 6 ) NOT NULL COMMENT 省份编码,name VARCHAR ( 40 ) NOT NULL COMMENT 省份名称 ) COMMENT 省份信息表;CREATE TABLE city (id VARCHAR ( 32 ) PRIMARY KEY COMMENT 主键,code …...

go面试题--使用两个goroutine交替打印数字与字母

使用两个goroutine交替打印数字与字母 题目如下&#xff1a; 使用两个goroutine交替打印序列&#xff0c;一个goroutine打印数字&#xff0c;另外一个goroutine打印字母&#xff0c;最终效果如下&#xff1a; 12AB34CD56EF78GH910IZ1112KL1314MN1516OP1718QR1920ST2122UV2324W…...

DolphinScheduler-3.2.0 集群搭建

目录 一、基础环境准备 1.1 组件下载地址 1.2 前置准备工作 二、 DolphinScheduler集群部署 2.1 解压安装包 2.2 配置数据库 2.3 准备 DolphinScheduler 启动环境 2.3.1 配置用户免密及权限 2.3.2 配置机器 SSH 免密登陆 2.3.3 启动 zookeeper集群 2.3.4 修改instal…...

07:Kubectl 命令详解|K8S资源对象管理|K8S集群管理(重难点)

Kubectl 命令详解&#xff5c;K8S资源对象管理&#xff5c;K8S集群管理 kubectl管理命令kubectl get 查询资源常用的排错命令kubectl run 创建容器 POD原理pod的生命周期 k8s资源对象管理资源文件使用资源文件管理对象Pod资源文件deploy资源文件 集群调度的规则扩容与缩减集群更…...

【设计模式】springboot3项目整合模板方法深入理解设计模式之模板方法(Template Method)

&#x1f389;&#x1f389;欢迎光临&#x1f389;&#x1f389; &#x1f3c5;我是苏泽&#xff0c;一位对技术充满热情的探索者和分享者。&#x1f680;&#x1f680; &#x1f31f;特别推荐给大家我的最新专栏《Spring 狂野之旅&#xff1a;底层原理高级进阶》 &#x1f680…...

Windows搭建docker+k8s

安装Docker Desktop 从官网下载&#xff0c;然后直接安装即可&#xff0c;过程很简单&#xff0c;一直Next就行。 有一点需要注意就是要看好对应的版本&#xff0c;因为后边涉及到版本的问题。 https://www.docker.com/products/docker-desktop 安装完成&#xff0c;双击图…...

年假作业10

一、选择题 BBDBACCCAD 二、填空题 1,4,13,40 3715 358 5 2 6 1 5 4 8 2 0 2 三、编程题 1、 #include <iostream> #include<array> #include <limits> using namespace std; int main() {array<int,10> score;array<int,10>::iterat…...

[ai笔记4] 将AI工具场景化,应用于生活和工作

欢迎来到文思源想的AI空间&#xff0c;这是技术老兵重学ai以及成长思考的第4篇分享内容&#xff01; 转眼已经到了大年初三&#xff0c;但是拜年的任务还只完成了一半&#xff0c;准备的大部头的书&#xff0c;现在也就看了两本&#xff0c;还好AI笔记通过每天早起坚持了下来。…...

MPNet:旋转机械轻量化故障诊断模型详解python代码复现

目录 一、问题背景与挑战 二、MPNet核心架构 2.1 多分支特征融合模块(MBFM) 2.2 残差注意力金字塔模块(RAPM) 2.2.1 空间金字塔注意力(SPA) 2.2.2 金字塔残差块(PRBlock) 2.3 分类器设计 三、关键技术突破 3.1 多尺度特征融合 3.2 轻量化设计策略 3.3 抗噪声…...

【Python】 -- 趣味代码 - 小恐龙游戏

文章目录 文章目录 00 小恐龙游戏程序设计框架代码结构和功能游戏流程总结01 小恐龙游戏程序设计02 百度网盘地址00 小恐龙游戏程序设计框架 这段代码是一个基于 Pygame 的简易跑酷游戏的完整实现,玩家控制一个角色(龙)躲避障碍物(仙人掌和乌鸦)。以下是代码的详细介绍:…...

CVPR 2025 MIMO: 支持视觉指代和像素grounding 的医学视觉语言模型

CVPR 2025 | MIMO&#xff1a;支持视觉指代和像素对齐的医学视觉语言模型 论文信息 标题&#xff1a;MIMO: A medical vision language model with visual referring multimodal input and pixel grounding multimodal output作者&#xff1a;Yanyuan Chen, Dexuan Xu, Yu Hu…...

k8s从入门到放弃之Ingress七层负载

k8s从入门到放弃之Ingress七层负载 在Kubernetes&#xff08;简称K8s&#xff09;中&#xff0c;Ingress是一个API对象&#xff0c;它允许你定义如何从集群外部访问集群内部的服务。Ingress可以提供负载均衡、SSL终结和基于名称的虚拟主机等功能。通过Ingress&#xff0c;你可…...

【Linux】C语言执行shell指令

在C语言中执行Shell指令 在C语言中&#xff0c;有几种方法可以执行Shell指令&#xff1a; 1. 使用system()函数 这是最简单的方法&#xff0c;包含在stdlib.h头文件中&#xff1a; #include <stdlib.h>int main() {system("ls -l"); // 执行ls -l命令retu…...

pam_env.so模块配置解析

在PAM&#xff08;Pluggable Authentication Modules&#xff09;配置中&#xff0c; /etc/pam.d/su 文件相关配置含义如下&#xff1a; 配置解析 auth required pam_env.so1. 字段分解 字段值说明模块类型auth认证类模块&#xff0c;负责验证用户身份&am…...

1688商品列表API与其他数据源的对接思路

将1688商品列表API与其他数据源对接时&#xff0c;需结合业务场景设计数据流转链路&#xff0c;重点关注数据格式兼容性、接口调用频率控制及数据一致性维护。以下是具体对接思路及关键技术点&#xff1a; 一、核心对接场景与目标 商品数据同步 场景&#xff1a;将1688商品信息…...

Qwen3-Embedding-0.6B深度解析:多语言语义检索的轻量级利器

第一章 引言&#xff1a;语义表示的新时代挑战与Qwen3的破局之路 1.1 文本嵌入的核心价值与技术演进 在人工智能领域&#xff0c;文本嵌入技术如同连接自然语言与机器理解的“神经突触”——它将人类语言转化为计算机可计算的语义向量&#xff0c;支撑着搜索引擎、推荐系统、…...

第一篇:Agent2Agent (A2A) 协议——协作式人工智能的黎明

AI 领域的快速发展正在催生一个新时代&#xff0c;智能代理&#xff08;agents&#xff09;不再是孤立的个体&#xff0c;而是能够像一个数字团队一样协作。然而&#xff0c;当前 AI 生态系统的碎片化阻碍了这一愿景的实现&#xff0c;导致了“AI 巴别塔问题”——不同代理之间…...

快刀集(1): 一刀斩断视频片头广告

一刀流&#xff1a;用一个简单脚本&#xff0c;秒杀视频片头广告&#xff0c;还你清爽观影体验。 1. 引子 作为一个爱生活、爱学习、爱收藏高清资源的老码农&#xff0c;平时写代码之余看看电影、补补片&#xff0c;是再正常不过的事。 电影嘛&#xff0c;要沉浸&#xff0c;…...