跟着cherno手搓游戏引擎【19】抽象纹理

引入:

导入stb_image:

GitHub - nothings/stb: stb single-file public domain libraries for C/C++

下载复制stb_image.h的内容(8000多行),然后粘到如图位置

stb_image.cpp:

#include"ytpch.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

修改SRC下的premake.lua

workspace "YOTOEngine"		-- sln文件名architecture "x64"	configurations{"Debug","Release","Dist"}
startproject "Sandbox"
-- https://github.com/premake/premake-core/wiki/Tokens#value-tokens
-- 组成输出目录:Debug-windows-x86_64
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
-- 包含相对解决方案的目录
IncludeDir={}
IncludeDir["GLFW"]="YOTOEngine/vendor/GLFW/include"
IncludeDir["Glad"]="YOTOEngine/vendor/Glad/include"
IncludeDir["ImGui"] ="YOTOEngine/vendor/imgui"
IncludeDir["glm"] ="YOTOEngine/vendor/glm"
IncludeDir["stb_image"] ="YOTOEngine/vendor/stb_image"
--项目中包含某包
include "YOTOEngine/vendor/GLFW"
include "YOTOEngine/vendor/Glad"
include "YOTOEngine/vendor/imgui"project "YOTOEngine"		--YOTOEngine项目location "YOTOEngine"--在sln所属文件夹下的YOTOEngine文件夹kind "StaticLib"--修改为lib静态库language "C++"targetdir ("bin/" .. outputdir .. "/%{prj.name}") -- 输出目录objdir ("bin-int/" .. outputdir .. "/%{prj.name}")-- 中间目录cppdialect "C++17" staticruntime "on"--打开pchheader "ytpch.h"pchsource "YOTOEngine/src/ytpch.cpp"-- 包含的所有h和cpp文件files{"%{prj.name}/src/**.h","%{prj.name}/src/**.cpp","%{prj.name}/vendor/stb_image/**.h","%{prj.name}/vendor/stb_image/**.cpp","%{prj.name}/vendor/glm/glm/**.hpp","%{prj.name}/vendor/glm/glm/**.inl"}defines{"_CRT_SECURE_NO_WARNINGS"}-- 包含目录includedirs{"%{prj.name}/src","%{prj.name}/vendor/spdlog-1.x/include","%{IncludeDir.GLFW}","%{IncludeDir.Glad}","%{IncludeDir.ImGui}","%{IncludeDir.glm}","%{IncludeDir.stb_image}",}links{"GLFW",-- GLFW.lib库链接到YOTOEngine项目中"Glad",-- Glad.lib库链接到YOTOEngine项目中"ImGui",-- ImGui.lib库链接到YOTOEngine项目中"opengl32.lib"}-- 如果是window系统filter "system:windows"-- On:代码生成的运行库选项是MTD,静态链接MSVCRT.lib库;-- Off:代码生成的运行库选项是MDD,动态链接MSVCRT.dll库;打包后的exe放到另一台电脑上若无这个dll会报错systemversion "latest"	-- windowSDK版本-- 预处理器定义defines{"YT_PLATFORM_WINDOWS","YT_BUILD_DLL",-- "YT_ENABLE_ASSERTS", "GLFW_INCLUDE_NONE",-- 让GLFW不包含OpenGL}-- 编译好后移动Hazel.dll文件到Sandbox文件夹下-- postbuildcommands{-- 	("{COPY} %{cfg.buildtarget.relpath} ../bin/" .. outputdir .. "/Sandbox")-- }-- 不同配置下的预定义不同filter "configurations:Debug"defines "YT_DEBUG"runtime "Debug"symbols "On"filter "configurations:Release"defines "YT_RELEASE"runtime "Release"optimize "On"filter "configurations:Dist"defines "YT_DIST"runtime "Release"optimize "On"project "Sandbox"location "Sandbox"kind "ConsoleApp"language "C++"cppdialect "C++17"staticruntime "on"targetdir ("bin/" .. outputdir .. "/%{prj.name}")objdir ("bin-int/" .. outputdir .. "/%{prj.name}")files{"%{prj.name}/src/**.h","%{prj.name}/src/**.cpp"}-- 同样包含spdlog头文件includedirs{"YOTOEngine/vendor/spdlog-1.x/include","YOTOEngine/src","YOTOEngine/vendor","%{IncludeDir.glm}"}-- 引用YOTOEnginelinks{"YOTOEngine","GLFW","opengl32.lib"}filter "system:windows"systemversion "latest"defines{"YT_PLATFORM_WINDOWS"}filter "configurations:Debug"defines "YT_DEBUG"runtime "Debug"symbols "On"filter "configurations:Release"defines "YT_RELEASE"runtime "Release"optimize "On"filter "configurations:Dist"defines "YT_DIST"runtime "Release"optimize "On"

抽象:

在Renderer文件夹下创建:

Texture.h:

#pragma once
#include"YOTO/Core.h"
namespace YOTO {class Texture{public:virtual ~Texture() = default;virtual uint32_t GetWidth()const = 0;virtual uint32_t GetHeight()const = 0;virtual void Bind(uint32_t slot=0)const = 0;};class Texture2D :public Texture {public:static Ref<Texture2D>Create(const std::string& path);};
}

Texture.cpp: 

#include "ytpch.h"
#include "Texture.h"
#include"Renderer.h"
#include "Platform/OpenGL/OpenGLTexture.h"
namespace YOTO {Ref<Texture2D> Texture2D::Create(const std::string& path){switch (Renderer::GetAPI()){case RendererAPI::API::None:YT_CORE_ASSERT(false, "Texture2D:API为None不支持");return nullptr;case RendererAPI::API::OpenGL:return  std::make_shared<OpenGLTexture2D>(path);}YT_CORE_ASSERT(false, "Buffer:未知API");return nullptr;}
}

实例:

OpenGLTexture.h:

#pragma once
#include"YOTO/Renderer/Texture.h"
#include"YOTO/Log.h"
namespace YOTO {class OpenGLTexture2D:public Texture2D{public:OpenGLTexture2D(const std::string path);virtual~OpenGLTexture2D();virtual uint32_t GetWidth()const override { return m_Width; }virtual uint32_t GetHeight()const override { return m_Height; }virtual void Bind(uint32_t slot=0)const override;private:std::string m_Path;uint32_t m_Width, m_Height;uint32_t m_RendererID;};
}

OpenGLTexture.cpp:

#include "ytpch.h"
#include "OpenGLTexture.h"
#include<glad/glad.h>
#include"stb_image.h"
namespace YOTO {OpenGLTexture2D::OpenGLTexture2D(const std::string path):m_Path(path){int width, height, channels;stbi_set_flip_vertically_on_load(1);//翻转stbi_uc*data=stbi_load(path.c_str(),&width,&height,&channels,0);YT_CORE_ASSERT(data, "图片加载错误");m_Width = width;m_Height = height;//创建纹理glCreateTextures(GL_TEXTURE_2D, 1, &m_RendererID);///告诉OpenGLm_RendererID的纹理存储的是rbg8位,宽高的缓冲区glTextureStorage2D(m_RendererID, 1, GL_RGB8,m_Width,m_Height);//配置参数:纹理放大时用周围颜色的平均值过滤glTextureParameteri(m_RendererID,GL_TEXTURE_MIN_FILTER,GL_LINEAR);glTextureParameteri(m_RendererID, GL_TEXTURE_MAG_FILTER, GL_NEAREST);glTextureSubImage2D(m_RendererID, 0, 0, 0, m_Width, m_Height,GL_RGB,GL_UNSIGNED_BYTE,data);stbi_image_free(data);}OpenGLTexture2D::~OpenGLTexture2D(){glDeleteTextures(1,&m_RendererID);}void OpenGLTexture2D::Bind(uint32_t slot) const{glBindTextureUnit(slot, m_RendererID);}
}

修改配置:

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/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"

测试:

#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_Camera(-2.0f, 2.0f, -2.0f, 2.0f), m_CameraPosition(0){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.reset(YOTO::Shader::Create(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.reset(YOTO::Shader::Create(BlueShaderVertexSource, BlueShaderFragmentSource));std::string textureVertexSource = R"(#version 330 corelayout(location = 0) in vec3 a_Position;layout(location = 1) in vec2 a_TexCoord;uniform mat4 u_ViewProjection;uniform mat4 u_Transform;out vec2 v_TexCoord;out vec3 v_Position;void main(){v_TexCoord=a_TexCoord;v_Position=a_Position;gl_Position =u_ViewProjection*u_Transform*vec4( a_Position,1.0);})";//绘制颜色std::string textureFragmentSource = R"(#version 330 corelayout(location = 0) out vec4 color;in vec3 v_Position;in vec2 v_TexCoord;uniform sampler2D u_Texture ;void main(){color = texture(u_Texture, v_TexCoord);	//	color = vec4(v_TexCoord, 0.0f, 1.0f);	})";m_TextureShader.reset(YOTO::Shader::Create(textureVertexSource, textureFragmentSource));m_Texture=YOTO::Texture2D::Create("D:/GameEngine/yoto/SRC/Sandbox/assets/textures/Checkerboard.png");std::dynamic_pointer_cast<YOTO::OpenGLShader>(m_TextureShader)->Bind();std::dynamic_pointer_cast<YOTO::OpenGLShader>(m_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 {YT_CLIENT_TRACE("delta time {0}s ({1}ms)", ts.GetSeconds(), ts.GetMilliseconds());if (YOTO::Input::IsKeyPressed(YT_KEY_LEFT)) {m_CameraPosition.x -= m_CameraMoveSpeed* ts;}else if (YOTO::Input::IsKeyPressed(YT_KEY_RIGHT)) {m_CameraPosition.x += m_CameraMoveSpeed * ts;}if (YOTO::Input::IsKeyPressed(YT_KEY_DOWN)) {m_CameraPosition.y -= m_CameraMoveSpeed * ts;}else if (YOTO::Input::IsKeyPressed(YT_KEY_UP)) {m_CameraPosition.y += m_CameraMoveSpeed * ts;}if (YOTO::Input::IsKeyPressed(YT_KEY_A)) {m_CameraRotation += m_CameraRotationSpeed * ts;}else if (YOTO::Input::IsKeyPressed(YT_KEY_D)) {m_CameraRotation -= m_CameraRotationSpeed * ts;}YOTO::RenderCommand::SetClearColor({ 0.2f, 0.2f, 0.2f, 1.0f });YOTO::RenderCommand::Clear();m_Camera.SetPosition(m_CameraPosition);m_Camera.SetRotation(m_CameraRotation);YOTO::Renderer::BeginScene(m_Camera);{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.11f,y* 0.11f, 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);}}m_Texture->Bind();YOTO::Renderer::Submit(m_TextureShader, m_SquareVA, glm::scale(glm::mat4(1.0f), glm::vec3(1.5f)));//YOTO::Renderer::Submit(m_Shader, m_VertexArray);YOTO::Renderer::EndScene();}}void OnEvent(YOTO::Event& event)override {/*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::Ref<YOTO::Shader> m_Shader;YOTO::Ref<YOTO::VertexArray> m_VertexArray;YOTO::Ref<YOTO::Shader> m_BlueShader,m_TextureShader;YOTO::Ref<YOTO::VertexArray> m_SquareVA;YOTO::Ref<YOTO::Texture2D> m_Texture;YOTO::OrthographicCamera m_Camera;glm::vec3 m_CameraPosition;float m_CameraMoveSpeed = 5.0f;float m_CameraRotation = 0;float m_CameraRotationSpeed = 180.0f;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!

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

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

相关文章

04、全文检索 -- Solr -- 管理 Solr 的 core(使用命令和图形界面创建、删除 core,以及对core 目录下的各文件进行详细介绍)

目录 管理 Solr 的 core创建 Core方式1&#xff1a;solr 命令创建演示&#xff1a;使用 solr 命令创建 Core&#xff1a;演示&#xff1a;命令删除 Core&#xff08;彻底删除&#xff09; 方式2&#xff1a;图形界面创建Web控制台创建CoreWeb控制台删除 Core&#xff08;未彻底…

python使用fabric库

目录 一&#xff1a;介绍 二&#xff1a;远程命令执行 三&#xff1a;文件上传&#xff0c;下载 四&#xff1a;执行多台服务器命令 一&#xff1a;介绍 Fabric是一个Python库&#xff0c;用于简化SSH连接和自动化任务。它提供了一个简单的API来执行远程命令、上传和下载文…

软件工程(最简式总结)

目录 第一章:概述 1.软件危机的表现原因 2.常见的软件开发方法包括&#xff1a; 3.软件工程基本原则 4.软件工程三要素 5.设计模式的分类 6.针对变换型数据流设计步骤 7.针对事务型数据流设计步骤 第二章&#xff1a;软件过程 1.软件生命周期 2.软件过程模型 &…

【牛B得一塌糊涂】窗口归一化技术,改进医学图像的分布外泛化能力

窗口归一化技术&#xff0c;改进医学图像的分布外泛化能力 提出背景WIN、WIN-WIN、无参数归一化、特征级别数据增强如何提升分布外的泛化&#xff1f; 总结子问题1: 医学图像中的局部特征表示不足子问题2: 训练数据与新场景数据分布不一致子问题3: 模型在分布外数据上泛化能力不…

链表——C语言——day17

链表 链表是一种常见的重要的数据结构。它是动态地进行存储分配的一种结构。在用数组存放数据时&#xff0c;必须事先定义固定的长度&#xff08;即元素个数&#xff09;。链表则没有这种缺点&#xff0c;它根据需要开辟内存单元。 链表有一个“头指针“变量&#xff0c;图中…

docker exec命令流程

背景 在使用docker时&#xff0c;我们经常会使用docker的很多命令&#xff0c;比如docker exec等创建容器并执行命令&#xff0c;那么你知道这条命令背后的原理吗&#xff0c;本文就来解析下这条命令大致的执行流程图 docker exec命令 首先我们按照启动docker之后&#xff0…

集合的总结与复习

集合总结 1.1 什么是集合 集合可以看做是一个对象容器&#xff0c;可以存储很多个对象&#xff0c;管理多个对象及操作比较方便 1.2 集合与数组的区别 长度区别: 数组的长度是固定的而集合的长度是可变的&#xff1b; 存储数据类型的区别: 数组可以存储基本数据类型,也可以…

百无聊赖之JavaEE从入门到放弃(十八)其他常用类

目录 一.Math 类 二.Random 类 三.File类 四.枚举 一.Math 类 java.lang.Math 提供了一系列静态方法用于科学计算&#xff1b;常用方法如下&#xff1a; abs 绝对值 acos,asin,atan,cos,sin,tan 三角函数 sqrt 平方根 pow(double a, double b) a 的 b 次幂 max(double a,…

大数据分析|设计大数据分析的三个阶段

文献来源&#xff1a;Saggi M K, Jain S. A survey towards an integration of big data analytics to big insights for value-creation[J]. Information Processing & Management, 2018, 54(5): 758-790. 下载链接&#xff1a;链接&#xff1a;https://pan.baidu.com/s/1…

C++ pair+map+set+multimap+multiset+AVL树+红黑树(深度剖析)

文章目录 1. 前言2. 关联式容器3. pair——键值对4. 树形结构的关联式容器4.1 set4.1.1 set 的介绍4.1.2 set 的使用 4.2 map4.2.1 map 的介绍4.2.2 map 的使用 4.3 multiset4.3.1 multiset 的介绍4.3.2 multiset 的使用 4.4 multimap4.4.1 multimap 的介绍4.4.2 multimap 的使…

java处理ppt方案详解

需求 需要系统中展示的ppt案例有一个动态展示的效果&#xff0c;也就是要有动画的交互&#xff0c;要求支持浏览器直接打开预览 背景 目前已经实现了前端上传pptx文件&#xff0c;后端解析为png的图片&#xff0c;前端掉接口返回对应的图片&#xff0c;模拟播放ppt的效果 各种尝…

今天又接到了一个离谱的DEBUG订单

一、BUG程序 #include <iostream> #include <string>class Rectangle { private:int width;int height;public:Rectangle(int w, int h) {width w;height h;}void setWidth(int w) {width w;}void setHeight(int h) {height h;}int getArea() {return width *…