Procházet zdrojové kódy

feat : wip - abstract mesh for scene

Heedong Lee před 4 roky
rodič
revize
8a4ae1a18e

+ 13
- 0
Samples/Data/shaders/ObjMeshShader/objmesh.frag Zobrazit soubor

@@ -0,0 +1,13 @@
1
+#version 450
2
+
3
+layout (binding = 1) uniform sampler2D samplerColor;
4
+
5
+layout (location = 0) in vec3 fragColor;
6
+layout (location = 1) in vec2 fragTexCoord;
7
+
8
+layout (location = 0) out vec4 outFragColor;
9
+
10
+void main() 
11
+{
12
+	outFragColor = texture(samplerColor, fragTexCoord);
13
+}

binární
Samples/Data/shaders/ObjMeshShader/objmesh.frag.spv Zobrazit soubor


+ 28
- 0
Samples/Data/shaders/ObjMeshShader/objmesh.vert Zobrazit soubor

@@ -0,0 +1,28 @@
1
+#version 450
2
+
3
+layout (location = 0) in vec3 inPos;
4
+layout (location = 1) in vec3 inColor;
5
+layout (location = 2) in vec3 inNormal;
6
+layout (location = 3) in vec2 inTexCoord;
7
+
8
+layout (binding = 0) uniform UBO
9
+{
10
+	mat4 projection;
11
+	mat4 model;
12
+	mat4 view;
13
+} ubo;
14
+
15
+layout (location = 0) out vec3 fragColor;
16
+layout (location = 1) out vec2 fragTexCoord;
17
+
18
+out gl_PerVertex
19
+{
20
+    vec4 gl_Position;
21
+};
22
+
23
+void main()
24
+{
25
+	gl_Position = ubo.projection * ubo.view * ubo.model * vec4(inPos, 1.0);
26
+	fragColor = inColor;
27
+	fragTexCoord = inTexCoord;
28
+}

binární
Samples/Data/shaders/ObjMeshShader/objmesh.vert.spv Zobrazit soubor


+ 256
- 0
Samples/PBRScene/DKGLDemoScene.cpp Zobrazit soubor

@@ -0,0 +1,256 @@
1
+#include <cstddef>
2
+#include "app.h"
3
+#include "util.h"
4
+
5
+#include "StaticMesh.h"
6
+
7
+struct SceneUniformBuffer
8
+{
9
+    DKMatrix4 projectionMatrix;
10
+    DKMatrix4 modelMatrix;
11
+    DKMatrix4 viewMatrix;
12
+};
13
+
14
+class DKGLDemo : public SampleApp
15
+{
16
+    DKObject<DKWindow> window;
17
+	DKObject<DKThread> renderThread;
18
+	DKAtomicNumber32 runningRenderThread;
19
+	DKObject<StaticMesh> sampleMesh;
20
+
21
+    DKObject<DKGpuBuffer> sceneUniformBuffer;
22
+    SceneUniformBuffer* sceneBufferData = nullptr;
23
+
24
+public:
25
+    void LoadResource()
26
+    {
27
+        DKString vertexShaderPath
28
+            = resourcePool.ResourceFilePath("shaders/ObjMeshShader/objmesh.vert.spv");
29
+        DKString fragMentShaderPath
30
+            = resourcePool.ResourceFilePath("shaders/ObjMeshShader/objmesh.frag.spv");
31
+        DKString texturePath
32
+            = resourcePool.ResourceFilePath("meshes/VikingRoom/viking_room.png");
33
+
34
+        sampleMesh->LoadShaderFromFile(resourcePool, vertexShaderPath, DKShaderStage::Vertex);
35
+        sampleMesh->LoadShaderFromFile(resourcePool, fragMentShaderPath, DKShaderStage::Fragment);
36
+        sampleMesh->LoadTextureFromFile(resourcePool, texturePath);
37
+    }
38
+
39
+	void LoadRenderResource(DKObject<DKCommandQueue> queue)
40
+	{
41
+		DKLog("Loading Static Meshes");
42
+        DKString path = resourcePool.ResourceFilePath("meshes/VikingRoom/viking_room.obj");
43
+        sampleMesh->LoadMeshResourceFromFile(queue->Device(), resourcePool, path);
44
+        sampleMesh->LoadRenderResourceShader(queue->Device(), DKShaderStage::Vertex);
45
+        sampleMesh->LoadRenderResourceShader(queue->Device(), DKShaderStage::Fragment);
46
+        sampleMesh->LoadRenderResourceTexture(queue);
47
+	}
48
+
49
+    void SetupPipeline(DKRenderPipelineDescriptor& pipelineDesc)
50
+    {
51
+        sampleMesh->SetupPipelineDecriptor(pipelineDesc);
52
+    }
53
+
54
+    void SetupMaterial(DKObject<DKGraphicsDevice> device)
55
+    {
56
+        sampleMesh->SetupMaterial(device);
57
+    }
58
+
59
+    void SetupSceneUniformBuffer(DKObject<DKGraphicsDevice> device)
60
+    {
61
+        // should Go to Scene Uniform Buffer
62
+        sceneUniformBuffer = device->CreateBuffer(sizeof(SceneUniformBuffer)
63
+            , DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
64
+
65
+        sceneBufferData = reinterpret_cast<SceneUniformBuffer*>(sceneUniformBuffer->Contents());
66
+        sceneBufferData->projectionMatrix = DKMatrix4::identity;
67
+        sceneBufferData->modelMatrix = DKMatrix4::identity;
68
+        sceneBufferData->viewMatrix = DKMatrix4::identity;
69
+        sceneUniformBuffer->Flush();
70
+
71
+        //DKAffineTransform3 trans;
72
+        //trans.Multiply(DKLinearTransform3().Scale(0.5).Rotate(DKVector3(0,1,0), DKGL_PI * 0.5));
73
+        //ubo.modelMatrix.Multiply(trans.Matrix4());
74
+
75
+        //memcpy(uboBuffer->Contents(), &ubo, sizeof(ubo));
76
+
77
+        sampleMesh->SetupExternalUniformBuffer(sceneUniformBuffer, sizeof(SceneUniformBuffer), 0);
78
+    }
79
+
80
+    void EncodeScene(DKObject<DKRenderCommandEncoder> encoder)
81
+    {
82
+        sampleMesh->EncodeRenderCommand(encoder);
83
+    }
84
+
85
+	void RenderThread(void)
86
+	{
87
+		DKObject<DKGraphicsDevice> device = DKGraphicsDevice::SharedInstance();
88
+        DKObject<DKCommandQueue> queue = device->CreateCommandQueue(DKCommandQueue::Graphics);
89
+
90
+        LoadRenderResource(queue);
91
+
92
+		DKObject<DKSwapChain> swapChain = queue->CreateSwapChain(window);
93
+
94
+		DKRenderPipelineDescriptor pipelineDescriptor;
95
+        // setup color-attachment render-targets
96
+        pipelineDescriptor.colorAttachments.Resize(1);
97
+        pipelineDescriptor.colorAttachments.Value(0).pixelFormat = swapChain->ColorPixelFormat();
98
+        pipelineDescriptor.colorAttachments.Value(0).blendState.enabled = false;
99
+        pipelineDescriptor.colorAttachments.Value(0).blendState.sourceRGBBlendFactor = DKBlendFactor::SourceAlpha;
100
+        pipelineDescriptor.colorAttachments.Value(0).blendState.destinationRGBBlendFactor = DKBlendFactor::OneMinusSourceAlpha;
101
+        // setup depth-stencil
102
+        pipelineDescriptor.depthStencilAttachmentPixelFormat = DKPixelFormat::D32Float;
103
+        pipelineDescriptor.depthStencilDescriptor.depthWriteEnabled = true;
104
+        pipelineDescriptor.depthStencilDescriptor.depthCompareFunction = DKCompareFunctionLessEqual;
105
+        // setup topology and rasterization
106
+        pipelineDescriptor.primitiveTopology = DKPrimitiveType::Triangle;
107
+        pipelineDescriptor.frontFace = DKFrontFace::CCW;
108
+        pipelineDescriptor.triangleFillMode = DKTriangleFillMode::Fill;
109
+        pipelineDescriptor.depthClipMode = DKDepthClipMode::Clip;
110
+        pipelineDescriptor.cullMode = DKCullMode::Back;
111
+        pipelineDescriptor.rasterizationEnabled = true;
112
+
113
+        SetupPipeline(pipelineDescriptor);
114
+
115
+		DKPipelineReflection reflection;
116
+		DKObject<DKRenderPipelineState> pipelineState = device->CreateRenderPipeline(pipelineDescriptor, &reflection);
117
+		if (pipelineState)
118
+		{
119
+            PrintPipelineReflection(&reflection, DKLogCategory::Verbose);
120
+		}
121
+
122
+        SetupMaterial(device);
123
+        SetupSceneUniformBuffer(device);
124
+
125
+        DKObject<DKTexture> depthBuffer = nullptr;
126
+
127
+        DKCamera camera;
128
+        DKVector3 cameraPosition = { 0, 5, 10 };
129
+        DKVector3 cameraTartget = { 0, 0, 0 };
130
+
131
+        DKAffineTransform3 tm(DKLinearTransform3().Scale(5).Rotate(DKVector3(-1,0,0), DKGL_PI * 0.5));
132
+
133
+        DKTimer timer;
134
+		timer.Reset();
135
+
136
+		DKLog("Render thread begin");
137
+		while (!runningRenderThread.CompareAndSet(0, 0))
138
+		{
139
+			DKRenderPassDescriptor rpd = swapChain->CurrentRenderPassDescriptor();
140
+			double t = timer.Elapsed();
141
+			double waveT = (cos(t) + 1.0) * 0.5;
142
+			rpd.colorAttachments.Value(0).clearColor = DKColor(waveT, 0.0, 0.0, 0.0);
143
+
144
+            int width = rpd.colorAttachments.Value(0).renderTarget->Width();
145
+            int height = rpd.colorAttachments.Value(0).renderTarget->Height();
146
+            if (depthBuffer)
147
+            {
148
+                if (depthBuffer->Width() !=  width ||
149
+                    depthBuffer->Height() != height )
150
+                    depthBuffer = nullptr;
151
+            }
152
+            if (depthBuffer == nullptr)
153
+            {
154
+                // create depth buffer
155
+                DKTextureDescriptor texDesc = {};
156
+                texDesc.textureType = DKTexture::Type2D;
157
+                texDesc.pixelFormat = DKPixelFormat::D32Float;
158
+                texDesc.width = width;
159
+                texDesc.height = height;
160
+                texDesc.depth = 1;
161
+                texDesc.mipmapLevels = 1;
162
+                texDesc.sampleCount = 1;
163
+                texDesc.arrayLength = 1;
164
+                texDesc.usage = DKTexture::UsageRenderTarget;
165
+                depthBuffer = device->CreateTexture(texDesc);
166
+            }
167
+            rpd.depthStencilAttachment.renderTarget = depthBuffer;
168
+            rpd.depthStencilAttachment.loadAction = DKRenderPassAttachmentDescriptor::LoadActionClear;
169
+            rpd.depthStencilAttachment.storeAction = DKRenderPassAttachmentDescriptor::StoreActionDontCare;
170
+
171
+			DKObject<DKCommandBuffer> buffer = queue->CreateCommandBuffer();
172
+			DKObject<DKRenderCommandEncoder> encoder = buffer->CreateRenderCommandEncoder(rpd);
173
+			if (encoder)
174
+			{
175
+                if (sceneUniformBuffer)
176
+                {
177
+                    camera.SetView(cameraPosition, cameraTartget - cameraPosition, DKVector3(0, 1, 0));
178
+                    camera.SetPerspective(DKGL_DEGREE_TO_RADIAN(90), float(width)/float(height), 1, 1000);
179
+
180
+                    sceneBufferData->projectionMatrix = camera.ProjectionMatrix();
181
+                    sceneBufferData->viewMatrix = camera.ViewMatrix();
182
+
183
+                    DKQuaternion quat(DKVector3(0, 1, 0), t);
184
+                    DKAffineTransform3 trans = tm * DKAffineTransform3(quat);
185
+                    sceneBufferData->modelMatrix = trans.Matrix4();
186
+                    sceneUniformBuffer->Flush();
187
+
188
+                    sampleMesh->SetupExternalUniformBuffer(sceneUniformBuffer, sizeof(SceneUniformBuffer), 0);
189
+                }
190
+
191
+				encoder->SetRenderPipelineState(pipelineState);
192
+
193
+                EncodeScene(encoder);
194
+
195
+                buffer->Commit();
196
+				swapChain->Present();
197
+			}
198
+			else
199
+			{
200
+			}
201
+			DKThread::Sleep(0.01);
202
+		}
203
+		DKLog("RenderThread terminating...");
204
+	}
205
+
206
+	void OnInitialize(void) override
207
+	{
208
+        SampleApp::OnInitialize();
209
+		DKLogD("%s", DKGL_FUNCTION_NAME);
210
+
211
+        // create window
212
+        window = DKWindow::Create("DefaultWindow");
213
+        window->SetOrigin({ 0, 0 });
214
+        window->Resize({ 320, 240 });
215
+        window->Activate();
216
+
217
+        window->AddEventHandler(this, DKFunction([this](const DKWindow::WindowEvent& e)
218
+        {
219
+            if (e.type == DKWindow::WindowEvent::WindowClosed)
220
+                DKApplication::Instance()->Terminate(0);
221
+        }), NULL, NULL);
222
+
223
+        sampleMesh = DKObject<StaticMesh>::New();
224
+        LoadResource();
225
+
226
+		runningRenderThread = 1;
227
+		renderThread = DKThread::Create(DKFunction(this, &DKGLDemo::RenderThread)->Invocation());
228
+	}
229
+	void OnTerminate(void) override
230
+	{
231
+		DKLogD("%s", DKGL_FUNCTION_NAME);
232
+
233
+		runningRenderThread = 0;
234
+		renderThread->WaitTerminate();
235
+		renderThread = NULL;
236
+        window = NULL;
237
+
238
+        SampleApp::OnTerminate();
239
+	}
240
+};
241
+
242
+
243
+#ifdef _WIN32
244
+int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
245
+					  _In_opt_ HINSTANCE hPrevInstance,
246
+					  _In_ LPWSTR    lpCmdLine,
247
+					  _In_ int       nCmdShow)
248
+#else
249
+int main(int argc, const char * argv[])
250
+#endif
251
+{
252
+    DKGLDemo app;
253
+	DKPropertySet::SystemConfig().SetValue("AppDelegate", "AppDelegate");
254
+	DKPropertySet::SystemConfig().SetValue("GraphicsAPI", "Vulkan");
255
+	return app.Run();
256
+}

+ 109
- 0
Samples/PBRScene/ObjImportUtil.cpp Zobrazit soubor

@@ -0,0 +1,109 @@
1
+#include "ObjImportUtil.h"
2
+#include "tiny_obj_loader.h"
3
+
4
+
5
+int ObjImportUtil::ObjVertex::Compare(const ObjVertex& Other) const
6
+{
7
+    const float pp[] = { this->inPos.x, this->inPos.y, this->inPos.z,
8
+        this->inColor.x, this->inColor.y, this->inColor.z,
9
+        this->inTexCoord.x, this->inTexCoord.y,
10
+        this->inNormal.x, this->inNormal.y, this->inNormal.z };
11
+    const float rr[] = { Other.inPos.x, Other.inPos.y, Other.inPos.z,
12
+        Other.inColor.x, Other.inColor.y, Other.inColor.z,
13
+        Other.inTexCoord.x, Other.inTexCoord.y,
14
+        Other.inNormal.x, Other.inNormal.y, Other.inNormal.z };
15
+
16
+    for (int i = 0; i < std::size(pp); ++i)
17
+    {
18
+        auto k = pp[i] - rr[i];
19
+        if (abs(k) < 0.0001)
20
+            continue;
21
+        if (k > 0)
22
+            return 1;
23
+        else if (k < 0)
24
+            return -1;
25
+    }
26
+    return 0;
27
+}
28
+
29
+
30
+ObjImportUtil::ObjImportedMeshData ObjImportUtil::LoadFromObjFile(
31
+    const DKString& inPath
32
+    , DKResourcePool& inDKResourcePool)
33
+{
34
+    ObjImportedMeshData retData;
35
+
36
+    DKObject<DKData> objData = inDKResourcePool.LoadResourceData(inPath);
37
+    if (objData && objData->Length() > 0)
38
+    {
39
+        DKLog("Loading %ls... (%lu bytes)\n"
40
+            , (const wchar_t*)inPath
41
+            , objData->Length());
42
+
43
+        DKTimer timer;
44
+        timer.Reset();
45
+
46
+        retData.vertices.Reserve(100000);
47
+        retData.indices.Reserve(100000);
48
+        retData.vertexSize = sizeof(ObjImportUtil::ObjVertex);
49
+
50
+        tinyobj::attrib_t attrib;
51
+        std::vector<tinyobj::shape_t> shapes;
52
+        shapes.reserve(1000000);
53
+        std::vector<tinyobj::material_t> materials;
54
+
55
+        std::string err;
56
+        if (!tinyobj::LoadObj(&attrib, &shapes, &materials, &err, DKStringU8(inPath))) {
57
+            throw std::runtime_error(err);
58
+        }
59
+
60
+        DKMap<ObjVertex, uint32_t> uniqueVertices;
61
+
62
+        DKLog("Save to Container");
63
+        for (const auto& shape : shapes)
64
+        {
65
+            for (const auto& index : shape.mesh.indices)
66
+            {
67
+                ObjVertex vertex = {};
68
+
69
+                vertex.inPos = {
70
+                    attrib.vertices[3 * index.vertex_index + 0],
71
+                    attrib.vertices[3 * index.vertex_index + 1],
72
+                    attrib.vertices[3 * index.vertex_index + 2]
73
+                };
74
+
75
+                if (attrib.texcoords.size())
76
+                {
77
+                    vertex.inTexCoord = {
78
+                    attrib.texcoords[2 * index.texcoord_index + 0],
79
+                    1.0f - attrib.texcoords[2 * index.texcoord_index + 1]
80
+                    };
81
+                }
82
+
83
+                vertex.inColor = { 1.0f, 1.0f, 1.0f };
84
+
85
+                if (attrib.normals.size())
86
+                {
87
+                    vertex.inNormal = {
88
+                        attrib.normals[3 * index.normal_index + 0],
89
+                        attrib.normals[3 * index.normal_index + 1],
90
+                        attrib.normals[3 * index.normal_index + 2]
91
+                    };
92
+                }
93
+
94
+                if (uniqueVertices.Find(vertex) == nullptr)
95
+                {
96
+                    uniqueVertices.Insert(vertex
97
+                        , static_cast<uint32_t>(retData.vertices.Count()));
98
+                    retData.vertices.Add(vertex);
99
+                }
100
+
101
+                retData.indices.Add(uniqueVertices.Value(vertex));
102
+
103
+                retData.aabb.Expand(vertex.inPos);
104
+            }
105
+        }
106
+    }
107
+
108
+    return retData;
109
+}

+ 43
- 0
Samples/PBRScene/ObjImportUtil.h Zobrazit soubor

@@ -0,0 +1,43 @@
1
+// Simple Obj Loader from https://www.dkscript.com/wiki/SampleCodes/ObjLoader
2
+// but using tinyObjLoader for MTL convenience
3
+
4
+#pragma once
5
+
6
+#include <DK.h>
7
+
8
+class ObjImportUtil
9
+{
10
+public:
11
+    struct ObjVertex
12
+    {
13
+        DKVector3 inPos;
14
+        DKVector3 inColor;
15
+        DKVector3 inNormal;
16
+        DKVector2 inTexCoord;
17
+
18
+        int Compare(const ObjVertex& Other) const;
19
+
20
+        inline bool operator > (const ObjVertex& Other) const
21
+        {
22
+            return Compare(Other) > 0;
23
+        }
24
+
25
+        inline bool operator < (const ObjVertex& Other) const
26
+        {
27
+            return Compare(Other) < 0;
28
+        }
29
+    };
30
+
31
+    struct ObjImportedMeshData
32
+    {
33
+        DKArray<ObjVertex> vertices;
34
+        DKArray<uint32_t> indices;
35
+        DKAabb aabb;
36
+        uint32_t vertexSize;
37
+    };
38
+
39
+    static ObjImportedMeshData LoadFromObjFile(
40
+        const DKString& inPath
41
+        , DKResourcePool& inDKResourcePool);
42
+};
43
+

+ 0
- 468
Samples/PBRScene/PBRScene.cpp Zobrazit soubor

@@ -1,468 +0,0 @@
1
-#include <cstddef>
2
-#include "app.h"
3
-#include "util.h"
4
-
5
-#define TINYOBJLOADER_IMPLMENTATION
6
-#include "tiny_obj_loader.h"
7
-#include <unordered_map>
8
-
9
-
10
-class SampleObjMesh
11
-{
12
-public:
13
-	struct Vertex
14
-	{
15
-		DKVector3 inPos;
16
-		DKVector3 inColor;
17
-		DKVector2 intexCoord;
18
-
19
-		int Compare(const Vertex& Other) const
20
-		{
21
-            const float pp[] = { this->inPos.x, this->inPos.y, this->inPos.z,
22
-                this->inColor.x, this->inColor.y, this->inColor.z,
23
-                this->intexCoord.x, this->intexCoord.y};
24
-            const float rr[] = { Other.inPos.x, Other.inPos.y, Other.inPos.z,
25
-                Other.inColor.x, Other.inColor.y, Other.inColor.z,
26
-                Other.intexCoord.x, Other.intexCoord.y};
27
-
28
-            for (int i = 0; i < std::size(pp); ++i)
29
-            {
30
-                auto k = pp[i] - rr[i];
31
-                if (abs(k) < 0.0001)
32
-                    continue;
33
-                if (k > 0)
34
-                    return 1;
35
-                else if (k < 0)
36
-                    return -1;
37
-            }
38
-            return 0;
39
-		}
40
-
41
-		bool operator > (const Vertex& Other) const
42
-		{
43
-			return Compare(Other) > 0;
44
-		}
45
-
46
-		bool operator < (const Vertex& Other) const
47
-		{
48
-			return Compare(Other) < 0;
49
-		}
50
-	};
51
-
52
-	SampleObjMesh()
53
-	{
54
-		vertices.Reserve(100);
55
-		indices.Reserve(100);
56
-	}
57
-
58
-	void LoadFromObjFile(const char* InPath)
59
-	{
60
-		tinyobj::attrib_t attrib;
61
-		std::vector<tinyobj::shape_t> shapes;
62
-		std::vector<tinyobj::material_t> materials;
63
-		std::string err;
64
-		if (!tinyobj::LoadObj(&attrib, &shapes, &materials, &err, InPath)) {
65
-			throw std::runtime_error(err);
66
-		}
67
-
68
-		DKMap<Vertex, uint32_t> uniqueVertices;
69
-		DKLog("Save to Container");
70
-		for (const auto& shape : shapes)
71
-		{
72
-			for (const auto& index : shape.mesh.indices)
73
-			{
74
-				Vertex vertex = {};
75
-
76
-				vertex.inPos = {
77
-					attrib.vertices[3 * index.vertex_index + 0],
78
-					attrib.vertices[3 * index.vertex_index + 1],
79
-					attrib.vertices[3 * index.vertex_index + 2]
80
-				};
81
-
82
-				if (attrib.texcoords.size())
83
-				{
84
-					vertex.intexCoord = {
85
-					attrib.texcoords[2 * index.texcoord_index + 0],
86
-					1.0f - attrib.texcoords[2 * index.texcoord_index + 1]
87
-					};
88
-				}
89
-
90
-				vertex.inColor = { 1.0f, 1.0f, 1.0f };
91
-
92
-				if (uniqueVertices.Find(vertex) == nullptr)
93
-				{
94
-					uniqueVertices.Insert(vertex, static_cast<uint32_t>(vertices.Count()));
95
-					vertices.Add(vertex);
96
-				}
97
-
98
-				indices.Add(uniqueVertices.Value(vertex));
99
-
100
-                aabb.Expand(vertex.inPos);
101
-			}
102
-		}
103
-	}
104
-
105
-	uint32_t GetVerticesCount() const {
106
-		return static_cast<uint32_t>(vertices.Count()); };
107
-	uint32_t GetIndicesCount() const {
108
-		return static_cast<uint32_t>(indices.Count()); };
109
-	const Vertex* GetVerticesData() const {
110
-		return vertices; }
111
-	const uint32_t* GetIndicesData() const {
112
-		return indices; }
113
-
114
-    DKAabb aabb;
115
-private:
116
-	DKArray<Vertex> vertices;
117
-	DKArray<uint32_t> indices;
118
-	DKSpinLock                  MeshLock;
119
-};
120
-
121
-///// Template Spealization for DKString. (for DKMap, DKSet)
122
-//template <> struct DKMapKeyComparator<SampleObjMesh::Vertex>
123
-//{
124
-//	int operator () (const DKStringW& lhs, const DKStringW& rhs) const
125
-//	{
126
-//		return lhs.Compare(rhs);
127
-//	}
128
-//};
129
-
130
-
131
-class MeshDemo : public SampleApp
132
-{
133
-    DKObject<DKWindow> window;
134
-	DKObject<DKThread> renderThread;
135
-	DKAtomicNumber32 runningRenderThread;
136
-	DKObject<SampleObjMesh> SampleMesh;
137
-
138
-public:
139
-	void LoadMesh()
140
-	{
141
-
142
-		DKLog("Loading Mesh");
143
-        DKString path = resourcePool.ResourceFilePath("meshes/chalet/chalet.obj");
144
-		SampleMesh->LoadFromObjFile(DKStringU8(path));
145
-	}
146
-
147
-    DKObject<DKTexture> LoadTexture2D(DKCommandQueue* queue, DKData* data)
148
-    {
149
-        DKObject<DKImage> image = DKImage::Create(data);
150
-        if (image)
151
-        {
152
-            DKGraphicsDevice* device = queue->Device();
153
-            DKTextureDescriptor texDesc = {};
154
-            texDesc.textureType = DKTexture::Type2D;
155
-            texDesc.pixelFormat = DKPixelFormat::RGBA8Unorm;
156
-            texDesc.width = image->Width();
157
-            texDesc.height = image->Height();
158
-            texDesc.depth = 1;
159
-            texDesc.mipmapLevels = 1;
160
-            texDesc.sampleCount = 1;
161
-            texDesc.arrayLength = 1;
162
-            texDesc.usage = DKTexture::UsageCopyDestination | DKTexture::UsageSampled;
163
-            DKObject<DKTexture> tex = device->CreateTexture(texDesc);
164
-            if (tex)
165
-            {
166
-                size_t bytesPerPixel = image->BytesPerPixel();
167
-                DKASSERT_DESC(bytesPerPixel == DKPixelFormatBytesPerPixel(texDesc.pixelFormat), "BytesPerPixel mismatch!");
168
-
169
-                uint32_t width = image->Width();
170
-                uint32_t height = image->Height();
171
-
172
-                size_t bufferLength = bytesPerPixel * width * height;
173
-                DKObject<DKGpuBuffer> stagingBuffer = device->CreateBuffer(bufferLength, DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
174
-
175
-                memcpy(stagingBuffer->Contents(), image->Contents(), bufferLength);
176
-                stagingBuffer->Flush();
177
-
178
-                DKObject<DKCommandBuffer> cb = queue->CreateCommandBuffer();
179
-                DKObject<DKCopyCommandEncoder> encoder = cb->CreateCopyCommandEncoder();
180
-                encoder->CopyFromBufferToTexture(stagingBuffer,
181
-                                                 { 0, width, height },
182
-                                                 tex,
183
-                                                 { 0,0, 0,0,0 },
184
-                                                 { width,height,1 });
185
-                encoder->EndEncoding();
186
-                cb->Commit();
187
-
188
-                DKLog("Texture created!");
189
-                return tex;
190
-            }
191
-        }
192
-        return nullptr;
193
-    }
194
-	void RenderThread(void)
195
-	{
196
-		DKObject<DKData> vertData = resourcePool.LoadResourceData("shaders/mesh.vert.spv");
197
-		DKObject<DKData> fragData = resourcePool.LoadResourceData("shaders/mesh.frag.spv");
198
-		DKShader vertShader(vertData);
199
-		DKShader fragShader(fragData);
200
-
201
-		DKObject<DKGraphicsDevice> device = DKGraphicsDevice::SharedInstance();
202
-        DKObject<DKCommandQueue> queue = device->CreateCommandQueue(DKCommandQueue::Graphics);
203
-
204
-		// create texture
205
-		DKObject<DKTexture> texture = LoadTexture2D(queue, resourcePool.LoadResourceData("meshes/chalet.png"));
206
-		// create sampler
207
-		DKSamplerDescriptor samplerDesc = {};
208
-		samplerDesc.magFilter = DKSamplerDescriptor::MinMagFilterLinear;
209
-		samplerDesc.minFilter = DKSamplerDescriptor::MinMagFilterLinear;
210
-		samplerDesc.addressModeU = DKSamplerDescriptor::AddressModeClampToEdge;
211
-		samplerDesc.addressModeV = DKSamplerDescriptor::AddressModeClampToEdge;
212
-		samplerDesc.addressModeW = DKSamplerDescriptor::AddressModeClampToEdge;
213
-		samplerDesc.maxAnisotropy = 16;
214
-
215
-		DKObject<DKSamplerState> sampler = device->CreateSamplerState(samplerDesc);
216
-
217
-        // create shaders
218
-		DKObject<DKShaderModule> vertShaderModule = device->CreateShaderModule(&vertShader);
219
-		DKObject<DKShaderModule> fragShaderModule = device->CreateShaderModule(&fragShader);
220
-
221
-		DKObject<DKShaderFunction> vertShaderFunction = vertShaderModule->CreateFunction(vertShaderModule->FunctionNames().Value(0));
222
-		DKObject<DKShaderFunction> fragShaderFunction = fragShaderModule->CreateFunction(fragShaderModule->FunctionNames().Value(0));
223
-
224
-		DKObject<DKSwapChain> swapChain = queue->CreateSwapChain(window);
225
-
226
-		DKLog("VertexFunction.VertexAttributes: %d", vertShaderFunction->StageInputAttributes().Count());
227
-		for (int i = 0; i < vertShaderFunction->StageInputAttributes().Count(); ++i)
228
-		{
229
-			const DKShaderAttribute& attr = vertShaderFunction->StageInputAttributes().Value(i);
230
-			DKLog("  --> VertexAttribute[%d]: \"%ls\" (location:%u)", i, (const wchar_t*)attr.name, attr.location);
231
-		}
232
-
233
-
234
-		uint32_t vertexBufferSize = static_cast<uint32_t>(SampleMesh->GetVerticesCount()) * sizeof(SampleObjMesh::Vertex);
235
-		uint32_t indexBufferSize = SampleMesh->GetIndicesCount() * sizeof(uint32_t);
236
-
237
-		DKObject<DKGpuBuffer> vertexBuffer = device->CreateBuffer(vertexBufferSize, DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
238
-		memcpy(vertexBuffer->Contents(), SampleMesh->GetVerticesData(), vertexBufferSize);
239
-        vertexBuffer->Flush();
240
-
241
-		DKObject<DKGpuBuffer> indexBuffer = device->CreateBuffer(indexBufferSize, DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
242
-		memcpy(indexBuffer->Contents(), SampleMesh->GetIndicesData(), indexBufferSize);
243
-        indexBuffer->Flush();
244
-
245
-		DKRenderPipelineDescriptor pipelineDescriptor;
246
-        // setup shader
247
-		pipelineDescriptor.vertexFunction = vertShaderFunction;
248
-		pipelineDescriptor.fragmentFunction = fragShaderFunction;
249
-        // setup color-attachment render-targets
250
-		pipelineDescriptor.colorAttachments.Resize(1);
251
-		pipelineDescriptor.colorAttachments.Value(0).pixelFormat = swapChain->ColorPixelFormat();
252
-        pipelineDescriptor.colorAttachments.Value(0).blendState.enabled = false;
253
-        pipelineDescriptor.colorAttachments.Value(0).blendState.sourceRGBBlendFactor = DKBlendFactor::SourceAlpha;
254
-        pipelineDescriptor.colorAttachments.Value(0).blendState.destinationRGBBlendFactor = DKBlendFactor::OneMinusSourceAlpha;
255
-        // setup depth-stencil
256
-		pipelineDescriptor.depthStencilAttachmentPixelFormat = DKPixelFormat::D32Float;
257
-        pipelineDescriptor.depthStencilDescriptor.depthWriteEnabled = true;
258
-        pipelineDescriptor.depthStencilDescriptor.depthCompareFunction = DKCompareFunctionLessEqual;
259
-        // setup vertex buffer and attributes
260
-        pipelineDescriptor.vertexDescriptor.attributes = {
261
-			{ DKVertexFormat::Float3, offsetof(SampleObjMesh::Vertex, inPos), 0, 0 },
262
-            { DKVertexFormat::Float3, offsetof(SampleObjMesh::Vertex, inColor), 0, 1 },
263
-			{ DKVertexFormat::Float2, offsetof(SampleObjMesh::Vertex, intexCoord), 0, 2 },
264
-		};
265
-		pipelineDescriptor.vertexDescriptor.layouts = {
266
-			{ DKVertexStepRate::Vertex, sizeof(SampleObjMesh::Vertex), 0 },
267
-		};
268
-        // setup topology and rasterization
269
-		pipelineDescriptor.primitiveTopology = DKPrimitiveType::Triangle;
270
-		pipelineDescriptor.frontFace = DKFrontFace::CCW;
271
-		pipelineDescriptor.triangleFillMode = DKTriangleFillMode::Fill;
272
-		pipelineDescriptor.depthClipMode = DKDepthClipMode::Clip;
273
-		pipelineDescriptor.cullMode = DKCullMode::Back;
274
-		pipelineDescriptor.rasterizationEnabled = true;
275
-
276
-		DKPipelineReflection reflection;
277
-		DKObject<DKRenderPipelineState> pipelineState = device->CreateRenderPipeline(pipelineDescriptor, &reflection);
278
-		if (pipelineState)
279
-		{
280
-            PrintPipelineReflection(&reflection, DKLogCategory::Verbose);
281
-		}
282
-
283
-        DKShaderBindingSetLayout layout;
284
-        if (1)
285
-        {
286
-            DKShaderBinding bindings[2] = {
287
-                {
288
-                    0,
289
-                    DKShader::DescriptorTypeUniformBuffer,
290
-                    1,
291
-                    nullptr
292
-                },
293
-                {
294
-                    1,
295
-                    DKShader::DescriptorTypeTextureSampler,
296
-                    1,
297
-                    nullptr
298
-                },
299
-            };
300
-            layout.bindings.Add(bindings, 2);
301
-        }
302
-        DKObject<DKShaderBindingSet> bindSet = device->CreateShaderBindingSet(layout);
303
-
304
-        struct UBO
305
-        {
306
-            DKMatrix4 projectionMatrix;
307
-            DKMatrix4 modelMatrix;
308
-            DKMatrix4 viewMatrix;
309
-        };
310
-        DKObject<DKGpuBuffer> uboBuffer = device->CreateBuffer(sizeof(UBO), DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
311
-        UBO* ubo = nullptr;
312
-        if (bindSet)
313
-        {
314
-            if (uboBuffer)
315
-            {
316
-                ubo = reinterpret_cast<UBO*>(uboBuffer->Contents());
317
-                ubo->projectionMatrix = DKMatrix4::identity;
318
-                ubo->modelMatrix = DKMatrix4::identity;
319
-                ubo->viewMatrix = DKMatrix4::identity;
320
-                uboBuffer->Flush();
321
-
322
-                //DKAffineTransform3 trans;
323
-                //trans.Multiply(DKLinearTransform3().Scale(0.5).Rotate(DKVector3(0,1,0), DKGL_PI * 0.5));
324
-                //ubo.modelMatrix.Multiply(trans.Matrix4());
325
-
326
-                //memcpy(uboBuffer->Contents(), &ubo, sizeof(ubo));
327
-                bindSet->SetBuffer(0, uboBuffer, 0, sizeof(UBO));
328
-            }
329
-
330
-            bindSet->SetTexture(1, texture);
331
-            bindSet->SetSamplerState(1, sampler);
332
-        }
333
-
334
-        DKObject<DKTexture> depthBuffer = nullptr;
335
-
336
-        DKCamera camera;
337
-        DKVector3 cameraPosition = { 0, 5, 10 };
338
-        DKVector3 cameraTartget = { 0, 0, 0 };
339
-
340
-        DKAffineTransform3 tm(DKLinearTransform3().Scale(5).Rotate(DKVector3(-1,0,0), DKGL_PI * 0.5));
341
-
342
-        DKTimer timer;
343
-		timer.Reset();
344
-
345
-		DKLog("Render thread begin");
346
-		while (!runningRenderThread.CompareAndSet(0, 0))
347
-		{
348
-			DKRenderPassDescriptor rpd = swapChain->CurrentRenderPassDescriptor();
349
-			double t = timer.Elapsed();
350
-			double waveT = (cos(t) + 1.0) * 0.5;
351
-			rpd.colorAttachments.Value(0).clearColor = DKColor(waveT, 0.0, 0.0, 0.0);
352
-
353
-            int width = rpd.colorAttachments.Value(0).renderTarget->Width();
354
-            int height = rpd.colorAttachments.Value(0).renderTarget->Height();
355
-            if (depthBuffer)
356
-            {
357
-                if (depthBuffer->Width() !=  width ||
358
-                    depthBuffer->Height() != height )
359
-                    depthBuffer = nullptr;
360
-            }
361
-            if (depthBuffer == nullptr)
362
-            {
363
-                // create depth buffer
364
-                DKTextureDescriptor texDesc = {};
365
-                texDesc.textureType = DKTexture::Type2D;
366
-                texDesc.pixelFormat = DKPixelFormat::D32Float;
367
-                texDesc.width = width;
368
-                texDesc.height = height;
369
-                texDesc.depth = 1;
370
-                texDesc.mipmapLevels = 1;
371
-                texDesc.sampleCount = 1;
372
-                texDesc.arrayLength = 1;
373
-                texDesc.usage = DKTexture::UsageRenderTarget;
374
-                depthBuffer = device->CreateTexture(texDesc);
375
-            }
376
-            rpd.depthStencilAttachment.renderTarget = depthBuffer;
377
-            rpd.depthStencilAttachment.loadAction = DKRenderPassAttachmentDescriptor::LoadActionClear;
378
-            rpd.depthStencilAttachment.storeAction = DKRenderPassAttachmentDescriptor::StoreActionDontCare;
379
-
380
-			DKObject<DKCommandBuffer> buffer = queue->CreateCommandBuffer();
381
-			DKObject<DKRenderCommandEncoder> encoder = buffer->CreateRenderCommandEncoder(rpd);
382
-			if (encoder)
383
-			{
384
-                if (bindSet && ubo)
385
-                {
386
-                    camera.SetView(cameraPosition, cameraTartget - cameraPosition, DKVector3(0, 1, 0));
387
-                    camera.SetPerspective(DKGL_DEGREE_TO_RADIAN(90), float(width)/float(height), 1, 1000);
388
-
389
-                    ubo->projectionMatrix = camera.ProjectionMatrix();
390
-                    ubo->viewMatrix = camera.ViewMatrix();
391
-
392
-                    DKQuaternion quat(DKVector3(0, 1, 0), t);
393
-                    DKAffineTransform3 trans = tm * DKAffineTransform3(quat);
394
-                    ubo->modelMatrix = trans.Matrix4();
395
-                    uboBuffer->Flush();
396
-                    bindSet->SetBuffer(0, uboBuffer, 0, sizeof(UBO));
397
-                }
398
-
399
-				encoder->SetRenderPipelineState(pipelineState);
400
-				encoder->SetVertexBuffer(vertexBuffer, 0, 0);
401
-				encoder->SetIndexBuffer(indexBuffer, 0, DKIndexType::UInt32);
402
-                encoder->SetResources(0, bindSet);
403
-				// draw scene!
404
-				encoder->DrawIndexed(SampleMesh->GetIndicesCount(), 1, 0, 0, 0);
405
-				encoder->EndEncoding();
406
-				buffer->Commit();
407
-				swapChain->Present();
408
-			}
409
-			else
410
-			{
411
-			}
412
-			DKThread::Sleep(0.01);
413
-		}
414
-		DKLog("RenderThread terminating...");
415
-	}
416
-
417
-	void OnInitialize(void) override
418
-	{
419
-        SampleApp::OnInitialize();
420
-		DKLogD("%s", DKGL_FUNCTION_NAME);
421
-
422
-        // create window
423
-        window = DKWindow::Create("DefaultWindow");
424
-        window->SetOrigin({ 0, 0 });
425
-        window->Resize({ 320, 240 });
426
-        window->Activate();
427
-
428
-        window->AddEventHandler(this, DKFunction([this](const DKWindow::WindowEvent& e)
429
-        {
430
-            if (e.type == DKWindow::WindowEvent::WindowClosed)
431
-                DKApplication::Instance()->Terminate(0);
432
-        }), NULL, NULL);
433
-
434
-        SampleMesh = DKOBJECT_NEW SampleObjMesh();
435
-
436
-		LoadMesh();
437
-
438
-		runningRenderThread = 1;
439
-		renderThread = DKThread::Create(DKFunction(this, &MeshDemo::RenderThread)->Invocation());
440
-	}
441
-	void OnTerminate(void) override
442
-	{
443
-		DKLogD("%s", DKGL_FUNCTION_NAME);
444
-
445
-		runningRenderThread = 0;
446
-		renderThread->WaitTerminate();
447
-		renderThread = NULL;
448
-        window = NULL;
449
-
450
-        SampleApp::OnTerminate();
451
-	}
452
-};
453
-
454
-
455
-#ifdef _WIN32
456
-int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
457
-					  _In_opt_ HINSTANCE hPrevInstance,
458
-					  _In_ LPWSTR    lpCmdLine,
459
-					  _In_ int       nCmdShow)
460
-#else
461
-int main(int argc, const char * argv[])
462
-#endif
463
-{
464
-    MeshDemo app;
465
-	DKPropertySet::SystemConfig().SetValue("AppDelegate", "AppDelegate");
466
-	DKPropertySet::SystemConfig().SetValue("GraphicsAPI", "Vulkan");
467
-	return app.Run();
468
-}

+ 4
- 0
Samples/PBRScene/PBRScene.vcxproj Zobrazit soubor

@@ -25,6 +25,8 @@
25 25
     <ClInclude Include="..\Common\Win32\stdafx.h" />
26 26
     <ClInclude Include="..\Common\Win32\targetver.h" />
27 27
     <ClInclude Include="..\Libs\tinyobjLoader\tiny_obj_loader.h" />
28
+    <ClInclude Include="ObjImportUtil.h" />
29
+    <ClInclude Include="StaticMesh.h" />
28 30
   </ItemGroup>
29 31
   <ItemGroup>
30 32
     <Image Include="..\Common\Win32\SampleApp.ico" />
@@ -36,7 +38,9 @@
36 38
   <ItemGroup>
37 39
     <ClCompile Include="..\Common\dkgl_new.cpp" />
38 40
     <ClCompile Include="..\Libs\tinyobjLoader\tiny_obj_loader.cc" />
41
+    <ClCompile Include="ObjImportUtil.cpp" />
39 42
     <ClCompile Include="PBRScene.cpp" />
43
+    <ClCompile Include="StaticMesh.cpp" />
40 44
   </ItemGroup>
41 45
   <ItemGroup>
42 46
     <ProjectReference Include="..\..\DK\DK_static.vcxproj">

+ 4
- 0
Samples/PBRScene/PBRScene.vcxproj.filters Zobrazit soubor

@@ -33,6 +33,8 @@
33 33
     <ClInclude Include="..\Libs\tinyobjLoader\tiny_obj_loader.h">
34 34
       <Filter>Libs</Filter>
35 35
     </ClInclude>
36
+    <ClInclude Include="ObjImportUtil.h" />
37
+    <ClInclude Include="StaticMesh.h" />
36 38
   </ItemGroup>
37 39
   <ItemGroup>
38 40
     <Image Include="..\Common\Win32\SampleApp.ico">
@@ -57,5 +59,7 @@
57 59
     <ClCompile Include="PBRScene.cpp">
58 60
       <Filter>Source Files</Filter>
59 61
     </ClCompile>
62
+    <ClCompile Include="ObjImportUtil.cpp" />
63
+    <ClCompile Include="StaticMesh.cpp" />
60 64
   </ItemGroup>
61 65
 </Project>

+ 262
- 0
Samples/PBRScene/StaticMesh.cpp Zobrazit soubor

@@ -0,0 +1,262 @@
1
+#include "StaticMesh.h"
2
+#include "ObjImportUtil.h"
3
+
4
+StaticMesh::StaticMesh()
5
+    : mesh(nullptr)
6
+{
7
+    memset(shaderData, 0
8
+        , sizeof(DKObject<DKData>) * static_cast<int>(DKShaderStage::Compute));
9
+}
10
+
11
+bool StaticMesh::LoadMeshResourceFromFile(DKObject<DKGraphicsDevice> inDevice
12
+    , DKResourcePool& inDKResourcePool, const DKString& inFileName)
13
+{
14
+    if (inDevice == nullptr)
15
+        return false;
16
+
17
+    if (inFileName.Length() == 0)
18
+        return false;
19
+
20
+    if (inFileName.HasSuffix("obj"))
21
+    {
22
+        ObjImportUtil::ObjImportedMeshData loadedData
23
+            = ObjImportUtil::LoadFromObjFile(inFileName, inDKResourcePool);
24
+
25
+        mesh = DKObject<DKMesh>::New();
26
+
27
+        uint32_t vertexBufferSize
28
+            = static_cast<uint32_t>(loadedData.vertices.Count()) * loadedData.vertexSize;
29
+
30
+        DKVertexBuffer vb = {};
31
+        {
32
+            DKObject<DKGpuBuffer> vertexBuffer
33
+                = inDevice->CreateBuffer(vertexBufferSize, DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
34
+            memcpy(vertexBuffer->Contents(), loadedData.vertices, vertexBufferSize);
35
+            vertexBuffer->Flush();
36
+
37
+            vb.buffer = vertexBuffer;
38
+            vb.count = loadedData.vertices.Count();
39
+            vb.offset = 0;
40
+            vb.size = loadedData.vertexSize;
41
+            vb.declarations =
42
+            {
43
+                {DKVertexStream::Position, DKVertexFormat::Float3, false, offsetof(ObjImportUtil::ObjVertex, inPos), DKString("Position")},
44
+                {DKVertexStream::Color, DKVertexFormat::Float3, false, offsetof(ObjImportUtil::ObjVertex, inColor), DKString("Color")},
45
+                {DKVertexStream::Normal, DKVertexFormat::Float3, false, offsetof(ObjImportUtil::ObjVertex, inNormal), DKString("Normal")},
46
+                {DKVertexStream::TexCoord, DKVertexFormat::Float2, false, offsetof(ObjImportUtil::ObjVertex, inTexCoord), DKString("TexCoord")},
47
+            };
48
+
49
+            mesh->vertexBuffers.Add(vb);
50
+        }
51
+
52
+        DKSubMesh subMesh = {};
53
+        {
54
+            uint32_t indexBufferSize
55
+                = loadedData.indices.Count() * sizeof(uint32_t);
56
+
57
+            DKObject<DKGpuBuffer> indexBuffer =
58
+                inDevice->CreateBuffer(indexBufferSize
59
+                    , DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
60
+
61
+            memcpy(indexBuffer->Contents(), loadedData.indices, indexBufferSize);
62
+            indexBuffer->Flush();
63
+
64
+            subMesh.indexBuffer = indexBuffer;
65
+            subMesh.indexCount = loadedData.indices.Count();
66
+            subMesh.indexOffset = 0;
67
+            subMesh.indexType = DKIndexType::UInt32;
68
+            subMesh.vertexOffset = 0;
69
+            subMesh.visible = true;
70
+        }
71
+
72
+        mesh->subMeshes.Add(subMesh);
73
+
74
+        aabb = loadedData.aabb;
75
+
76
+        return true;
77
+    }
78
+
79
+    return false;
80
+}
81
+
82
+bool StaticMesh::LoadTextureFromFile(DKResourcePool& inDKResourcePool
83
+    , const DKString& inFileName)
84
+{
85
+   textureSrc = DKImage::Create(inDKResourcePool.LoadResourceData(inFileName));
86
+   if (textureSrc)
87
+       return true;
88
+
89
+   return false;
90
+}
91
+
92
+bool StaticMesh::LoadRenderResourceTexture(DKObject<DKCommandQueue> queue)
93
+{
94
+    if (textureSrc && texture == nullptr)
95
+    {
96
+        DKGraphicsDevice* device = queue->Device();
97
+        DKTextureDescriptor texDesc = {};
98
+        texDesc.textureType = DKTexture::Type2D;
99
+        texDesc.pixelFormat = DKPixelFormat::RGBA8Unorm;
100
+        texDesc.width = textureSrc->Width();
101
+        texDesc.height = textureSrc->Height();
102
+        texDesc.depth = 1;
103
+        texDesc.mipmapLevels = 1;
104
+        texDesc.sampleCount = 1;
105
+        texDesc.arrayLength = 1;
106
+        texDesc.usage = DKTexture::UsageCopyDestination | DKTexture::UsageSampled;
107
+        DKObject<DKTexture> tex = device->CreateTexture(texDesc);
108
+        if (tex)
109
+        {
110
+            size_t bytesPerPixel = textureSrc->BytesPerPixel();
111
+            DKASSERT_DESC(bytesPerPixel
112
+                == DKPixelFormatBytesPerPixel(texDesc.pixelFormat)
113
+                , "BytesPerPixel mismatch!");
114
+
115
+            uint32_t width = textureSrc->Width();
116
+            uint32_t height = textureSrc->Height();
117
+
118
+            size_t bufferLength = bytesPerPixel * texDesc.width * texDesc.height;
119
+            DKObject<DKGpuBuffer> stagingBuffer = device->CreateBuffer(bufferLength
120
+                , DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
121
+
122
+            memcpy(stagingBuffer->Contents(), textureSrc->Contents(), bufferLength);
123
+            stagingBuffer->Flush();
124
+
125
+            DKObject<DKCommandBuffer> cb = queue->CreateCommandBuffer();
126
+            DKObject<DKCopyCommandEncoder> encoder = cb->CreateCopyCommandEncoder();
127
+            encoder->CopyFromBufferToTexture(stagingBuffer,
128
+                { 0, width, height },
129
+                tex,
130
+                { 0,0, 0,0,0 },
131
+                { width,height,1 });
132
+            encoder->EndEncoding();
133
+            cb->Commit();
134
+
135
+            DKLog("Texture created!");
136
+            texture = tex;
137
+
138
+            // create sampler
139
+            DKSamplerDescriptor samplerDesc = {};
140
+            samplerDesc.magFilter = DKSamplerDescriptor::MinMagFilterLinear;
141
+            samplerDesc.minFilter = DKSamplerDescriptor::MinMagFilterLinear;
142
+            samplerDesc.addressModeU = DKSamplerDescriptor::AddressModeClampToEdge;
143
+            samplerDesc.addressModeV = DKSamplerDescriptor::AddressModeClampToEdge;
144
+            samplerDesc.addressModeW = DKSamplerDescriptor::AddressModeClampToEdge;
145
+            samplerDesc.maxAnisotropy = 16;
146
+
147
+            textureSampler = device->CreateSamplerState(samplerDesc);
148
+
149
+            return true;
150
+        }
151
+    }
152
+    return false;
153
+}
154
+
155
+bool StaticMesh::LoadShaderFromFile(DKResourcePool& inDKResourcePool
156
+    , const DKString& inFileName
157
+    , DKShaderStage inStage)
158
+{
159
+    DKObject<DKData> data = inDKResourcePool.LoadResourceData(inFileName);
160
+    shaderData[static_cast<int>(inStage)] = data;
161
+    if (data)
162
+        return true;
163
+    return false;
164
+}
165
+
166
+bool StaticMesh::LoadRenderResourceShader(DKObject<DKGraphicsDevice> inDevice
167
+    , DKShaderStage inStage)
168
+{
169
+    DKShader shader(shaderData[static_cast<int>(inStage)]);
170
+    DKObject<DKShaderModule> module = inDevice->CreateShaderModule(&shader);
171
+    DKObject<DKShaderFunction> function
172
+        = module->CreateFunction(module->FunctionNames().Value(0));
173
+    shaderModule[static_cast<int>(inStage)] = module;
174
+    shaderFunction[static_cast<int>(inStage)] = function;
175
+
176
+    if (module && function)
177
+    {
178
+        if (inStage == DKShaderStage::Vertex)
179
+        {
180
+            DKLog("VertexFunction.VertexAttributes: %d", function->StageInputAttributes().Count());
181
+            for (int i = 0; i < function->StageInputAttributes().Count(); ++i)
182
+            {
183
+                const DKShaderAttribute& attr = function->StageInputAttributes().Value(i);
184
+                DKLog("  --> VertexAttribute[%d]: \"%ls\" (location:%u)", i, (const wchar_t*)attr.name, attr.location);
185
+            }
186
+        }
187
+        return true;
188
+    }
189
+
190
+    return false;
191
+}
192
+
193
+void StaticMesh::SetupPipelineDecriptor(DKRenderPipelineDescriptor& pipelineDescriptor)
194
+{
195
+    // setup shader
196
+    pipelineDescriptor.vertexFunction = shaderFunction[static_cast<int>(DKShaderStage::Vertex)];
197
+    pipelineDescriptor.fragmentFunction = shaderFunction[static_cast<int>(DKShaderStage::Fragment)];
198
+
199
+    uint32_t i = 0;
200
+    for (auto decl : mesh->vertexBuffers[0].declarations)
201
+    {
202
+        pipelineDescriptor.vertexDescriptor.attributes.Add(
203
+            DKVertexAttributeDescriptor{ decl.format, decl.offset, 0, i }
204
+        );
205
+        i++;
206
+    }
207
+
208
+    pipelineDescriptor.vertexDescriptor.layouts = {
209
+        { DKVertexStepRate::Vertex, mesh->vertexBuffers[0].size, 0 },
210
+    };
211
+}
212
+
213
+void StaticMesh::SetupMaterial(DKObject<DKGraphicsDevice> inDevice)
214
+{
215
+    DKShaderBindingSetLayout layout;
216
+    if (1)
217
+    {
218
+        DKShaderBinding bindings[2] = {
219
+            {
220
+                0,
221
+                DKShader::DescriptorTypeUniformBuffer,
222
+                1,
223
+                nullptr
224
+            }, // Scene Uniform Buffer
225
+            {
226
+                1,
227
+                DKShader::DescriptorTypeTextureSampler,
228
+                1,
229
+                nullptr
230
+            }, // Texture
231
+        };
232
+        layout.bindings.Add(bindings, 2);
233
+    }
234
+
235
+    bindSet = inDevice->CreateShaderBindingSet(layout);
236
+
237
+    if (bindSet == nullptr)
238
+        return;
239
+
240
+    bindSet->SetTexture(1, texture);
241
+    bindSet->SetSamplerState(1, textureSampler);
242
+}
243
+
244
+void StaticMesh::SetupExternalUniformBuffer(DKObject<DKGpuBuffer> uniformBuffer, size_t uniformBufferSize, int index)
245
+{
246
+    if (uniformBuffer == nullptr || bindSet == nullptr)
247
+        return;
248
+
249
+    bindSet->SetBuffer(index, uniformBuffer, 0, uniformBufferSize);
250
+}
251
+
252
+bool StaticMesh::EncodeRenderCommand(DKRenderCommandEncoder* encoder) const
253
+{
254
+    encoder->SetVertexBuffer(mesh->vertexBuffers[0].buffer, 0, 0);
255
+    encoder->SetIndexBuffer(mesh->subMeshes[0].indexBuffer, 0, mesh->subMeshes[0].indexType);
256
+    encoder->SetResources(0, bindSet);
257
+    // draw scene!
258
+    encoder->DrawIndexed(mesh->subMeshes[0].indexCount, 1, 0, 0, 0);
259
+    encoder->EndEncoding();
260
+    return true;
261
+}
262
+

+ 52
- 0
Samples/PBRScene/StaticMesh.h Zobrazit soubor

@@ -0,0 +1,52 @@
1
+#pragma once
2
+
3
+#include <DK.h>
4
+
5
+// simple wrapper of dk mesh
6
+
7
+class StaticMesh
8
+{
9
+public:
10
+    StaticMesh();
11
+
12
+    bool LoadMeshResourceFromFile(DKObject<DKGraphicsDevice> inDevice
13
+        , DKResourcePool& inDKResourcePool, const DKString& inFileName);
14
+
15
+    bool LoadShaderFromFile(DKResourcePool& inDKResourcePool
16
+        , const DKString& inFileName
17
+        , DKShaderStage inStage);
18
+
19
+    // Should be seperated
20
+    bool LoadTextureFromFile(DKResourcePool& inDKResourcePool
21
+        , const DKString& inFileName);
22
+
23
+    bool LoadRenderResourceTexture(DKObject<DKCommandQueue> queue);
24
+    bool LoadRenderResourceShader(DKObject<DKGraphicsDevice> inDevice,
25
+        DKShaderStage inStage);
26
+
27
+    DKObject<DKMesh> Mesh() { return mesh; }
28
+
29
+    void SetupPipelineDecriptor(DKRenderPipelineDescriptor& pipelineDescriptor);
30
+    void SetupMaterial(DKObject<DKGraphicsDevice> inDevice);
31
+    void SetupExternalUniformBuffer(DKObject<DKGpuBuffer> uniformBuffer
32
+        , size_t uniformBufferSize, int index);
33
+
34
+    bool EncodeRenderCommand(DKRenderCommandEncoder* encoder) const;
35
+
36
+private:
37
+    DKString fileName;
38
+    DKObject<DKMesh> mesh;
39
+
40
+    // Temporary variables before material work
41
+    DKObject<DKImage> textureSrc;
42
+
43
+    DKObject<DKTexture> texture;
44
+    DKObject<DKSamplerState> textureSampler;
45
+
46
+    DKObject<DKShaderBindingSet> bindSet;
47
+    DKObject<DKData> shaderData[static_cast<int>(DKShaderStage::Compute)];
48
+    DKObject<DKShaderModule> shaderModule[static_cast<int>(DKShaderStage::Compute)];
49
+    DKObject<DKShaderFunction> shaderFunction[static_cast<int>(DKShaderStage::Compute)];
50
+
51
+    DKAabb aabb;
52
+};