-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWorld.cpp
More file actions
624 lines (582 loc) · 15.6 KB
/
Copy pathWorld.cpp
File metadata and controls
624 lines (582 loc) · 15.6 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
#include "World.h"
#include "GameObject.h"
#include "ImGUImpl.h"
#include "WorldEvents.hpp"
#include "AssetLoaderFactory.h"
#include "GameRenderer.h"
#include "Component/Phys/RigidBody.h"
#include "Component/Phys/Collider.h"
#include "Component/Render/Camera.h"
#include "Core/GarbageCollection.h"
#include "Core/Util.h"
#include "Core/SObjectManager.h"
#include "Core/Asset.h"
#include "Render/Renderer.h"
#include "Render/ShadowMapManager.h"
#include <utility>
#include <cstdint>
namespace sh::game
{
SH_GAME_API World::World(sh::render::Renderer& renderer, ImGUImpl& guiContext) :
renderer(renderer), componentModule(*game::ComponentModule::GetInstance()), imgui(&guiContext),
mainCamera(nullptr),
lightOctree(render::AABB{-1000, -1000, -1000, 1000, 1000, 1000})
{
SetName("World");
gc = core::GarbageCollection::GetInstance();
shadowMapManager = std::make_unique<render::ShadowMapManager>();
physEventSubscriber.SetCallback(
[](const phys::PhysicsEvent& evt)
{
const auto callCollisionFn =
[](const phys::PhysicsEvent& evt, RigidBody* rb1Ptr, Collider* collider2Ptr)
{
if (core::IsValid(rb1Ptr))
{
if (evt.type == phys::PhysicsEvent::Type::CollisionEnter ||
evt.type == phys::PhysicsEvent::Type::CollisionStay ||
evt.type == phys::PhysicsEvent::Type::CollisionExit)
{
if (evt.contactCount < Collision::ARRAY_SIZE)
{
std::array<phys::ContactPoint, Collision::ARRAY_SIZE> contactPoint;
for (uint32_t i = 0; i < evt.contactCount; ++i)
evt.getContactPointFn(contactPoint[i], i);
Collision collision{ contactPoint };
collision.collider = collider2Ptr;
collision.contactCount = evt.contactCount;
if (evt.type == phys::PhysicsEvent::Type::CollisionEnter)
rb1Ptr->gameObject.OnCollisionEnter(std::move(collision));
else if (evt.type == phys::PhysicsEvent::Type::CollisionStay)
rb1Ptr->gameObject.OnCollisionStay(std::move(collision));
else if (evt.type == phys::PhysicsEvent::Type::CollisionExit)
rb1Ptr->gameObject.OnCollisionExit(std::move(collision));
}
else
{
std::vector<phys::ContactPoint> contactPoint(evt.contactCount);
for (uint32_t i = 0; i < evt.contactCount; ++i)
evt.getContactPointFn(contactPoint[i], i);
Collision collision{ std::move(contactPoint) };
collision.collider = collider2Ptr;
collision.contactCount = evt.contactCount;
if (evt.type == phys::PhysicsEvent::Type::CollisionEnter)
rb1Ptr->gameObject.OnCollisionEnter(std::move(collision));
if (evt.type == phys::PhysicsEvent::Type::CollisionStay)
rb1Ptr->gameObject.OnCollisionStay(std::move(collision));
else if (evt.type == phys::PhysicsEvent::Type::CollisionExit)
rb1Ptr->gameObject.OnCollisionExit(std::move(collision));
}
}
else
{
if (!core::IsValid(collider2Ptr))
return;
if (evt.type == phys::PhysicsEvent::Type::TriggerEnter)
rb1Ptr->gameObject.OnTriggerEnter(*collider2Ptr);
else if (evt.type == phys::PhysicsEvent::Type::TriggerExit)
rb1Ptr->gameObject.OnTriggerExit(*collider2Ptr);
}
}
};
RigidBody* const rb1Ptr = RigidBody::GetRigidBodyUsingHandle(evt.rigidBody1Handle);
RigidBody* const rb2Ptr = RigidBody::GetRigidBodyUsingHandle(evt.rigidBody2Handle);
Collider* const collider1Ptr = Collider::GetColliderUsingHandle(evt.collider1Handle);
Collider* const collider2Ptr = Collider::GetColliderUsingHandle(evt.collider2Handle);
callCollisionFn(evt, rb1Ptr, collider2Ptr);
callCollisionFn(evt, rb2Ptr, collider1Ptr);
}
);
physWorld.bus.Subscribe(physEventSubscriber);
}
SH_GAME_API World::~World()
{
SH_INFO_FORMAT("~World {}", GetUUID().ToString());
Clear();
physWorld.bus.Unsubscribe(physEventSubscriber);
physWorld.Clean();
}
SH_GAME_API void World::OnDestroy()
{
Clear();
Super::OnDestroy();
}
SH_GAME_API auto World::Serialize() const -> core::Json
{
if (IsLoaded())
{
core::Json mainJson = Super::Serialize();
core::Json& objsJson = mainJson["objs"];
for (auto obj : objs)
{
if (obj->bNotSave || !core::IsValid(obj))
continue;
objsJson.push_back(obj->Serialize());
}
return mainJson;
}
const core::Json* worldPointPtr = GetWorldPoint();
if (worldPointPtr == nullptr || worldPointPtr->empty() || worldPointPtr->is_discarded())
return core::Json();
return *worldPointPtr;
}
SH_GAME_API void World::Deserialize(const core::Json& json)
{
bLoaded = true;
Super::Deserialize(json);
if (!json.contains("objs"))
{
bLoaded = false;
return;
}
bool hasCustomRenderer = customRenderer != nullptr;
CleanObjs();
if (hasCustomRenderer)
SetupRenderer();
InitResource();
core::SObjectManager* objManager = core::SObjectManager::GetInstance();
// 유효한 참조를 위해 두번 로드하는 과정을 거친다.
// 생성만 하는 과정
for (const auto& objJson : json["objs"])
{
const std::string& name = objJson["name"].get_ref<const std::string&>();
core::UUID objuuid{ objJson["uuid"].get_ref<const std::string&>() };
auto sobj = objManager->GetSObject(objuuid);
GameObject* gameObj = nullptr;
if (core::IsValid(sobj)) // 이미 월드 상에 존재 할 경우
{
gameObj = static_cast<GameObject*>(sobj);
// 모든 컴포넌트 제거
for (int i = 0; i < gameObj->GetComponents().size(); ++i)
{
Component* component = gameObj->GetComponents()[i];
if (component == nullptr)
continue;
component->SetUUID(core::UUID::Generate());
component->Destroy();
}
}
else
{
if (sobj != nullptr) // pending kill
sobj->SetUUID(core::UUID::Generate());
gameObj = this->AddGameObject(name);
gameObj->SetUUID(objuuid);
}
for (auto& compJson : objJson["Components"])
{
std::string name{ compJson["name"].get<std::string>() };
std::string type{ compJson["type"].get<std::string>() };
core::UUID uuid{ compJson["uuid"].get<std::string>() };
if (type == "Transform") // 트랜스폼은 게임오브젝트 생성 시 이미 만들어져있다.
{
if (gameObj->transform->GetUUID() != uuid)
{
// 실패 했다면 이미 해당 트랜스폼이 존재하는 상태
if (!gameObj->transform->SetUUID(uuid))
{
auto obj = core::SObjectManager::GetInstance()->GetSObject(uuid);
// 보류 상태라면 UUID 변경
if (obj != nullptr && obj->IsPendingKill())
{
obj->SetUUID(core::UUID::Generate());
gameObj->transform->SetUUID(uuid);
}
}
}
continue;
}
auto compType = ComponentModule::GetInstance()->GetComponent(name);
if (compType == nullptr)
{
SH_ERROR_FORMAT("Not found component - {}", type);
continue;
}
Component* component = compType->Create(*gameObj);
// 실패 했다면 이미 해당 컴포넌트가 존재하는 상태 (PendingKill상태 일 수도 있음)
if (!component->SetUUID(core::UUID{ uuid }))
{
auto obj = core::SObjectManager::GetInstance()->GetSObject(uuid);
// 보류 상태라면 UUID 변경
if (obj != nullptr && obj->IsPendingKill())
{
obj->SetUUID(core::UUID::Generate());
component->SetUUID(core::UUID{ uuid });
}
}
gameObj->AddComponent(component);
}
}
// 역 직렬화
for (const auto& objJson : json["objs"])
{
GameObject* obj = static_cast<GameObject*>(objManager->GetSObject(core::UUID{ objJson["uuid"].get<std::string>() }));
obj->Deserialize(objJson);
}
for (auto obj : objs)
{
if (!obj->activeSelf)
obj->PropagateEnable();
}
for (auto& obj : addedObjs)
{
if (!obj->activeSelf)
obj->PropagateEnable();
}
}
SH_GAME_API void World::Clear()
{
if (shadowMapManager != nullptr)
shadowMapManager->Clear();
CleanObjs();
while (!deallocatedObjs.empty())
{
objPool.DeAllocate(deallocatedObjs.front());
deallocatedObjs.pop();
}
bStartLoop = false;
bPlaying = false;
bLoaded = false;
bOnStart = false;
}
SH_GAME_API void World::SetupRenderer()
{
customRenderer = std::make_unique<GameRenderer>(*renderer.GetContext(), GetUiContext(), *this);
customRenderer->Init();
renderer.SetScriptableRenderer(*customRenderer);
if (shadowMapManager != nullptr)
shadowMapManager->Init(*renderer.GetContext());
}
SH_GAME_API void World::InitResource()
{
SH_INFO("Init resource");
bLoaded = true;
}
SH_GAME_API void World::CleanObjs()
{
for (auto obj : objs)
{
if (core::IsValid(obj))
obj->Destroy();
}
for (auto& obj : addedObjs)
{
if (obj.IsValid())
obj->Destroy();
}
objIdx.clear();
objs.clear();
cameras.clear();
lightOctree.Clear();
mainCamera = nullptr;
}
SH_GAME_API auto World::AddGameObject(std::string_view name) -> GameObject*
{
GameObject* ptr = AllocateGameObject();
if (ptr == nullptr)
return nullptr;
GameObject* obj = CreateAt<GameObject>(ptr, *this, std::string{ name }, GameObject::CreateKey{});
addedObjs.push_back(obj);
gc->SetRootSet(obj);
eventBus.Publish(events::GameObjectEvent{ *obj, events::GameObjectEvent::Type::Added });
return obj;
}
SH_GAME_API void World::DestroyGameObject(std::string_view name)
{
GameObject* obj = GetGameObject(name);
if (obj != nullptr)
DestroyGameObject(*obj);
}
SH_GAME_API void World::DestroyGameObject(GameObject& obj)
{
if (obj.IsPendingKill())
{
auto it = objIdx.find(&obj);
if (it == objIdx.end())
return;
const std::size_t idx = it->second;
const std::size_t last = objs.size() - 1;
objIdx.erase(it);
if (idx != last)
{
GameObject* moved = objs[last];
objs[idx] = moved;
objIdx[moved] = idx;
}
objs.pop_back();
return;
}
obj.Destroy(); // 이 함수에서 월드의 DestroyGameObject()함수가 호출됨
}
SH_GAME_API auto World::GetGameObject(std::string_view name) const -> GameObject*
{
if (!addedObjs.empty())
{
for (auto& obj : addedObjs)
{
if (!obj.IsValid())
continue;
if (obj->GetName() == name)
return obj.Get();
}
}
for (auto obj : objs)
{
if (!core::IsValid(obj))
continue;
if (obj->GetName() == name)
return obj;
}
return nullptr;
}
SH_GAME_API void World::PushDeAllocatedGameObject(GameObject* ptr)
{
deallocatedObjs.push(ptr);
}
SH_GAME_API void World::Start()
{
bOnStart = true;
}
SH_GAME_API void World::Update(double deltaTime)
{
dt = deltaTime;
if (!bStartLoop)
bStartLoop = true;
if (bWaitPlaying)
{
bPlaying = true;
bWaitPlaying = false;
eventBus.Publish(events::WorldEvent{ events::WorldEvent::Type::Play });
}
for (auto& addedObj : addedObjs)
{
if (addedObj.IsValid())
{
objIdx[addedObj.Get()] = objs.size();
objs.push_back(addedObj.Get());
}
}
addedObjs.clear();
for (auto& obj : objs)
{
if (!core::IsValid(obj))
continue;
obj->Awake();
}
for (auto& obj : objs)
{
if (!core::IsValid(obj))
continue;
if (!obj->IsActive())
continue;
obj->Start();
}
for (auto& obj : objs)
{
if (!sh::core::IsValid(obj))
continue;
if (!obj->IsActive())
continue;
obj->BeginUpdate();
}
dtAccumulator += dt;
while (dtAccumulator >= FIXED_TIME)
{
if (bPlaying)
{
physWorld.Update(FIXED_TIME);
}
for (auto& obj : objs)
{
if (!sh::core::IsValid(obj))
continue;
if (!obj->IsActive())
continue;
obj->FixedUpdate();
}
dtAccumulator -= FIXED_TIME;
}
for (auto& obj : objs)
{
if (!sh::core::IsValid(obj))
continue;
if (!obj->IsActive())
continue;
obj->ProcessCollisionFunctions();
}
for (auto& obj : objs)
{
if (!sh::core::IsValid(obj))
continue;
if (!obj->IsActive())
continue;
obj->Update();
}
for (auto& obj : objs)
{
if (!sh::core::IsValid(obj))
continue;
if (!obj->IsActive())
continue;
obj->LateUpdate();
}
if (shadowMapManager != nullptr)
shadowMapManager->Submit(renderer);
}
SH_GAME_API void World::BeforeSync()
{
while (!beforeSyncTasks.empty())
{
beforeSyncTasks.front()();
beforeSyncTasks.pop();
}
}
SH_GAME_API void World::AfterSync()
{
while (!afterSyncTasks.empty())
{
afterSyncTasks.front()();
afterSyncTasks.pop();
}
}
SH_GAME_API void World::RegisterCamera(Camera& cam)
{
if (cam.IsPendingKill())
return;
for (int i = 0; i < cameras.size(); ++i)
{
if (cameras[i] == &cam)
return;
}
cameras.push_back(&cam);
eventBus.Publish(events::CameraEvent{ cam, events::CameraEvent::Type::Added });
}
SH_GAME_API void World::UnRegisterCamera(Camera& cam)
{
cameras.erase(std::remove(cameras.begin(), cameras.end(), &cam), cameras.end()); // O(n)
eventBus.Publish(events::CameraEvent{ cam, events::CameraEvent::Type::Removed });
}
SH_GAME_API void World::SetMainCamera(Camera* cam)
{
if (!core::IsValid(cam))
return;
mainCamera = cam;
}
SH_GAME_API void World::AddBeforeSyncTask(const std::function<void()>& func)
{
beforeSyncTasks.push(func);
}
SH_GAME_API void World::AddAfterSyncTask(const std::function<void()>& func)
{
afterSyncTasks.push(func);
}
SH_GAME_API void World::SaveWorldPoint(const core::Json& json, std::string_view name)
{
savePoints[std::string{ name }] = json;
}
SH_GAME_API void World::SaveWorldPoint(core::Json&& json, std::string_view name)
{
savePoints[std::string{ name }] = std::move(json);
}
SH_GAME_API void World::LoadWorldPoint()
{
LoadWorldPoint("default");
}
SH_GAME_API void World::LoadWorldPoint(const std::string& name)
{
auto it = savePoints.find(name);
if (it == savePoints.end())
return;
AddAfterSyncTask(
[this, savePoint = it->second]()
{
renderer.Reset();
Deserialize(savePoint);
}
);
}
SH_GAME_API auto World::GetWorldPoint() const -> const core::Json*
{
return GetWorldPoint("default");
}
SH_GAME_API auto World::GetWorldPoint(const std::string& name) const -> const core::Json*
{
auto it = savePoints.find(name);
if (it == savePoints.end())
return nullptr;
return &it->second;
}
SH_GAME_API auto World::GetWorldPoint() -> core::Json*
{
return GetWorldPoint("default");
}
SH_GAME_API auto World::GetWorldPoint(const std::string& name) -> core::Json*
{
auto it = savePoints.find(name);
if (it == savePoints.end())
return nullptr;
return &it->second;
}
SH_GAME_API void World::ClearWorldPoints()
{
savePoints.clear();
}
SH_GAME_API void World::ClearWorldPoint(const std::string& name)
{
savePoints.erase(name);
}
SH_GAME_API void World::PublishEvent(const core::IEvent& event)
{
eventBus.Publish(event);
}
SH_GAME_API void World::SubscribeEvent(core::ISubscriber& subscriber)
{
eventBus.Subscribe(subscriber);
}
SH_GAME_API void World::Play()
{
if (bPlaying || bWaitPlaying)
return;
bWaitPlaying = true;
}
SH_GAME_API void World::Stop()
{
if (!bPlaying)
return;
bPlaying = false;
bOnStart = false;
eventBus.Publish(events::WorldEvent{ events::WorldEvent::Type::Stop });
}
SH_GAME_API void World::ReallocateUUIDS()
{
auto changeObjUUIDfn =
[](GameObject* obj)
{
obj->SetUUID(core::UUID::Generate());
for (auto component : obj->GetComponents())
{
if (component != nullptr)
component->SetUUID(core::UUID::Generate());
}
};
for (auto obj : objs)
{
changeObjUUIDfn(obj);
}
for (auto& obj : addedObjs)
{
if (obj.IsValid())
changeObjUUIDfn(obj.Get());
}
SetUUID(core::UUID::Generate());
}
auto World::AllocateGameObject() -> GameObject*
{
while (!deallocatedObjs.empty())
{
objPool.DeAllocate(deallocatedObjs.front());
deallocatedObjs.pop();
}
return objPool.Allocate();
}
}//namespace