forked from vixorien/D3D11Starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mesh.cpp
452 lines (393 loc) · 14.5 KB
/
Mesh.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
#include "Mesh.h"
Mesh::Mesh(
Vertex* vertices,
int numVertices,
unsigned int* indices,
int numIndices,
Microsoft::WRL::ComPtr<ID3D11Device> device,
Microsoft::WRL::ComPtr<ID3D11DeviceContext> context
)
{
CreateBuffers(vertices, numVertices, indices, numIndices, device, context);
}
Mesh::Mesh(
const std::wstring& objFile,
Microsoft::WRL::ComPtr<ID3D11Device> device,
Microsoft::WRL::ComPtr<ID3D11DeviceContext> context
)
{
// Author: Chris Cascioli
// Purpose: Basic .OBJ 3D model loading, supporting positions, uvs and normals
//
// - You are allowed to directly copy/paste this into your code base
// for assignments, given that you clearly cite that this is not
// code of your own design.
//
// - NOTE: You'll need to #include <fstream>
// File input object
std::ifstream obj(objFile);
// Check for successful open
if (!obj.is_open())
return;
// Variables used while reading the file
std::vector<DirectX::XMFLOAT3> positions; // Positions from the file
std::vector<DirectX::XMFLOAT3> normals; // Normals from the file
std::vector<DirectX::XMFLOAT2> uvs; // UVs from the file
std::vector<Vertex> verts; // Verts we're assembling
std::vector<UINT> indices; // Indices of these verts
int vertCounter = 0; // Count of vertices
int indexCounter = 0; // Count of indices
char chars[100]; // String for line reading
// Still have data left?
while (obj.good())
{
// Get the line (100 characters should be more than enough)
obj.getline(chars, 100);
// Check the type of line
if (chars[0] == 'v' && chars[1] == 'n') // Normals start with 'vn'
{
// Read the 3 numbers directly into an XMFLOAT3
DirectX::XMFLOAT3 norm;
// Scans for data of this shape and if it is found, passes the found %f (floats) into the corresponding x, y and z variables
sscanf_s(
chars,
"vn %f %f %f",
&norm.x, &norm.y, &norm.z);
// Add to the list of normals
normals.push_back(norm);
}
else if (chars[0] == 'v' && chars[1] == 't') // UVs start with 'vt'
{
// Read the 2 numbers directly into an XMFLOAT2
DirectX::XMFLOAT2 uv;
sscanf_s(
chars,
"vt %f %f",
&uv.x, &uv.y);
// Add to the list of uv's
uvs.push_back(uv);
}
else if (chars[0] == 'v') // Vertices start with 'v'
{
// Read the 3 numbers directly into an XMFLOAT3
DirectX::XMFLOAT3 pos;
sscanf_s(
chars,
"v %f %f %f",
&pos.x, &pos.y, &pos.z);
// Add to the positions
positions.push_back(pos);
}
else if (chars[0] == 'f')
{
// Read the face indices into an array
// NOTE: This assumes the given obj file contains
// vertex positions, uv coordinates AND normals.
unsigned int i[12];
int numbersRead = sscanf_s(
chars,
"f %d/%d/%d %d/%d/%d %d/%d/%d %d/%d/%d",
&i[0], &i[1], &i[2],
&i[3], &i[4], &i[5],
&i[6], &i[7], &i[8],
&i[9], &i[10], &i[11]);
// If we only got the first number, chances are the OBJ
// file has no UV coordinates. This isn't great, but we
// still want to load the model without crashing, so we
// need to re-read a different pattern (in which we assume
// there are no UVs denoted for any of the vertices)
if (numbersRead == 1)
{
// Re-read with a different pattern
numbersRead = sscanf_s(
chars,
"f %d//%d %d//%d %d//%d %d//%d",
&i[0], &i[2],
&i[3], &i[5],
&i[6], &i[8],
&i[9], &i[11]);
// The following indices are where the UVs should
// have been, so give them a valid value
i[1] = 1;
i[4] = 1;
i[7] = 1;
i[10] = 1;
// If we have no UVs, create a single UV coordinate
// that will be used for all vertices
if (uvs.size() == 0)
uvs.push_back(DirectX::XMFLOAT2(0, 0));
}
// - Create the verts by looking up
// corresponding data from vectors
// - OBJ File indices are 1-based, so
// they need to be adusted
Vertex v1;
v1.Position = positions[i[0] - 1];
v1.UV = uvs[i[1] - 1];
v1.Normal = normals[i[2] - 1];
Vertex v2;
v2.Position = positions[i[3] - 1];
v2.UV = uvs[i[4] - 1];
v2.Normal = normals[i[5] - 1];
Vertex v3;
v3.Position = positions[i[6] - 1];
v3.UV = uvs[i[7] - 1];
v3.Normal = normals[i[8] - 1];
// The model is most likely in a right-handed space,
// especially if it came from Maya. We want to convert
// to a left-handed space for DirectX. This means we
// need to:
// - Invert the Z position
// - Invert the normal's Z
// - Flip the winding order
// We also need to flip the UV coordinate since DirectX
// defines (0,0) as the top left of the texture, and many
// 3D modeling packages use the bottom left as (0,0)
// Flip the UV's since they're probably "upside down"
v1.UV.y = 1.0f - v1.UV.y;
v2.UV.y = 1.0f - v2.UV.y;
v3.UV.y = 1.0f - v3.UV.y;
// Flip Z (LH vs. RH)
v1.Position.z *= -1.0f;
v2.Position.z *= -1.0f;
v3.Position.z *= -1.0f;
// Flip normal's Z
v1.Normal.z *= -1.0f;
v2.Normal.z *= -1.0f;
v3.Normal.z *= -1.0f;
// Add the verts to the vector (flipping the winding order)
verts.push_back(v1);
verts.push_back(v3);
verts.push_back(v2);
vertCounter += 3;
// Add three more indices
indices.push_back(indexCounter); indexCounter += 1;
indices.push_back(indexCounter); indexCounter += 1;
indices.push_back(indexCounter); indexCounter += 1;
// Was there a 4th face?
// - 12 numbers read means 4 faces WITH uv's
// - 8 numbers read means 4 faces WITHOUT uv's
if (numbersRead == 12 || numbersRead == 8)
{
// Make the last vertex
Vertex v4;
v4.Position = positions[i[9] - 1];
v4.UV = uvs[i[10] - 1];
v4.Normal = normals[i[11] - 1];
// Flip the UV, Z pos and normal's Z
v4.UV.y = 1.0f - v4.UV.y;
v4.Position.z *= -1.0f;
v4.Normal.z *= -1.0f;
// Add a whole triangle (flipping the winding order)
verts.push_back(v1);
verts.push_back(v4);
verts.push_back(v3);
vertCounter += 3;
// Add three more indices
indices.push_back(indexCounter); indexCounter += 1;
indices.push_back(indexCounter); indexCounter += 1;
indices.push_back(indexCounter); indexCounter += 1;
}
}
}
// Close the file and create the actual buffers
obj.close();
// - At this point, "verts" is a vector of Vertex structs, and can be used
// directly to create a vertex buffer: &verts[0] is the address of the first vert
//
// - The vector "indices" is similar. It's a vector of unsigned ints and
// can be used directly for the index buffer: &indices[0] is the address of the first int
//
// - "vertCounter" is the number of vertices
// - "indexCounter" is the number of indices
// - Yes, these are effectively the same since OBJs do not index entire vertices! This means
// an index buffer isn't doing much for us. We could try to optimize the mesh ourselves
// and detect duplicate vertices, but at that point it would be better to use a more
// sophisticated model loading library like TinyOBJLoader or The Open Asset Importer Library
// Calculate the tangents and add them to the vertices
CalculateTangents(&verts[0], vertCounter, &indices[0], indexCounter);
// Run CreateBuffers
CreateBuffers(&verts[0], vertCounter, &indices[0], indexCounter, device, context);
}
Mesh::~Mesh()
{
}
Microsoft::WRL::ComPtr<ID3D11Buffer> Mesh::GetVertexBuffer()
{
return vertexBuffer;
}
Microsoft::WRL::ComPtr<ID3D11Buffer> Mesh::GetIndexBuffer()
{
return indexBuffer;
}
int Mesh::GetIndexCount()
{
return indexCount;
}
void Mesh::Draw()
{
// DRAW geometry
// - These steps are generally repeated for EACH object you draw
// - Other Direct3D calls will also be necessary to do more complex things
UINT stride = sizeof(Vertex);
UINT offset = 0;
// Set buffers in the input assembler (IA) stage
// - Do this ONCE PER OBJECT, since each object may have different geometry
// - For this demo, this step *could* simply be done once during Init()
// - However, this needs to be done between EACH DrawIndexed() call
// when drawing different geometry, so it's here as an example
deviceContext->IASetVertexBuffers(0, 1, this->GetVertexBuffer().GetAddressOf(), &stride, &offset);
deviceContext->IASetIndexBuffer(this->GetIndexBuffer().Get(), DXGI_FORMAT_R32_UINT, 0);
// Tell Direct3D to draw
// - Begins the rendering pipeline on the GPU
// - Do this ONCE PER OBJECT you intend to draw
// - This will use all currently set Direct3D resources (shaders, buffers, etc)
// - DrawIndexed() uses the currently set INDEX BUFFER to look up corresponding
// vertices in the currently set VERTEX BUFFER
deviceContext->DrawIndexed(
indexCount, // The number of indices to use (we could draw a subset if we wanted)
0, // Offset to the first index we want to use
0); // Offset to add to each index when looking up vertices
}
void Mesh::CreateBuffers(
Vertex* vertices,
int numVertices,
unsigned int* indices,
int numIndices,
Microsoft::WRL::ComPtr<ID3D11Device> device,
Microsoft::WRL::ComPtr<ID3D11DeviceContext> context
)
{
// Set the reference to the context and index count
deviceContext = context;
indexCount = numIndices;
// Create a VERTEX BUFFER
// - This holds the vertex data of triangles for a single object
// - This buffer is created on the GPU, which is where the data needs to
// be if we want the GPU to act on it (as in: draw it to the screen)
{
// First, we need to describe the buffer we want Direct3D to make on the GPU
// - Note that this variable is created on the stack since we only need it once
// - After the buffer is created, this description variable is unnecessary
D3D11_BUFFER_DESC vbd = {};
vbd.Usage = D3D11_USAGE_IMMUTABLE; // Will NEVER change
vbd.ByteWidth = sizeof(Vertex) * numVertices; // Number of vertices in the buffer
vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; // Tells Direct3D this is a vertex buffer
vbd.CPUAccessFlags = 0; // Note: We cannot access the data from C++ (this is good)
vbd.MiscFlags = 0;
vbd.StructureByteStride = 0;
// Create the proper struct to hold the initial vertex data
// - This is how we initially fill the buffer with data
// - Essentially, we're specifying a pointer to the data to copy
D3D11_SUBRESOURCE_DATA initialVertexData = {};
initialVertexData.pSysMem = vertices; // pSysMem = Pointer to System Memory
// Actually create the buffer on the GPU with the initial data
// - Once we do this, we'll NEVER CHANGE DATA IN THE BUFFER AGAIN
device->CreateBuffer(&vbd, &initialVertexData, vertexBuffer.GetAddressOf());
}
// Create an INDEX BUFFER
// - This holds indices to elements in the vertex buffer
// - This is most useful when vertices are shared among neighboring triangles
// - This buffer is created on the GPU, which is where the data needs to
// be if we want the GPU to act on it (as in: draw it to the screen)
{
// Describe the buffer, as we did above, with two major differences
// - Byte Width (3 unsigned integers vs. 3 whole vertices)
// - Bind Flag (used as an index buffer instead of a vertex buffer)
D3D11_BUFFER_DESC ibd = {};
ibd.Usage = D3D11_USAGE_IMMUTABLE; // Will NEVER change
ibd.ByteWidth = sizeof(unsigned int) * numIndices; // Number of indices in the buffer
ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; // Tells Direct3D this is an index buffer
ibd.CPUAccessFlags = 0; // Note: We cannot access the data from C++ (this is good)
ibd.MiscFlags = 0;
ibd.StructureByteStride = 0;
// Specify the initial data for this buffer, similar to above
D3D11_SUBRESOURCE_DATA initialIndexData = {};
initialIndexData.pSysMem = indices; // pSysMem = Pointer to System Memory
// Actually create the buffer with the initial data
// - Once we do this, we'll NEVER CHANGE THE BUFFER AGAIN
device->CreateBuffer(&ibd, &initialIndexData, indexBuffer.GetAddressOf());
}
}
void Mesh::CalculateTangents(
Vertex* verts,
int numVerts,
unsigned int* indices,
int numIndices
)
{
// --------------------------------------------------------
// Author: Chris Cascioli
// Purpose: Calculates the tangents of the vertices in a mesh
//
// - You are allowed to directly copy/paste this into your code base
// for assignments, given that you clearly cite that this is not
// code of your own design.
//
// - Code originally adapted from: http://www.terathon.com/code/tangent.html
// - Updated version now found here: http://foundationsofgameenginedev.com/FGED2-sample.pdf
// - See listing 7.4 in section 7.5 (page 9 of the PDF)
//
// - Note: For this code to work, your Vertex format must
// contain an XMFLOAT3 called Tangent
//
// - Be sure to call this BEFORE creating your D3D vertex/index buffers
// --------------------------------------------------------
// Reset tangents
for (int i = 0; i < numVerts; i++)
{
verts[i].Tangent = DirectX::XMFLOAT3(0, 0, 0);
}
// Calculate tangents one whole triangle at a time
for (int i = 0; i < numIndices;)
{
// Grab indices and vertices of first triangle
unsigned int i1 = indices[i++];
unsigned int i2 = indices[i++];
unsigned int i3 = indices[i++];
Vertex* v1 = &verts[i1];
Vertex* v2 = &verts[i2];
Vertex* v3 = &verts[i3];
// Calculate vectors relative to triangle positions
float x1 = v2->Position.x - v1->Position.x;
float y1 = v2->Position.y - v1->Position.y;
float z1 = v2->Position.z - v1->Position.z;
float x2 = v3->Position.x - v1->Position.x;
float y2 = v3->Position.y - v1->Position.y;
float z2 = v3->Position.z - v1->Position.z;
// Do the same for vectors relative to triangle uv's
float s1 = v2->UV.x - v1->UV.x;
float t1 = v2->UV.y - v1->UV.y;
float s2 = v3->UV.x - v1->UV.x;
float t2 = v3->UV.y - v1->UV.y;
// Create vectors for tangent calculation
float r = 1.0f / (s1 * t2 - s2 * t1);
float tx = (t2 * x1 - t1 * x2) * r;
float ty = (t2 * y1 - t1 * y2) * r;
float tz = (t2 * z1 - t1 * z2) * r;
// Adjust tangents of each vert of the triangle
v1->Tangent.x += tx;
v1->Tangent.y += ty;
v1->Tangent.z += tz;
v2->Tangent.x += tx;
v2->Tangent.y += ty;
v2->Tangent.z += tz;
v3->Tangent.x += tx;
v3->Tangent.y += ty;
v3->Tangent.z += tz;
}
// Ensure all of the tangents are orthogonal to the normals
for (int i = 0; i < numVerts; i++)
{
// Grab the two vectors
DirectX::XMVECTOR normal = XMLoadFloat3(&verts[i].Normal);
DirectX::XMVECTOR tangent = XMLoadFloat3(&verts[i].Tangent);
// Use Gram-Schmidt orthonormalize to ensure
// the normal and tangent are exactly 90 degrees apart
tangent = DirectX::XMVector3Normalize(
DirectX::XMVectorSubtract(tangent, DirectX::XMVectorMultiply(normal, DirectX::XMVector3Dot(normal, tangent)))
);
// Store the tangent
XMStoreFloat3(&verts[i].Tangent, tangent);
}
}