-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
3186 lines (2716 loc) · 122 KB
/
Copy pathmain.cpp
File metadata and controls
3186 lines (2716 loc) · 122 KB
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3.h>
#include <GLFW/glfw3native.h>
#include "glm/glm.hpp"
#include <d3d11.h>
#include <d3dcompiler.h>
#include <DirectXMath.h>
#include "DirectXTex-main/DirectXTex/DirectXTex.h"
#include "DirectXTK-main/Inc/SpriteBatch.h"
#include "DirectXTK-main/Inc/SpriteFont.h"
#include <DirectXCollision.h>
#include "imgui/imgui.h"
#include "imgui/backends/imgui_impl_glfw.h"
#include "imgui/backends/imgui_impl_dx11.h"
#include <iostream>
#include <vector>
#include <cstring>
#include <fstream>
#include <sstream>
#include <conio.h>
#include <array>
#include <thread>
#include <filesystem>
#include <algorithm>
#include <shlobj.h>
#include <combaseapi.h>
#include <cstdlib>
#include <limits>
#include "zlib-1.3.1/zlib.h"
#include "ImGuizmo.h"
#include "tinyxml2.h"
#include "physx/include/PxPhysics.h"
#include "physx/include/PxPhysicsAPI.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define MAX_POINT_LIGHTS 16
physx::PxFoundation* gFoundation = nullptr;
physx::PxPhysics* gPhysics = nullptr;
physx::PxDefaultCpuDispatcher* gDispatcher = nullptr;
physx::PxScene* gScene = nullptr;
physx::PxMaterial* gMaterial = nullptr;
physx::PxPvd* gPvd = nullptr;
ID3D11Device* g_device = nullptr;
ID3D11DeviceContext* g_deviceContext = nullptr;
IDXGISwapChain* g_swapChain = nullptr;
ID3D11RenderTargetView* g_renderTargetView = nullptr;
ID3D11DepthStencilView* g_depthStencilView = nullptr;
ID3D11DepthStencilState* g_depthStencilState = nullptr;
ID3D11ShaderResourceView* g_texture = nullptr;
ID3D11RasterizerState* g_rasterizerState = nullptr;
ID3D11InputLayout* g_inputLayout = nullptr;
ID3D11Buffer* g_vertexBuffer = nullptr;
ID3D11VertexShader* g_vertexShader = nullptr;
ID3D11PixelShader* g_pixelShader = nullptr;
ID3D11Buffer* g_matrixBuffer = nullptr;
ID3D11Buffer* g_lightBuffer = nullptr;
ID3D11Buffer* g_pointLightBuffer = nullptr;
ID3D11ShaderResourceView* g_pointLightSRV = nullptr;
DirectX::XMMATRIX ortho;
DirectX::XMMATRIX view;
DirectX::XMMATRIX projection;
struct AABB {
DirectX::XMFLOAT3 min;
DirectX::XMFLOAT3 max;
};
#define IMVEC2_SUB(a, b) ImVec2((a).x - (b).x, (a).y - (b).y)
std::unique_ptr<DirectX::SpriteBatch> g_spriteBatch;
std::unique_ptr<DirectX::SpriteFont> g_spriteFont;
struct PointLight
{
DirectX::XMFLOAT3 position;
float range;
DirectX::XMFLOAT3 color;
float intensity;
};
std::vector<PointLight> pointLights;
std::vector<std::string> plNames;
struct LightBuffer
{
DirectX::XMFLOAT3 dirLightDirection;
float pad1;
DirectX::XMFLOAT3 dirLightColor;
float pad2;
DirectX::XMFLOAT3 cameraPosition;
float pad3;
int numPointLights;
float pad4[3]; // Padding to align to 16 bytes
};
struct Vertex {
DirectX::XMFLOAT3 position;
DirectX::XMFLOAT3 normal;
DirectX::XMFLOAT2 texCoord;
};
struct MatrixBuffer {
DirectX::XMMATRIX world;
DirectX::XMMATRIX view;
DirectX::XMMATRIX projection;
};
struct Model
{
std::string name;
std::string filePath;
std::vector<Vertex> vertices;
ID3D11Buffer* vertexBuffer = nullptr;
DirectX::XMFLOAT3 position = {0, 0, 0};
DirectX::XMFLOAT3 rotation = {0, 0, 0};
float scale = 1.0f;
bool valid = false;
ID3D11ShaderResourceView* textureSRV = nullptr;
std::string id;
AABB localBounds;
AABB worldBounds;
physx::PxRigidDynamic* rigidBody = nullptr;
bool isStatic = false;
float mass = 0.0f;
};
struct LoadedTexture {
std::string name;
ID3D11ShaderResourceView* srv;
};
struct TextureInfo {
std::string name;
std::string path;
ID3D11ShaderResourceView* srv;
};
struct Camera {
DirectX::XMFLOAT3 position;
DirectX::XMFLOAT2 rotation;
float fov;
std::string name;
bool isFPS;
};
enum class UIElementType {
None = 0,
Label = 1,
Button = 2,
// ...
};
struct UIElement {
float x, y, width, height;
DirectX::XMFLOAT4 color = {1.0f, 1.0f, 1.0f, 1.0f};
std::string name;
float textScale = 1.0f;
UIElementType type = UIElementType::None;
virtual void Draw() = 0;
virtual void Update(float mouseX, float mouseY, bool clicked) {}
};
std::vector<std::unique_ptr<UIElement>> uiElements;
struct UILabel : public UIElement {
std::string text;
void Draw() override
{
g_spriteBatch->Begin();
g_spriteFont->DrawString(
g_spriteBatch.get(),
std::wstring(text.begin(), text.end()).c_str(),
DirectX::XMFLOAT2(x, y),
DirectX::XMVECTOR{color.x, color.y, color.z, color.w},
0.0f,
DirectX::XMFLOAT2(0.0f, 0.0f),
textScale
);
g_spriteBatch->End();
}
UILabel() {
type = UIElementType::Label;
}
};
struct UIButton : public UIElement {
std::string text;
DirectX::XMFLOAT4 hoverColor = {0.0f, 0.8f, 0.2f, 1.0f};
std::function<void()> onClick;
bool hovered = false;
bool wasPressed = false;
void Update(float mx, float my, bool clicked) override
{
hovered = (mx >= x && mx <= x + width &&
my >= y && my <= y + height);
if(hovered && clicked && !wasPressed)
{
if(onClick) onClick();
wasPressed = true;
}
if(!clicked)
{
wasPressed = false;
}
}
void Draw() override
{
if(!g_spriteBatch || !g_spriteFont) return;
const auto& col = hovered ? hoverColor : color;
g_spriteBatch->Begin();
g_spriteFont->DrawString(
g_spriteBatch.get(),
std::wstring(text.begin(), text.end()).c_str(),
DirectX::XMFLOAT2(x, y),
DirectX::XMVECTOR{col.x, col.y, col.z, col.w},
0.0f,
DirectX::XMFLOAT2(0.0f, 0.0f),
textScale
);
g_spriteBatch->End();
}
UIButton() {
type = UIElementType::Button;
}
};
std::vector<std::string> scripts;
std::vector<Camera> g_cameras;
std::vector<LoadedTexture> g_textures;
std::vector<TextureInfo> g_texture_info;
std::vector<Model> g_models;
std::string projectPath;
std::vector<int> g_texture_ids;
ImVec2 gameSize;
std::vector<Vertex> g_vertices;
std::vector<uint32_t> g_indices;
void InitPhysics()
{
static physx::PxDefaultErrorCallback gDefaultErrorCallback;
static physx::PxDefaultAllocator gDefaultAllocatorCallback;
gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gDefaultAllocatorCallback, gDefaultErrorCallback);
gPvd = physx::PxCreatePvd(*gFoundation);
physx::PxPvdTransport* transport = physx::PxDefaultPvdSocketTransportCreate("127.0.0.1", 5425, 10);
gPvd->connect(*transport, physx::PxPvdInstrumentationFlag::eALL);
gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, physx::PxTolerancesScale(), true, gPvd);
physx::PxSceneDesc sceneDesc(gPhysics->getTolerancesScale());
sceneDesc.gravity = physx::PxVec3(0.0f, -9.81f, 0.0f);
gDispatcher = physx::PxDefaultCpuDispatcherCreate(2);
sceneDesc.cpuDispatcher = gDispatcher;
sceneDesc.filterShader = physx::PxDefaultSimulationFilterShader;
gScene = gPhysics->createScene(sceneDesc);
gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // static friction, dynamic friction, restitution
}
void InitDX(HWND hwnd, GLFWwindow* window)
{
std::cout << "Checking version" << '\n';
IMGUI_CHECKVERSION();
std::cout << "Checking version done" << '\n';
std::cout << "Creating context" << '\n';
ImGui::CreateContext();
std::cout << "Creating context done" << '\n';
std::cout << "style colors" << '\n';
ImGui::StyleColorsDark();
std::cout << "style colors done" << '\n';
std::cout << "init for opengl" << '\n';
ImGui_ImplGlfw_InitForOpenGL(window, true);
std::cout << "init for opengl done" << '\n';
DXGI_SWAP_CHAIN_DESC swapChainDesc = {};
swapChainDesc.BufferCount = 1;
swapChainDesc.BufferDesc.Width = 1920;
swapChainDesc.BufferDesc.Height = 1080;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.OutputWindow = hwnd;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.Windowed = TRUE;
D3D_FEATURE_LEVEL featureLevel;
HRESULT hr = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION, &swapChainDesc, &g_swapChain, &g_device, &featureLevel, &g_deviceContext);
if(FAILED(hr))
{
std::cerr << "Failed to create DirectX device and swap chain." << '\n';
exit(-1);
}
std::cout << "init for dx11" << '\n';
ImGui_ImplDX11_Init(g_device, g_deviceContext);
std::cout << "init for dx11 done" << '\n';
ID3D11Texture2D* pBackBuffer = nullptr;
hr = g_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&pBackBuffer);
if(FAILED(hr))
{
std::cerr << "Failed to get back buffer" << '\n';
exit(-1);
}
hr = g_device->CreateRenderTargetView(pBackBuffer, nullptr, &g_renderTargetView);
pBackBuffer->Release();
if(FAILED(hr))
{
std::cerr << "Failed to create render target view" << '\n';
exit(-1);
}
D3D11_TEXTURE2D_DESC depthStencilDesc = {};
depthStencilDesc.Width = 1920;
depthStencilDesc.Height = 1080;
depthStencilDesc.MipLevels = 1;
depthStencilDesc.ArraySize = 1;
depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilDesc.SampleDesc.Count = 1;
depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
ID3D11Texture2D* pDepthStencilBuffer = nullptr;
hr = g_device->CreateTexture2D(&depthStencilDesc, nullptr, &pDepthStencilBuffer);
if(FAILED(hr))
{
std::cerr << "Failed to create depth stencil buffer" << '\n';
exit(-1);
}
hr = g_device->CreateDepthStencilView(pDepthStencilBuffer, nullptr, &g_depthStencilView);
pDepthStencilBuffer->Release();
if(FAILED(hr))
{
std::cerr << "Failed to create depth stencil view" << '\n';
exit(-1);
}
D3D11_BUFFER_DESC lightBufferDesc = {};
lightBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
lightBufferDesc.ByteWidth = sizeof(LightBuffer);
lightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
lightBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
hr = g_device->CreateBuffer(&lightBufferDesc, nullptr, &g_lightBuffer);
if(FAILED(hr))
{
std::cerr << "Failed to create light buffer!\n";
}
D3D11_BUFFER_DESC lightDesc = {};
lightDesc.Usage = D3D11_USAGE_DYNAMIC;
lightDesc.ByteWidth = sizeof(PointLight) * MAX_POINT_LIGHTS;
lightDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
lightDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
lightDesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;
lightDesc.StructureByteStride = sizeof(PointLight);
g_device->CreateBuffer(&lightDesc, nullptr, &g_pointLightBuffer);
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Format = DXGI_FORMAT_UNKNOWN;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER;
srvDesc.Buffer.FirstElement = 0;
srvDesc.Buffer.NumElements = MAX_POINT_LIGHTS;
hr = g_device->CreateShaderResourceView(g_pointLightBuffer, &srvDesc, &g_pointLightSRV);
g_deviceContext->OMSetRenderTargets(1, &g_renderTargetView, g_depthStencilView);
D3D11_VIEWPORT viewport = {};
viewport.Width = 1920;
viewport.Height = 1080;
g_deviceContext->RSSetViewports(1, &viewport);
}
void CleanDX()
{
if(g_texture) g_texture->Release();
if(g_inputLayout) g_inputLayout->Release();
if(g_vertexBuffer) g_vertexBuffer->Release();
if(g_vertexShader) g_vertexShader->Release();
if(g_pixelShader) g_pixelShader->Release();
if(g_matrixBuffer) g_matrixBuffer->Release();
if(g_deviceContext) g_deviceContext->ClearState();
if(g_renderTargetView) g_renderTargetView->Release();
if(g_depthStencilView) g_depthStencilView->Release();
if(g_swapChain) g_swapChain->Release();
if(g_deviceContext) g_deviceContext->Release();
if(g_device) g_device->Release();
if(g_lightBuffer) g_lightBuffer->Release();
g_texture = nullptr;
g_inputLayout = nullptr;
g_vertexBuffer = nullptr;
g_vertexShader = nullptr;
g_pixelShader = nullptr;
g_matrixBuffer = nullptr;
g_renderTargetView = nullptr;
g_depthStencilView = nullptr;
g_swapChain = nullptr;
g_deviceContext = nullptr;
g_device = nullptr;
g_lightBuffer = nullptr;
}
bool ReadFileBinary(const std::string& path, std::vector<char>& outData)
{
std::ifstream in(path, std::ios::binary);
if(!in) return false;
outData.assign((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
return true;
}
void CompileShaders()
{
std::vector<char> vsData;
std::vector<char> psData;
if(!ReadFileBinary("vs.cso", vsData) || !ReadFileBinary("ps.cso", psData))
{
std::cerr << "Failed to read precompiled shaders\n";
return;
}
HRESULT hr = g_device->CreateVertexShader(vsData.data(), vsData.size(), nullptr, &g_vertexShader);
if(FAILED(hr)) { std::cerr << "Failed to create vertex shader\n"; return; }
hr = g_device->CreatePixelShader(psData.data(), psData.size(), nullptr, &g_pixelShader);
if(FAILED(hr)) { std::cerr << "Failed to create pixel shader\n"; return; }
D3D11_INPUT_ELEMENT_DESC layout[] = {
{ "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 = g_device->CreateInputLayout(layout, ARRAYSIZE(layout), vsData.data(), vsData.size(), &g_inputLayout);
if(FAILED(hr)) { std::cerr << "Failed to create input layout\n"; return; }
if(FAILED(hr))
{
std::cerr << "Failed to create input layout" << std::endl;
}
else
{
std::cout << "Created input layout" << '\n';
}
D3D11_BUFFER_DESC cbDesc = {};
cbDesc.Usage = D3D11_USAGE_DYNAMIC;
cbDesc.ByteWidth = sizeof(MatrixBuffer);
cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
hr = g_device->CreateBuffer(&cbDesc, nullptr, &g_matrixBuffer);
if(FAILED(hr))
{
std::cerr << "Failed to create constant buffer" << std::endl;
}
else
{
std::cout << "Created matrix buffer" << '\n';
}
ID3D11SamplerState* samplerState;
D3D11_SAMPLER_DESC samplerDesc = {};
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
hr = g_device->CreateSamplerState(&samplerDesc, &samplerState);
if(FAILED(hr))
{
std::cerr << "Failed to create sampler state" << std::endl;
}
else
{
g_deviceContext->PSSetSamplers(0, 1, &samplerState);
samplerState->Release();
std::cout << "Created and set sampler state" << '\n';
}
}
std::string OpenFileDialog(const char* filter, bool save = false)
{
char filename[MAX_PATH] = "";
OPENFILENAME ofn = { 0 };
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.lpstrFilter = filter;
ofn.lpstrFile = filename;
ofn.nMaxFile = MAX_PATH;
if(save)
{
ofn.Flags = OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST;
ofn.lpstrTitle = "Save File";
if(GetSaveFileName(&ofn))
return filename;
}
else
{
ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
ofn.lpstrTitle = "Open File";
if(GetOpenFileName(&ofn))
return filename;
}
return "";
}
Model LoadOBJModel(const std::string& path, float scale = 1.0f)
{
Model model;
std::cout << "Loading OBJ: " << path << std::endl;
std::ifstream file(path);
if(!file.is_open())
{
std::cerr << "Failed to open file: " << path << std::endl;
return model;
}
model.vertices.clear();
std::vector<DirectX::XMFLOAT3> positions;
std::vector<DirectX::XMFLOAT3> normals;
std::vector<DirectX::XMFLOAT2> texcoords;
positions.push_back({0, 0, 0});
normals.push_back({0, 0, 1});
texcoords.push_back({0, 0});
std::string line;
while(std::getline(file, line))
{
std::istringstream iss(line);
std::string type;
iss >> type;
if(type == "v")
{
float x, y, z;
iss >> x >> y >> z;
positions.emplace_back(x, y, z);
}
else if(type == "vn")
{
float nx, ny, nz;
iss >> nx >> ny >> nz;
normals.emplace_back(nx, ny, nz);
}
else if(type == "vt")
{
float u, v;
iss >> u >> v;
texcoords.emplace_back(u, 1.0f - v);
}
else if(type == "f")
{
std::string vertexData;
std::vector<std::string> faceVertices;
while(iss >> vertexData)
{
faceVertices.push_back(vertexData);
}
for(size_t i = 2; i < faceVertices.size(); ++i)
{
std::array<std::string, 3> triangleVerts = {
faceVertices[0], faceVertices[i-1], faceVertices[i]
};
for(const auto& vert : triangleVerts)
{
Vertex vtx;
vtx.position = {0, 0, 0};
vtx.normal = {0, 0, 1};
vtx.texCoord = {0, 0};
size_t slash1 = vert.find('/');
if(slash1 != std::string::npos)
{
int posIndex = std::stoi(vert.substr(0, slash1));
if(posIndex < 0)
posIndex = positions.size() + posIndex;
else
posIndex = posIndex;
if(posIndex > 0 && posIndex < positions.size())
{
vtx.position = positions[posIndex];
}
size_t slash2 = vert.find('/', slash1 + 1);
if(slash2 > slash1 + 1)
{
int texIndex = std::stoi(vert.substr(slash1 + 1, slash2 - slash1 - 1));
if(texIndex < 0)
texIndex = texcoords.size() + texIndex;
if(texIndex > 0 && texIndex < texcoords.size())
{
vtx.texCoord = texcoords[texIndex];
}
}
if(slash2 != std::string::npos && slash2 + 1 < vert.length())
{
int normIndex = std::stoi(vert.substr(slash2 + 1));
if(normIndex < 0)
normIndex = normals.size() + normIndex;
if(normIndex > 0 && normIndex < normals.size())
{
vtx.normal = normals[normIndex];
}
}
}
else
{
int posIndex = std::stoi(vert);
if(posIndex < 0)
posIndex = positions.size() + posIndex;
if(posIndex > 0 && posIndex < (int)positions.size())
{
DirectX::XMFLOAT3 pos = positions[posIndex];
vtx.position = { pos.x * scale, pos.y * scale, pos.z * scale };
}
}
model.vertices.push_back(vtx);
}
}
}
}
if(model.vertices.empty())
{
std::cerr << "No vertices loaded from OBJ file: " << path << std::endl;
return model;
}
if(normals.size() <= 1)
{
std::cout << "No normals in OBJ file, calculating face normals..." << std::endl;
for(size_t i = 0; i < model.vertices.size(); i += 3)
{
if(i + 2 < model.vertices.size())
{
DirectX::XMVECTOR v0 = DirectX::XMLoadFloat3(&model.vertices[i].position);
DirectX::XMVECTOR v1 = DirectX::XMLoadFloat3(&model.vertices[i+1].position);
DirectX::XMVECTOR v2 = DirectX::XMLoadFloat3(&model.vertices[i+2].position);
DirectX::XMVECTOR edge1 = DirectX::XMVectorSubtract(v1, v0);
DirectX::XMVECTOR edge2 = DirectX::XMVectorSubtract(v2, v0);
DirectX::XMVECTOR normal = DirectX::XMVector3Normalize(
DirectX::XMVector3Cross(edge1, edge2)
);
DirectX::XMFLOAT3 normalFloat3;
DirectX::XMStoreFloat3(&normalFloat3, normal);
model.vertices[i].normal = normalFloat3;
model.vertices[i+1].normal = normalFloat3;
model.vertices[i+2].normal = normalFloat3;
}
}
}
std::cout << "Loaded " << model.vertices.size() << " vertices from OBJ file" << std::endl;
if(model.vertexBuffer)
{
model.vertexBuffer->Release();
model.vertexBuffer = nullptr;
}
D3D11_BUFFER_DESC vbDesc = {};
vbDesc.Usage = D3D11_USAGE_DEFAULT;
vbDesc.ByteWidth = sizeof(Vertex) * model.vertices.size();
vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
D3D11_SUBRESOURCE_DATA initData = {};
initData.pSysMem = model.vertices.data();
HRESULT hr = g_device->CreateBuffer(&vbDesc, &initData, &model.vertexBuffer);
if(FAILED(hr))
{
std::cerr << "Failed to create vertex buffer! HRESULT: " << hr << std::endl;
}
else
{
std::cout << "Successfully created vertex buffer" << std::endl;
}
model.valid = true;
model.filePath = path;
return model;
}
ID3D11ShaderResourceView* g_textureSRV = nullptr;
ID3D11ShaderResourceView* LoadTexture(const std::string& path)
{
int width, height, channels;
unsigned char* imageData = stbi_load(path.c_str(), &width, &height, &channels, STBI_rgb_alpha);
if(!imageData)
{
std::cerr << "Failed to load image: " << path << '\n';
return nullptr;
}
D3D11_TEXTURE2D_DESC texDesc = {};
texDesc.Width = width;
texDesc.Height = height;
texDesc.MipLevels = 1;
texDesc.ArraySize = 1;
texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texDesc.SampleDesc.Count = 1;
texDesc.Usage = D3D11_USAGE_DEFAULT;
texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texDesc.CPUAccessFlags = 0;
D3D11_SUBRESOURCE_DATA initData = {};
initData.pSysMem = imageData;
initData.SysMemPitch = width * 4;
initData.SysMemSlicePitch = width * height * 4;
ID3D11Texture2D* texture = nullptr;
HRESULT hr = g_device->CreateTexture2D(&texDesc, &initData, &texture);
if(FAILED(hr))
{
std::cerr << "Failed to create texture from image: " << path << '\n';
stbi_image_free(imageData);
return nullptr;
}
ID3D11ShaderResourceView* textureSRV = nullptr;
hr = g_device->CreateShaderResourceView(texture, nullptr, &textureSRV);
texture->Release();
stbi_image_free(imageData);
if(FAILED(hr))
{
std::cerr << "Failed to create shader resource view: " << path << '\n';
return nullptr;
}
return textureSRV;
}
std::string MakeUniqueName(const std::string& baseName, const std::vector<std::string>& existingNames)
{
std::string uniqueName = baseName;
int counter = 1;
while(std::find(existingNames.begin(), existingNames.end(), uniqueName) != existingNames.end())
uniqueName = baseName + " (" + std::to_string(counter++) + ")";
return uniqueName;
}
void ResizeSwapChain(int width, int height)
{
if(width <= 0 || height <= 0 || !g_device || !g_swapChain)
return;
if(g_renderTargetView) g_renderTargetView->Release();
if(g_depthStencilView) g_depthStencilView->Release();
HRESULT hr = g_swapChain->ResizeBuffers(1, width, height, DXGI_FORMAT_R8G8B8A8_UNORM, 0);
if(FAILED(hr))
{
std::cerr << "Failed to resize swap chain buffers!" << std::endl;
return;
}
ID3D11Texture2D* pBackBuffer = nullptr;
hr = g_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&pBackBuffer);
if(FAILED(hr))
{
std::cerr << "Failed to get back buffer after resize" << std::endl;
return;
}
hr = g_device->CreateRenderTargetView(pBackBuffer, nullptr, &g_renderTargetView);
pBackBuffer->Release();
if(FAILED(hr))
{
std::cerr << "Failed to create render target view after resize" << std::endl;
return;
}
D3D11_TEXTURE2D_DESC depthStencilDesc = {};
depthStencilDesc.Width = width;
depthStencilDesc.Height = height;
depthStencilDesc.MipLevels = 1;
depthStencilDesc.ArraySize = 1;
depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilDesc.SampleDesc.Count = 1;
depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
ID3D11Texture2D* pDepthStencilBuffer = nullptr;
hr = g_device->CreateTexture2D(&depthStencilDesc, nullptr, &pDepthStencilBuffer);
if(FAILED(hr))
{
std::cerr << "Failed to create depth stencil buffer after resize" << std::endl;
return;
}
hr = g_device->CreateDepthStencilView(pDepthStencilBuffer, nullptr, &g_depthStencilView);
pDepthStencilBuffer->Release();
if(FAILED(hr))
{
std::cerr << "Failed to create depth stencil view after resize" << std::endl;
return;
}
g_deviceContext->OMSetRenderTargets(1, &g_renderTargetView, g_depthStencilView);
D3D11_VIEWPORT viewport = {};
viewport.Width = static_cast<float>(width);
viewport.Height = static_cast<float>(height);
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
g_deviceContext->RSSetViewports(1, &viewport);
}
void WindowResizeCallback(GLFWwindow* window, int width, int height)
{
if(width > 0 && height > 0)
ResizeSwapChain(width, height);
}
ID3D11ShaderResourceView* LoadTextureIfNotLoaded(const std::string& path)
{
for(const auto& info : g_texture_info)
{
if(info.path == path)
return info.srv;
}
ID3D11ShaderResourceView* srv = LoadTexture(path);
if(!srv)
return nullptr;
std::string fileName = std::filesystem::path(path).filename().string();
std::vector<std::string> existingTextureNames;
for(const auto& tex : g_textures)
existingTextureNames.push_back(tex.name);
std::string uniqueName = MakeUniqueName(fileName, existingTextureNames);
//g_texture_info.push_back({ uniqueName, path, srv });
//g_textures.push_back({ uniqueName, srv });
return srv;
}
std::string fontPath;
void SaveProject(const std::string& path, const std::vector<Model>& models)
{
std::ofstream file(path, std::ios::binary);
if(!file.is_open())
{
std::cerr << "Failed to open file for saving: " << path << std::endl;
return;
}
const char* header = "GE3PROJ";
file.write(header, 7);
uint32_t version = 1;
file.write(reinterpret_cast<const char*>(&version), sizeof(version));
uint32_t modelCount = static_cast<uint32_t>(models.size());
file.write(reinterpret_cast<const char*>(&modelCount), sizeof(modelCount));
uint32_t scriptCount = static_cast<uint32_t>(scripts.size());
file.write(reinterpret_cast<const char*>(&scriptCount), sizeof(scriptCount));
uint32_t camCount = static_cast<uint32_t>(g_cameras.size());
file.write(reinterpret_cast<const char*>(&camCount), sizeof(camCount));
uint32_t uiCount = static_cast<uint32_t>(uiElements.size());
file.write(reinterpret_cast<const char*>(&uiCount), sizeof(uiCount));
uint32_t plCount = static_cast<uint32_t>(pointLights.size());
file.write(reinterpret_cast<const char*>(&plCount), sizeof(plCount));
for(const auto& elem : uiElements)
{
uint32_t elemNameLen = static_cast<uint32_t>(elem->name.length());
file.write(reinterpret_cast<const char*>(&elemNameLen), sizeof(elemNameLen));
file.write(elem->name.c_str(), elemNameLen);
file.write(reinterpret_cast<const char*>(&elem->type), sizeof(UIElementType));
file.write(reinterpret_cast<const char*>(&elem->x), sizeof(float));
file.write(reinterpret_cast<const char*>(&elem->y), sizeof(float));
file.write(reinterpret_cast<const char*>(&elem->color), sizeof(DirectX::XMFLOAT4));
if(elem->type == UIElementType::Label)
{
UILabel* label = dynamic_cast<UILabel*>(elem.get());
if(label)
{
uint32_t textLen = static_cast<uint32_t>(label->text.length());
file.write(reinterpret_cast<const char*>(&textLen), sizeof(textLen));
file.write(label->text.c_str(), textLen);
file.write(reinterpret_cast<const char*>(&label->textScale), sizeof(float));
}
}
else if(elem->type == UIElementType::Button)
{
UIButton* button = dynamic_cast<UIButton*>(elem.get());
if(button)
{
uint32_t textLen = static_cast<uint32_t>(button->text.length());
file.write(reinterpret_cast<const char*>(&textLen), sizeof(textLen));
file.write(button->text.c_str(), textLen);
file.write(reinterpret_cast<const char*>(&button->width), sizeof(float));
file.write(reinterpret_cast<const char*>(&button->height), sizeof(float));
file.write(reinterpret_cast<const char*>(&button->textScale), sizeof(float));
file.write(reinterpret_cast<const char*>(&button->hoverColor), sizeof(DirectX::XMFLOAT4));
}
}
}
for(const Camera& cam : g_cameras)
{
uint32_t camNameLen = static_cast<uint32_t>(cam.name.length());
file.write(reinterpret_cast<const char*>(&camNameLen), sizeof(camNameLen));
file.write(cam.name.c_str(), camNameLen);
file.write(reinterpret_cast<const char*>(&cam.position), sizeof(DirectX::XMFLOAT3));
file.write(reinterpret_cast<const char*>(&cam.rotation), sizeof(DirectX::XMFLOAT2));
file.write(reinterpret_cast<const char*>(&cam.fov), sizeof(float));
int isFPSint = cam.isFPS;
file.write(reinterpret_cast<const char*>(&isFPSint), sizeof(int));
}
for(const auto& i : scripts)
{
uint32_t scriptNameLen = static_cast<uint32_t>(i.length());
file.write(reinterpret_cast<const char*>(&scriptNameLen), sizeof(scriptNameLen));
file.write(i.c_str(), scriptNameLen);
}
for(const Model& model : models)
{
uint32_t nameLength = static_cast<uint32_t>(model.name.length());
file.write(reinterpret_cast<const char*>(&nameLength), sizeof(nameLength));
file.write(model.name.c_str(), nameLength);
uint32_t pathLength = static_cast<uint32_t>(model.filePath.length());
file.write(reinterpret_cast<const char*>(&pathLength), sizeof(pathLength));
file.write(model.filePath.c_str(), pathLength);