write me a c++ project that renders fbx scenes with directx11 and load scenes with assimp
- User
write me a c++ project that renders fbx scenes with directx11 and load scenes with assimp
- Assistant
This is an ambitious project for a single request, as it combines several complex topics: WinAPI, DirectX 11, Assimp, HLSL shaders, and 3D math. I'll provide a solid foundation for a basic renderer that can load and display static FBX models with diffuse textures and simple lighting.
Core Features:
- DirectX 11 Setup: Window creation, device, context, swap chain, render target, depth buffer, viewport.
- Assimp Integration: Load
.fbx(or other supported formats) models, traverse scene nodes, extract mesh data (vertices, normals, UVs, indices), and material properties (diffuse color, diffuse texture path). - Basic Lighting: Simple Blinn-Phong shading in HLSL.
- Texture Loading: Using
WICTextureLoader(part of DirectX Tool Kit) to load common image formats. - Camera: A simple orbiting camera.
- HLSL Shaders: Vertex and Pixel Shaders for rendering.
- Resource Management: Basic DirectX resource creation and release.
Project Structure:
DirectX11FBXRenderer/ ├── main.cpp ├── D3DApp.h ├── D3DApp.cpp ├── Camera.h ├── Camera.cpp ├── Mesh.h ├── Mesh.cpp ├── Model.h ├── Model.cpp ├── Shaders.hlsl ├── Utils.h <-- Helper functions/macros ├── Common.h <-- Common structs (Vertex, Material) ├── Libraries/ <-- You'll place Assimp and DirectX Tool Kit here │ ├── assimp/ │ │ ├── include/ │ │ └── lib/ │ ├── DirectXTex/ (or just WICTextureLoader.h/.cpp from DirectX Tool Kit) │ │ ├── include/ │ │ └── lib/ ├── Assets/ <-- Your FBX models and textures go here │ └── box.fbx │ └── texture.png
Prerequisites:
- Visual Studio 2019/2022: With "Desktop development with C++" workload installed.
- DirectX SDK (Optional but helpful): While DirectX 11 headers are part of the Windows SDK, the legacy SDK provided some utilities.
- Assimp:
- Download pre-built binaries or build from source: Assimp Releases
- You'll need
assimp-vc14x-mt.lib(or similar for your VS version) and its include files.
- DirectX Tool Kit for DirectX 11:
- Download from GitHub: DirectX Tool Kit
- Specifically, we need
WICTextureLoader.handWICTextureLoader.cpp. You can just copy these two files into your project or build the entire library and linkDirectXTK.lib. For simplicity, I'll assume you copy them.
- A Sample FBX Model: You can export a simple cube or sphere from Blender/Maya or download one. Make sure it has UV coordinates and a diffuse texture. Place it in the
Assetsfolder.
Project Setup in Visual Studio:
-
Create a New Project:
- Select "Empty Project" (C++).
- Name it
DirectX11FBXRenderer. - Click "Create".
-
Configure Project Properties:
-
Right-click on the project in Solution Explorer ->
Properties. -
Configuration:
All Configurations -
Platform:
All Platforms -
VC++ Directories:
Include Directories: Add the path to Assimp'sincludefolder (e.g.,$(SolutionDir)Libraries\assimp\include). Also, add the folder containingWICTextureLoader.h(e.g.,$(SolutionDir)if you copy it to the root, or$(SolutionDir)Libraries\DirectXTK\include).Library Directories: Add the path to Assimp'slibfolder (e.g.,$(SolutionDir)Libraries\assimp\lib). Also, the folder containingDirectXTK.libif you link the whole library.
-
Linker -> Input:
Additional Dependencies: Add the following libraries:d3d11.libd3dcompiler.libdxgi.libwinmm.libassimp-vc143-mt.lib(Adjust based on your VS version and Assimp build, e.g.,assimp-vc142-mt.lib)DirectXTK.lib(If you link the whole library, otherwiseWICTextureLoader.cppis compiled directly)
-
C/C++ -> Preprocessor:
Preprocessor Definitions: Add_CRT_SECURE_NO_WARNINGS(to suppress some warnings) andNOMINMAX.
-
C/C++ -> Language:
Conformance Mode: No (or leave as Default if you fix warnings otherwise)
-
Code Implementation:
1.
Utils.h#pragma once #include <windows.h> #include <string> #include <stdexcept> #include <d3d11.h> // Macro for COM error checking #ifndef HR #define HR(x) \ { \ HRESULT hr = (x); \ if (FAILED(hr)) \ { \ char s_str[256]; \ sprintf_s(s_str, "HRESULT: %x\nFile: %s\nLine: %d\n", hr, __FILE__, __LINE__); \ OutputDebugStringA(s_str); \ MessageBoxA(NULL, s_str, "Error", MB_OK | MB_ICONERROR); \ throw std::runtime_error(s_str); \ } \ } #endif // Smart pointer for COM objects template <typename T> class ComPtr { public: ComPtr() : m_ptr(nullptr) {} ComPtr(T* ptr) : m_ptr(ptr) { if (m_ptr) m_ptr->AddRef(); } ComPtr(const ComPtr& other) : m_ptr(other.m_ptr) { if (m_ptr) m_ptr->AddRef(); } ComPtr(ComPtr&& other) noexcept : m_ptr(other.m_ptr) { other.m_ptr = nullptr; } ~ComPtr() { Release(); } ComPtr& operator=(T* ptr) { if (m_ptr != ptr) { Release(); m_ptr = ptr; if (m_ptr) m_ptr->AddRef(); } return *this; } ComPtr& operator=(const ComPtr& other) { if (m_ptr != other.m_ptr) { Release(); m_ptr = other.m_ptr; if (m_ptr) m_ptr->AddRef(); } return *this; } ComPtr& operator=(ComPtr&& other) noexcept { if (m_ptr != other.m_ptr) { Release(); m_ptr = other.m_ptr; other.m_ptr = nullptr; } return *this; } T* operator->() { return m_ptr; } const T* operator->() const { return m_ptr; } T* Get() { return m_ptr; } const T* Get() const { return m_ptr; } T** GetAddressOf() { Release(); return &m_ptr; } T* const* GetAddressOf() const { return &m_ptr; } void Reset() { Release(); } operator bool() const { return m_ptr != nullptr; } private: T* m_ptr; void Release() { if (m_ptr) { m_ptr->Release(); m_ptr = nullptr; } } }; // Helper for wide string conversion inline std::wstring AnsiToWString(const std::string& ansi) { WCHAR wide[512]; MultiByteToWideChar(CP_ACP, 0, ansi.c_str(), -1, wide, 512); return wide; } inline std::string GetFileDirectory(const std::string& filePath) { size_t found = filePath.find_last_of("/\\"); if (found != std::string::npos) { return filePath.substr(0, found + 1); } return ""; } // For use with DirectXTK's WICTextureLoader.h #include <wincodec.h> // Required for WICTextureLoader #include "WICTextureLoader.h" // Copy this file into your project2.
Common.h#pragma once #include <DirectXMath.h> // For DirectXMath using namespace DirectX; // Vertex structure struct Vertex { XMFLOAT3 Pos; XMFLOAT3 Normal; XMFLOAT2 TexC; }; // Material structure struct Material { XMFLOAT4 Ambient; XMFLOAT4 Diffuse; XMFLOAT4 Specular; // Add more properties if needed (e.g., Shininess, Emissive) bool HasDiffuseTexture; }; // Constant buffers data structures struct CbPerFrame { XMMATRIX ViewProj; XMFLOAT3 LightPos; float Padding1; XMFLOAT4 LightColor; XMFLOAT3 CameraPos; float Padding2; }; struct CbPerObject { XMMATRIX World; XMFLOAT4 MaterialAmbient; XMFLOAT4 MaterialDiffuse; XMFLOAT4 MaterialSpecular; };3.
Shaders.hlslCreate this file in your project root. Ensure its "Item Type" property in VS is set toHLSL Compiler.// Constant Buffers cbuffer CbPerFrame : register(b0) { float4x4 g_ViewProj; // Combined View * Projection float3 g_LightPos; float g_Padding1; float4 g_LightColor; float3 g_CameraPos; float g_Padding2; } cbuffer CbPerObject : register(b1) { float4x4 g_World; float4 g_MaterialAmbient; float4 g_MaterialDiffuse; float4 g_MaterialSpecular; } // Textures and Samplers Texture2D g_DiffuseMap : register(t0); SamplerState g_Sampler : register(s0); // Vertex Shader Input struct VS_INPUT { float3 PosL : POSITION; // Position in Local Space float3 NormL : NORMAL; // Normal in Local Space float2 TexC : TEXCOORD; // Texture Coordinates }; // Vertex Shader Output (and Pixel Shader Input) struct VS_OUTPUT { float4 PosH : SV_POSITION; // Position in Homogeneous Clip Space float3 NormW : NORMAL; // Normal in World Space float3 PosW : POSITION; // Position in World Space float2 TexC : TEXCOORD; // Texture Coordinates }; // Vertex Shader VS_OUTPUT VS_Main(VS_INPUT vin) { VS_OUTPUT vout; // Transform position and normal to world space vout.PosW = mul(float4(vin.PosL, 1.0f), g_World).xyz; // For non-uniform scaling, normals should be transformed by inverse transpose of world matrix // For uniform scaling, just mul(vin.NormL, (float3x3)g_World); is fine. // For simplicity here, assuming uniform scaling or no scaling. vout.NormW = mul(vin.NormL, (float3x3)g_World); // Transform position to homogeneous clip space vout.PosH = mul(float4(vin.PosL, 1.0f), mul(g_World, g_ViewProj)); // Pass texture coordinates to pixel shader vout.TexC = vin.TexC; return vout; } // Pixel Shader float4 PS_Main(VS_OUTPUT pin) : SV_TARGET { // Normalize interpolated normal (can be non-normalized due to interpolation) float3 normal = normalize(pin.NormW); // Light direction (from surface to light) float3 lightDir = normalize(g_LightPos - pin.PosW); // View direction (from surface to camera) float3 viewDir = normalize(g_CameraPos - pin.PosW); // Ambient Term float4 ambient = g_MaterialAmbient * g_LightColor; // Diffuse Term (Lambertian) float diffuseFactor = saturate(dot(normal, lightDir)); float4 diffuse = g_MaterialDiffuse * g_LightColor * diffuseFactor; // Specular Term (Blinn-Phong) float3 halfVec = normalize(lightDir + viewDir); // Halfway vector float specularFactor = pow(saturate(dot(normal, halfVec)), 32.0f); // Power (shininess) float4 specular = g_MaterialSpecular * g_LightColor * specularFactor; // Sample texture float4 texColor = g_DiffuseMap.Sample(g_Sampler, pin.TexC); // Combine terms and multiply by texture color return texColor * (ambient + diffuse + specular); }4.
Camera.h#pragma once #include "Common.h" class Camera { public: Camera(); // Get/Set world camera position. XMVECTOR GetPositionXM() const; XMFLOAT3 GetPosition() const; void SetPosition(float x, float y, float z); // Get camera basis vectors. XMVECTOR GetRightXM() const; XMFLOAT3 GetRight() const; XMVECTOR GetUpXM() const; XMFLOAT3 GetUp() const; XMVECTOR GetLookXM() const; XMFLOAT3 GetLook() const; // Get View/Proj matrices. XMMATRIX GetView() const; XMMATRIX GetProj() const; XMMATRIX GetViewProj() const; // Set frustum. void SetLens(float fovY, float aspect, float zn, float zf); // Update camera movement (for orbiting) void Orbit(float dx, float dy); void Zoom(float dz); // Rebuilds the view matrix. void UpdateViewMatrix(); private: // Camera position (relative to target for orbit) XMFLOAT3 m_Position; XMFLOAT3 m_Target; // For orbiting camera, the point it looks at. XMFLOAT3 m_Up; // World up vector float m_Radius; // Orbit radius float m_Phi; // Polar angle (vertical rotation) float m_Theta; // Azimuthal angle (horizontal rotation) // Cache frustum properties. float m_NearZ; float m_FarZ; float m_Aspect; float m_FovY; // Cache View/Proj matrices. XMFLOAT4X4 m_View; XMFLOAT4X4 m_Proj; };5.
Camera.cpp#include "Camera.h" Camera::Camera() : m_Position(0.0f, 0.0f, 0.0f), m_Target(0.0f, 0.0f, 0.0f), m_Up(0.0f, 1.0f, 0.0f), m_Radius(5.0f), m_Phi(XM_PIDIV2), m_Theta(0.0f), m_NearZ(0.1f), m_FarZ(100.0f), m_Aspect(1.0f), m_FovY(0.25f * XM_PI) { XMStoreFloat4X4(&m_View, XMMatrixIdentity()); XMStoreFloat4X4(&m_Proj, XMMatrixIdentity()); } XMVECTOR Camera::GetPositionXM() const { return XMLoadFloat3(&m_Position); } XMFLOAT3 Camera::GetPosition() const { return m_Position; } void Camera::SetPosition(float x, float y, float z) { m_Position = XMFLOAT3(x, y, z); // For orbiting camera, this position is calculated, not set directly. // So this function might not be directly used for orbit camera. } XMVECTOR Camera::GetRightXM() const { XMMATRIX V = XMLoadFloat4X4(&m_View); return XMVectorSet(V.r[0].m128_f32[0], V.r[0].m128_f32[1], V.r[0].m128_f32[2], 0.0f); } XMFLOAT3 Camera::GetRight() const { XMFLOAT3 right; XMStoreFloat3(&right, GetRightXM()); return right; } XMVECTOR Camera::GetUpXM() const { XMMATRIX V = XMLoadFloat4X4(&m_View); return XMVectorSet(V.r[1].m128_f32[0], V.r[1].m128_f32[1], V.r[1].m128_f32[2], 0.0f); } XMFLOAT3 Camera::GetUp() const { XMFLOAT3 up; XMStoreFloat3(&up, GetUpXM()); return up; } XMVECTOR Camera::GetLookXM() const { XMMATRIX V = XMLoadFloat4X4(&m_View); return XMVectorSet(V.r[2].m128_f32[0], V.r[2].m128_f32[1], V.r[2].m128_f32[2], 0.0f); } XMFLOAT3 Camera::GetLook() const { XMFLOAT3 look; XMStoreFloat3(&look, GetLookXM()); return look; } XMMATRIX Camera::GetView() const { return XMLoadFloat4X4(&m_View); } XMMATRIX Camera::GetProj() const { return XMLoadFloat4X4(&m_Proj); } XMMATRIX Camera::GetViewProj() const { return XMMatrixMultiply(GetView(), GetProj()); } void Camera::SetLens(float fovY, float aspect, float zn, float zf) { m_FovY = fovY; m_Aspect = aspect; m_NearZ = zn; m_FarZ = zf; XMStoreFloat4X4(&m_Proj, XMMatrixPerspectiveFovLH(m_FovY, m_Aspect, m_NearZ, m_FarZ)); } void Camera::Orbit(float dx, float dy) { m_Theta += dx; // Rotate around Y axis m_Phi += dy; // Rotate up/down // Clamp phi to avoid gimbal lock and going upside down m_Phi = max(0.1f, min(XM_PI - 0.1f, m_Phi)); // 0.1 to PI - 0.1 } void Camera::Zoom(float dz) { m_Radius += dz; m_Radius = max(1.0f, m_Radius); // Minimum radius } void Camera::UpdateViewMatrix() { // Convert spherical coordinates to Cartesian for camera position m_Position.x = m_Target.x + m_Radius * sin(m_Phi) * sin(m_Theta); m_Position.z = m_Target.z + m_Radius * sin(m_Phi) * cos(m_Theta); m_Position.y = m_Target.y + m_Radius * cos(m_Phi); // Determine camera's up vector (world up is Y) XMVECTOR pos = XMLoadFloat3(&m_Position); XMVECTOR target = XMLoadFloat3(&m_Target); XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f); XMMATRIX V = XMMatrixLookAtLH(pos, target, up); XMStoreFloat4X4(&m_View, V); }6.
Mesh.h#pragma once #include "Common.h" #include "Utils.h" // For ComPtr #include <vector> #include <string> // Forward declaration for Assimp struct aiMesh; struct aiMaterial; class Mesh { public: Mesh(ID3D11Device* device, ID3D11DeviceContext* context); ~Mesh(); void Init(const std::vector<Vertex>& vertices, const std::vector<UINT>& indices, const Material& material, const std::string& texturePath, const std::string& directory); void Draw(ID3D11DeviceContext* context); Material GetMaterial() const { return m_Material; } void SetMaterial(const Material& material) { m_Material = material; } ID3D11ShaderResourceView* GetTextureSRV() const { return m_DiffuseMapSRV.Get(); } private: ComPtr<ID3D11Device> m_Device; ComPtr<ID3D11DeviceContext> m_Context; ComPtr<ID3D11Buffer> m_VertexBuffer; ComPtr<ID3D11Buffer> m_IndexBuffer; UINT m_IndexCount; Material m_Material; ComPtr<ID3D11ShaderResourceView> m_DiffuseMapSRV; void LoadTexture(const std::string& texturePath, const std::string& directory); };7.
Mesh.cpp#include "Mesh.h" Mesh::Mesh(ID3D11Device* device, ID3D11DeviceContext* context) : m_Device(device), m_Context(context), m_IndexCount(0) { } Mesh::~Mesh() { // ComPtr handles resource release automatically } void Mesh::Init(const std::vector<Vertex>& vertices, const std::vector<UINT>& indices, const Material& material, const std::string& texturePath, const std::string& directory) { m_Material = material; m_IndexCount = (UINT)indices.size(); // Create Vertex Buffer D3D11_BUFFER_DESC vbd; ZeroMemory(&vbd, sizeof(vbd)); vbd.Usage = D3D11_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof(Vertex) * (UINT)vertices.size(); vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA vinitData; ZeroMemory(&vinitData, sizeof(vinitData)); vinitData.pSysMem = vertices.data(); HR(m_Device->CreateBuffer(&vbd, &vinitData, m_VertexBuffer.GetAddressOf())); // Create Index Buffer D3D11_BUFFER_DESC ibd; ZeroMemory(&ibd, sizeof(ibd)); ibd.Usage = D3D11_USAGE_IMMUTABLE; ibd.ByteWidth = sizeof(UINT) * (UINT)indices.size(); ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA iinitData; ZeroMemory(&iinitData, sizeof(iinitData)); iinitData.pSysMem = indices.data(); HR(m_Device->CreateBuffer(&ibd, &iinitData, m_IndexBuffer.GetAddressOf())); // Load texture if path is provided and material has texture if (m_Material.HasDiffuseTexture && !texturePath.empty()) { LoadTexture(texturePath, directory); } } void Mesh::Draw(ID3D11DeviceContext* context) { UINT stride = sizeof(Vertex); UINT offset = 0; context->IASetVertexBuffers(0, 1, m_VertexBuffer.GetAddressOf(), &stride, &offset); context->IASetIndexBuffer(m_IndexBuffer.Get(), DXGI_FORMAT_R32_UINT, 0); context->DrawIndexed(m_IndexCount, 0, 0); } void Mesh::LoadTexture(const std::string& texturePath, const std::string& directory) { // Try to load from the exact path first std::wstring wTexturePath = AnsiToWString(texturePath); HRESULT hr = DirectX::CreateWICTextureFromFile(m_Device.Get(), m_Context.Get(), wTexturePath.c_str(), nullptr, m_DiffuseMapSRV.GetAddressOf()); if (FAILED(hr)) { // If not found, try combining with the model's directory std::string fullPath = directory + texturePath; wTexturePath = AnsiToWString(fullPath); hr = DirectX::CreateWICTextureFromFile(m_Device.Get(), m_Context.Get(), wTexturePath.c_str(), nullptr, m_DiffuseMapSRV.GetAddressOf()); if (FAILED(hr)) { OutputDebugStringA(("WARNING: Failed to load texture: " + texturePath + "\n").c_str()); m_Material.HasDiffuseTexture = false; // Mark as no texture if loading failed } } }8.
Model.h#pragma once #include "Mesh.h" #include "Common.h" #include <vector> #include <string> // Assimp includes #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> class Model { public: Model(ID3D11Device* device, ID3D11DeviceContext* context); ~Model(); void Load(const std::string& filePath); void Draw(ID3D11DeviceContext* context, const XMMATRIX& worldTransform); private: ID3D11Device* m_Device; ID3D11DeviceContext* m_Context; std::vector<Mesh*> m_Meshes; std::string m_Directory; // Directory where the model file is located // Assimp processing functions void ProcessNode(aiNode* node, const aiScene* scene); Mesh* ProcessMesh(aiMesh* mesh, const aiScene* scene); Material ProcessMaterial(aiMaterial* material); std::string LoadMaterialTexture(aiMaterial* material, aiTextureType type, const std::string& typeName); };9.
Model.cpp#include "Model.h" // For assimp debugging/error output #include <assimp/DefaultLogger.hpp> #include <assimp/LogStream.hpp> Model::Model(ID3D11Device* device, ID3D11DeviceContext* context) : m_Device(device), m_Context(context) { // Set up Assimp logger (optional, but good for debugging) // Assimp::DefaultLogger::create("assimp_log.txt", Assimp::Logger::VERBOSE); } Model::~Model() { for (Mesh* mesh : m_Meshes) { delete mesh; } m_Meshes.clear(); // Assimp::DefaultLogger::kill(); // Clean up logger } void Model::Load(const std::string& filePath) { m_Directory = GetFileDirectory(filePath); Assimp::Importer importer; // aiProcess_Triangulate: makes sure all faces are triangles // aiProcess_GenSmoothNormals: generates normals if not present // aiProcess_CalcTangentSpace: useful for normal mapping (not used here but good to know) // aiProcess_FlipUVs: flips UV coordinates vertically (DirectX uses top-left origin, some models might use bottom-left) // aiProcess_MakeLeftHanded: Converts to left-handed coordinate system (DirectX) const aiScene* scene = importer.ReadFile(filePath, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_MakeLeftHanded); if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { throw std::runtime_error("Assimp: " + std::string(importer.GetErrorString())); } ProcessNode(scene->mRootNode, scene); } void Model::Draw(ID3D11DeviceContext* context, const XMMATRIX& worldTransform) { // Update per-object constant buffer CbPerObject cbPerObject; XMStoreXMMATRIX(&cbPerObject.World, XMMatrixTranspose(worldTransform)); // Transpose for HLSL // Bind constant buffer to pixel shader (and vertex shader if needed) // This part should be handled by D3DApp before calling Model::Draw // For now, let's assume D3DApp passes the correct pointer or handles it. // It's better to update the constant buffer *before* drawing meshes. // So this function might not be directly responsible for CB updates. // Model::Draw should primarily call Mesh::Draw. for (Mesh* mesh : m_Meshes) { context->PSSetShaderResources(0, 1, mesh->GetTextureSRV() ? &mesh->GetTextureSRV() : nullptr); mesh->Draw(context); } } void Model::ProcessNode(aiNode* node, const aiScene* scene) { // Process all the node's meshes (if any) for (UINT i = 0; i < node->mNumMeshes; i++) { aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; m_Meshes.push_back(ProcessMesh(mesh, scene)); } // Then do the same for each of its children for (UINT i = 0; i < node->mNumChildren; i++) { ProcessNode(node->mChildren[i], scene); } } Mesh* Model::ProcessMesh(aiMesh* mesh, const aiScene* scene) { std::vector<Vertex> vertices; std::vector<UINT> indices; // Process vertices for (UINT i = 0; i < mesh->mNumVertices; i++) { Vertex vertex; vertex.Pos = XMFLOAT3(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z); vertex.Normal = XMFLOAT3(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z); if (mesh->mTextureCoords[0]) // Check if mesh has texture coordinates { vertex.TexC = XMFLOAT2(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y); } else { vertex.TexC = XMFLOAT2(0.0f, 0.0f); } vertices.push_back(vertex); } // Process indices for (UINT i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; for (UINT j = 0; j < face.mNumIndices; j++) { indices.push_back(face.mIndices[j]); } } // Process material aiMaterial* aiMaterial = scene->mMaterials[mesh->mMaterialIndex]; Material material = ProcessMaterial(aiMaterial); std::string texturePath = LoadMaterialTexture(aiMaterial, aiTextureType_DIFFUSE, "texture_diffuse"); Mesh* newMesh = new Mesh(m_Device, m_Context); newMesh->Init(vertices, indices, material, texturePath, m_Directory); return newMesh; } Material Model::ProcessMaterial(aiMaterial* material) { Material mat; aiColor3D color; // Ambient material->Get(AI_MATKEY_COLOR_AMBIENT, color); mat.Ambient = XMFLOAT4(color.r, color.g, color.b, 1.0f); // Diffuse material->Get(AI_MATKEY_COLOR_DIFFUSE, color); mat.Diffuse = XMFLOAT4(color.r, color.g, color.b, 1.0f); // Specular material->Get(AI_MATKEY_COLOR_SPECULAR, color); mat.Specular = XMFLOAT4(color.r, color.g, color.b, 1.0f); // Check for diffuse texture mat.HasDiffuseTexture = (material->GetTextureCount(aiTextureType_DIFFUSE) > 0); return mat; } std::string Model::LoadMaterialTexture(aiMaterial* material, aiTextureType type, const std::string& typeName) { if (material->GetTextureCount(type) > 0) { aiString str; material->GetTexture(type, 0, &str); return str.C_Str(); } return ""; }10.
D3DApp.h#pragma once #include <windows.h> #include <d3d11.h> #include <DirectXMath.h> #include "Utils.h" #include "Common.h" #include "Camera.h" #include "Model.h" class D3DApp { public: D3DApp(HINSTANCE hInstance); ~D3DApp(); HINSTANCE GetAppInstance() const; HWND GetMainWnd() const; float GetAspectRatio() const; int Run(); virtual bool Initialize(); virtual void OnResize(); virtual void Update(float dt); virtual void Draw(); virtual LRESULT MsgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); protected: bool InitMainWindow(); bool InitDirect3D(); void CalculateFrameStats(); void CompileShader(const std::wstring& filename, const std::string& entryPoint, const std::string& shaderModel, ComPtr<ID3DBlob>& blobOut); void CreateConstantBuffer(UINT byteWidth, ComPtr<ID3D11Buffer>& bufferOut); void SetupShaders(); HINSTANCE m_hAppInstance; HWND m_hMainWnd; bool m_bMinimized; bool m_bMaximized; bool m_bResizing; UINT m_4xMsaaQuality; ComPtr<ID3D11Device> m_d3dDevice; ComPtr<ID3D11DeviceContext> m_d3dContext; ComPtr<IDXGISwapChain> m_SwapChain; ComPtr<ID3D11Texture2D> m_DepthStencilBuffer; ComPtr<ID3D11RenderTargetView> m_RenderTargetView; ComPtr<ID3D11DepthStencilView> m_DepthStencilView; D3D11_VIEWPORT m_ScreenViewport; // Shaders and Input Layout ComPtr<ID3D11VertexShader> m_VertexShader; ComPtr<ID3D11PixelShader> m_PixelShader; ComPtr<ID3D11InputLayout> m_InputLayout; // Constant Buffers ComPtr<ID3D11Buffer> m_CbPerFrame; ComPtr<ID3D11Buffer> m_CbPerObject; // Sampler State ComPtr<ID3D11SamplerState> m_SamplerState; // Rendering objects Camera m_Camera; Model* m_Model; XMFLOAT3 m_LightPos; XMFLOAT4 m_LightColor; // Mouse input POINT m_LastMousePos; };11.
D3DApp.cpp#include "D3DApp.h" #include <sstream> #include <vector> #include <DirectXColors.h> #include <d3dcompiler.h> // For D3DCompile // Global App pointer for WinProc D3DApp* g_d3dApp = nullptr; LRESULT CALLBACK MainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { return g_d3dApp->MsgProc(hwnd, msg, wParam, lParam); } D3DApp::D3DApp(HINSTANCE hInstance) : m_hAppInstance(hInstance), m_hMainWnd(nullptr), m_bMinimized(false), m_bMaximized(false), m_bResizing(false), m_4xMsaaQuality(0), m_Model(nullptr) { g_d3dApp = this; // Initial camera setup m_Camera.SetLens(0.25f * XM_PI, GetAspectRatio(), 1.0f, 1000.0f); m_Camera.UpdateViewMatrix(); // Ensure initial view matrix is set // Light setup m_LightPos = XMFLOAT3(0.0f, 5.0f, -5.0f); m_LightColor = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); } D3DApp::~D3DApp() { if (m_d3dContext) m_d3dContext->ClearState(); // Clear all bound resources delete m_Model; } HINSTANCE D3DApp::GetAppInstance() const { return m_hAppInstance; } HWND D3DApp::GetMainWnd() const { return m_hMainWnd; } float D3DApp::GetAspectRatio() const { RECT R; GetClientRect(m_hMainWnd, &R); return (float)R.right / R.bottom; } int D3DApp::Run() { MSG msg = {0}; // Use a high-resolution timer for frame rate __int64 cntsPerSec = 0; QueryPerformanceFrequency((LARGE_INTEGER*)&cntsPerSec); float secsPerCnt = 1.0f / (float)cntsPerSec; __int64 prevCnt = 0; QueryPerformanceCounter((LARGE_INTEGER*)&prevCnt); while (msg.message != WM_QUIT) { if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { __int64 currCnt = 0; QueryPerformanceCounter((LARGE_INTEGER*)&currCnt); float dt = (currCnt - prevCnt) * secsPerCnt; prevCnt = currCnt; if (!m_bMinimized) { CalculateFrameStats(); Update(dt); Draw(); } else { Sleep(100); } } } return (int)msg.wParam; } bool D3DApp::Initialize() { if (!InitMainWindow()) return false; if (!InitDirect3D()) return false; OnResize(); // Setup Shaders SetupShaders(); // Create Constant Buffers CreateConstantBuffer(sizeof(CbPerFrame), m_CbPerFrame); CreateConstantBuffer(sizeof(CbPerObject), m_CbPerObject); // Create Sampler State D3D11_SAMPLER_DESC sampDesc; ZeroMemory(&sampDesc, sizeof(sampDesc)); sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; sampDesc.MinLOD = 0; sampDesc.MaxLOD = D3D11_FLOAT32_MAX; HR(m_d3dDevice->CreateSamplerState(&sampDesc, m_SamplerState.GetAddressOf())); // Load Model m_Model = new Model(m_d3dDevice.Get(), m_d3dContext.Get()); try { // IMPORTANT: Replace with the actual path to your FBX model m_Model->Load("Assets/box.fbx"); } catch (const std::runtime_error& e) { MessageBoxA(m_hMainWnd, e.what(), "Model Loading Error", MB_OK | MB_ICONERROR); return false; } return true; } void D3DApp::OnResize() { // Release the old views to resize the swap chain. m_RenderTargetView.Reset(); m_DepthStencilView.Reset(); m_DepthStencilBuffer.Reset(); // Resize the swap chain and recreate the render target view. HR(m_SwapChain->ResizeBuffers(1, 0, 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0)); ComPtr<ID3D11Texture2D> backBuffer; HR(m_SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)backBuffer.GetAddressOf())); HR(m_d3dDevice->CreateRenderTargetView(backBuffer.Get(), nullptr, m_RenderTargetView.GetAddressOf())); // Create the depth/stencil buffer and view. D3D11_TEXTURE2D_DESC depthStencilDesc; depthStencilDesc.Width = (UINT)(m_ScreenViewport.Width = GetAspectRatio() * m_ScreenViewport.Height); depthStencilDesc.Height = (UINT)m_ScreenViewport.Height; depthStencilDesc.MipLevels = 1; depthStencilDesc.ArraySize = 1; depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; // 24-bit depth, 8-bit stencil depthStencilDesc.SampleDesc.Count = 1; // No MSAA for simplicity depthStencilDesc.SampleDesc.Quality = 0; depthStencilDesc.Usage = D3D11_USAGE_DEFAULT; depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthStencilDesc.CPUAccessFlags = 0; depthStencilDesc.MiscFlags = 0; HR(m_d3dDevice->CreateTexture2D(&depthStencilDesc, nullptr, m_DepthStencilBuffer.GetAddressOf())); HR(m_d3dDevice->CreateDepthStencilView(m_DepthStencilBuffer.Get(), nullptr, m_DepthStencilView.GetAddressOf())); // Bind the render target view and depth/stencil view to the pipeline. m_d3dContext->OMSetRenderTargets(1, m_RenderTargetView.GetAddressOf(), m_DepthStencilView.Get()); // Set the viewport. m_ScreenViewport.TopLeftX = 0; m_ScreenViewport.TopLeftY = 0; m_ScreenViewport.MinDepth = 0.0f; m_ScreenViewport.MaxDepth = 1.0f; m_d3dContext->RSSetViewports(1, &m_ScreenViewport); // Update camera projection matrix m_Camera.SetLens(0.25f * XM_PI, GetAspectRatio(), 1.0f, 1000.0f); } void D3DApp::Update(float dt) { // Update camera position m_Camera.UpdateViewMatrix(); // Update constant buffer for frame data CbPerFrame cbPerFrame; XMStoreXMMATRIX(&cbPerFrame.ViewProj, XMMatrixTranspose(m_Camera.GetViewProj())); // Transpose for HLSL cbPerFrame.LightPos = m_LightPos; cbPerFrame.LightColor = m_LightColor; cbPerFrame.CameraPos = m_Camera.GetPosition(); m_d3dContext->UpdateSubresource(m_CbPerFrame.Get(), 0, nullptr, &cbPerFrame, 0, 0); } void D3DApp::Draw() { m_d3dContext->ClearRenderTargetView(m_RenderTargetView.Get(), DirectX::Colors::DarkSlateGray); m_d3dContext->ClearDepthStencilView(m_DepthStencilView.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); m_d3dContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // Set shaders m_d3dContext->VSSetShader(m_VertexShader.Get(), nullptr, 0); m_d3dContext->PSSetShader(m_PixelShader.Get(), nullptr, 0); // Set constant buffers m_d3dContext->VSSetConstantBuffers(0, 1, m_CbPerFrame.GetAddressOf()); m_d3dContext->PSSetConstantBuffers(0, 1, m_CbPerFrame.GetAddressOf()); m_d3dContext->VSSetConstantBuffers(1, 1, m_CbPerObject.GetAddressOf()); m_d3dContext->PSSetConstantBuffers(1, 1, m_CbPerObject.GetAddressOf()); // Set sampler state for textures m_d3dContext->PSSetSamplers(0, 1, m_SamplerState.GetAddressOf()); // Draw the model if (m_Model) { XMMATRIX world = XMMatrixIdentity(); // Identity world matrix for now, or apply transformations // Example: XMMATRIX world = XMMatrixRotationY(m_Timer.TotalTime() * 0.5f); // Update per-object constant buffer CbPerObject cbPerObject; XMStoreXMMATRIX(&cbPerObject.World, XMMatrixTranspose(world)); // Transpose for HLSL // For simplicity, let's just use arbitrary material values here // In a real application, you'd get these from the mesh material. // The Mesh class already stores its material, you could read it back. cbPerObject.MaterialAmbient = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f); cbPerObject.MaterialDiffuse = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f); cbPerObject.MaterialSpecular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); m_d3dContext->UpdateSubresource(m_CbPerObject.Get(), 0, nullptr, &cbPerObject, 0, 0); m_Model->Draw(m_d3dContext.Get(), world); } HR(m_SwapChain->Present(0, 0)); // No vsync for simplicity } LRESULT D3DApp::MsgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { // WM_ACTIVATE is sent when the window is activated or deactivated. case WM_ACTIVATE: if (LOWORD(wParam) == WA_INACTIVE) { // Pause } else { // Resume } return 0; // WM_SIZE is sent when the window's size changes. case WM_SIZE: // Save the new client area dimensions. RECT R; GetClientRect(m_hMainWnd, &R); m_ScreenViewport.Width = (float)R.right; m_ScreenViewport.Height = (float)R.bottom; if (m_d3dDevice) { if (wParam == SIZE_MINIMIZED) { m_bMinimized = true; m_bMaximized = false; } else if (wParam == SIZE_MAXIMIZED) { m_bMinimized = false; m_bMaximized = true; OnResize(); } else if (wParam == SIZE_RESTORED) { // Restoring from minimized or maximized states if (m_bMinimized || m_bMaximized) { m_bMinimized = false; m_bMaximized = false; OnResize(); } // Resizing else if (m_bResizing) { // Do nothing here, OnResize will be called when user releases mouse } else // API call { OnResize(); } } } return 0; // WM_EXITSIZEMOVE is sent when the user finishes dragging the resize bars. case WM_EXITSIZEMOVE: m_bResizing = false; OnResize(); return 0; // WM_DESTROY is sent when the window is being destroyed. case WM_DESTROY: PostQuitMessage(0); return 0; // The WM_MENUCHAR message occurs when a menu is active and the user presses a key that does not correspond to any mnemonic or accelerator key. case WM_MENUCHAR: // Don't beep when we alt-enter to fullscreen. return MAKELRESULT(0, MNC_NOREMOVE); // Catching LBUTTONDOWN and RBUTTONDOWN to start camera movement case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: m_LastMousePos.x = LOWORD(lParam); m_LastMousePos.y = HIWORD(lParam); SetCapture(hwnd); // Capture mouse input return 0; case WM_LBUTTONUP: case WM_RBUTTONUP: ReleaseCapture(); // Release mouse capture return 0; case WM_MOUSEMOVE: if (wParam & MK_LBUTTON) // Left button for orbiting { float dx = XMConvertToRadians(0.25f * (LOWORD(lParam) - m_LastMousePos.x)); float dy = XMConvertToRadians(0.25f * (HIWORD(lParam) - m_LastMousePos.y)); m_Camera.Orbit(dx, dy); } else if (wParam & MK_RBUTTON) // Right button for zooming { float dz = 0.01f * (HIWORD(lParam) - m_LastMousePos.y); // Vertical movement for zoom m_Camera.Zoom(dz); } m_LastMousePos.x = LOWORD(lParam); m_LastMousePos.y = HIWORD(lParam); return 0; // WM_KEYUP is sent when a key is released. case WM_KEYUP: if (wParam == VK_ESCAPE) { PostQuitMessage(0); } return 0; } return DefWindowProc(hwnd, msg, wParam, lParam); } bool D3DApp::InitMainWindow() { WNDCLASS wc; wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = MainWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = m_hAppInstance; wc.hIcon = LoadIcon(0, IDI_APPLICATION); wc.hCursor = LoadCursor(0, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH); wc.lpszMenuName = 0; wc.lpszClassName = L"D3D11WindowClass"; if (!RegisterClass(&wc)) { MessageBox(0, L"RegisterClass Failed.", 0, 0); return false; } // Compute window rectangle dimensions based on client area dimensions. RECT R = { 0, 0, 800, 600 }; AdjustWindowRect(&R, WS_OVERLAPPEDWINDOW, false); int width = R.right - R.left; int height = R.bottom - R.top; m_hMainWnd = CreateWindow(L"D3D11WindowClass", L"FBX Renderer (DirectX 11 & Assimp)", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, width, height, 0, 0, m_hAppInstance, 0); if (!m_hMainWnd) { MessageBox(0, L"CreateWindow Failed.", 0, 0); return false; } ShowWindow(m_hMainWnd, SW_SHOW); UpdateWindow(m_hMainWnd); return true; } bool D3DApp::InitDirect3D() { UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featureLevel; HRESULT hr = D3D11CreateDevice( nullptr, // Default adapter D3D_DRIVER_TYPE_HARDWARE, nullptr, // No software device createDeviceFlags, nullptr, 0, // Default feature levels D3D11_SDK_VERSION, m_d3dDevice.GetAddressOf(), &featureLevel, m_d3dContext.GetAddressOf()); if (FAILED(hr)) { MessageBox(0, L"D3D11CreateDevice Failed.", 0, 0); return false; } if (featureLevel != D3D_FEATURE_LEVEL_11_0) { MessageBox(0, L"Direct3D Feature Level 11.0 is not supported.", 0, 0); return false; } HR(m_d3dDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m_4xMsaaQuality)); // assert(m_4xMsaaQuality > 0); // Need at least 4x MSAA quality DXGI_SWAP_CHAIN_DESC sd; sd.BufferDesc.Width = 0; // Use window width sd.BufferDesc.Height = 0; // Use window height sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // No MSAA for simplicity in this example sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = 1; sd.OutputWindow = m_hMainWnd; sd.Windowed = true; // Windowed mode sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; sd.Flags = 0; // Create swap chain ComPtr<IDXGIDevice> dxgiDevice; HR(m_d3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)dxgiDevice.GetAddressOf())); ComPtr<IDXGIAdapter> dxgiAdapter; HR(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)dxgiAdapter.GetAddressOf())); ComPtr<IDXGIFactory> dxgiFactory; HR(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)dxgiFactory.GetAddressOf())); HR(dxgiFactory->CreateSwapChain(m_d3dDevice.Get(), &sd, m_SwapChain.GetAddressOf())); return true; } void D3DApp::CalculateFrameStats() { static int frameCnt = 0; static float timeElapsed = 0.0f; static float lastTime = 0.0f; __int64 currentTime = 0; __int64 frequency = 0; QueryPerformanceCounter((LARGE_INTEGER*)¤tTime); QueryPerformanceFrequency((LARGE_INTEGER*)&frequency); float dt = (currentTime - lastTime) / (float)frequency; lastTime = (float)currentTime; frameCnt++; timeElapsed += dt; if (timeElapsed >= 1.0f) { float fps = (float)frameCnt / timeElapsed; std::wstringstream outs; outs.precision(6); outs << L"FBX Renderer (DirectX 11 & Assimp) " << L"FPS: " << fps; SetWindowText(m_hMainWnd, outs.str().c_str()); frameCnt = 0; timeElapsed = 0.0f; } } void D3DApp::CompileShader(const std::wstring& filename, const std::string& entryPoint, const std::string& shaderModel, ComPtr<ID3DBlob>& blobOut) { UINT flags = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) || defined(_DEBUG) flags |= D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION; #endif ComPtr<ID3DBlob> errorBlob; HRESULT hr = D3DCompileFromFile(filename.c_str(), nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint.c_str(), shaderModel.c_str(), flags, 0, blobOut.GetAddressOf(), errorBlob.GetAddressOf()); if (FAILED(hr)) { if (errorBlob) { OutputDebugStringA((char*)errorBlob->GetBufferPointer()); MessageBoxA(m_hMainWnd, (char*)errorBlob->GetBufferPointer(), "Shader Compilation Error", MB_OK | MB_ICONERROR); } else { MessageBox(m_hMainWnd, L"Unknown shader compilation error.", L"Error", MB_OK | MB_ICONERROR); } throw std::runtime_error("Shader compilation failed."); } } void D3DApp::CreateConstantBuffer(UINT byteWidth, ComPtr<ID3D11Buffer>& bufferOut) { D3D11_BUFFER_DESC cbDesc; ZeroMemory(&cbDesc, sizeof(cbDesc)); cbDesc.ByteWidth = byteWidth; cbDesc.Usage = D3D11_USAGE_DEFAULT; // D3D11_USAGE_DYNAMIC if you use Map/Unmap cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbDesc.CPUAccessFlags = 0; // D3D11_CPU_ACCESS_WRITE if DYNAMIC HR(m_d3dDevice->CreateBuffer(&cbDesc, nullptr, bufferOut.GetAddressOf())); } void D3DApp::SetupShaders() { ComPtr<ID3DBlob> vsBlob, psBlob; // Compile Vertex Shader CompileShader(L"Shaders.hlsl", "VS_Main", "vs_5_0", vsBlob); HR(m_d3dDevice->CreateVertexShader(vsBlob->GetBufferPointer(), vsBlob->GetBufferSize(), nullptr, m_VertexShader.GetAddressOf())); // Create Input Layout D3D11_INPUT_ELEMENT_DESC inputLayout[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0} }; HR(m_d3dDevice->CreateInputLayout(inputLayout, ARRAYSIZE(inputLayout), vsBlob->GetBufferPointer(), vsBlob->GetBufferSize(), m_InputLayout.GetAddressOf())); m_d3dContext->IASetInputLayout(m_InputLayout.Get()); // Compile Pixel Shader CompileShader(L"Shaders.hlsl", "PS_Main", "ps_5_0", psBlob); HR(m_d3dDevice->CreatePixelShader(psBlob->GetBufferPointer(), psBlob->GetBufferSize(), nullptr, m_PixelShader.GetAddressOf())); }12.
main.cpp#include "D3DApp.h" #include <windows.h> // For WinMain int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int showCmd) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif D3DApp theApp(hInstance); if (!theApp.Initialize()) return 0; return theApp.Run(); }
How to Build and Run:
- Create Project and Configure: Follow the "Project Setup in Visual Studio" steps meticulously.
- Add Files: Add all the
.h,.cpp, and.hlslfiles to your Visual Studio project. - Download and Place Libraries:
- Create a
Librariesfolder in your project root. - Inside
Libraries, createassimp. Copyincludeandlibfolders from Assimp download intoLibraries/assimp. - Copy
WICTextureLoader.handWICTextureLoader.cppdirectly into your project's root folder (orLibraries/DirectXTK/includeandLibraries/DirectXTK/srcif you prefer to build the library). If you copyWICTextureLoader.cppinto your project, you don't need to linkDirectXTK.lib.
- Create a
- Create Assets Folder: Create an
Assetsfolder in your project root. Place your.fbxmodel (e.g.,box.fbx) and its associated diffuse texture (e.g.,texture.png) inside this folder. - Update Model Path: In
D3DApp.cpp, find the linem_Model->Load("Assets/box.fbx");and update"Assets/box.fbx"to the correct path and filename of your FBX model. - Build: Build the solution (Ctrl+Shift+B). If there are errors, double-check your project settings, file paths, and ensure you have all necessary libraries.
- Run: Run the application (F5).
You should see a window rendering your FBX model with simple lighting. You can orbit the camera by holding the left mouse button and dragging, and zoom in/out by holding the right mouse button and dragging vertically.
Further Improvements and Next Steps:
- Error Handling: The
HRmacro is basic. More robust error logging and user feedback would be beneficial. - Resource Management: While
ComPtrhelps, a more comprehensive resource manager (e.g., for textures, shaders) would prevent redundant loading and improve performance. - Material System: Expand
Materialstruct and shader to support more properties: specular power, emissive, normal maps, metallic/roughness (PBR). - Animation: Assimp supports skeletal animation. This is a significant undertaking, requiring skinning in the vertex shader, bone matrices, and animation blending.
- Scene Graph: Implement a proper scene graph for hierarchical transformations (nodes in Assimp are already hierarchical, but you'd want to represent this in your own engine).
- Camera Controls: Implement WASD controls, flying camera, etc.
- Rendering Pipeline:
- Lighting: Implement multiple lights (point, directional, spot).
- Post-processing: Bloom, SSAO, anti-aliasing.
- Shadows: Essential for realistic rendering.
- UI: Add a UI using libraries like Dear ImGui to adjust parameters (light position, material properties, camera speed) at runtime.
- Optimization: Frustum culling, occlusion culling, instancing for multiple identical objects.
- Skybox/Skydome: For environmental lighting.
- Model Instancing: If you need to draw the same model many times.
This project provides a strong starting point for exploring DirectX 11 rendering with Assimp. Good luck!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.