-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFoliageComponent.cpp
More file actions
355 lines (305 loc) · 10.4 KB
/
Copy pathFoliageComponent.cpp
File metadata and controls
355 lines (305 loc) · 10.4 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
#include "FoliageComponent.h"
#include "FoliageSystem.h"
#include "Model.h"
#include "DataSystem.h"
#include "Interfaces/AssetAuthoringPort.h"
#include "SceneManager.h"
#include "RenderScene.h"
#include "Terrain.h"
#include "Scene.h"
#include "Camera.h"
#include "SceneManager.h"
#include "Mathematics.Intersect.h"
#include <mathematics/transform.hpp>
#include <random>
#include <sstream>
void FoliageComponent::OnInitialized()
{
auto scene = GetOwner()->m_ownerScene;
auto renderScene = SceneManagers->GetRenderScene();
if(scene)
{
scene->CollectFoliageComponent(this);
if(renderScene)
{
renderScene->RegisterCommand(this);
}
}
}
// 트랙 C3 — FoliageSystem 등록/해지. Awake/OnDestroy(컴포넌트당 1회 게이트)가
// 아니라 씬 편입/이탈 훅을 쓰는 이유는 AnimatorSystem.h 상단 주석 참고 — DDOL
// 오브젝트가 씬을 건널 때도 매번 다시 불려야 하기 때문이다. 실제 파괴 경로
// (Scene::FlushPendingDestroy·PrefabUtility::ApplyComponentDiff)도
// OnUninitializing(위 OnDestroy 브리지) 직전에 OnRemovingFromScene을 먼저
// 부르므로, 이 시스템에서 빠지는 시점이 항상 실 파괴보다 먼저다.
void FoliageComponent::OnAddedToScene()
{
FoliageSystems->Register(this);
}
void FoliageComponent::OnRemovingFromScene()
{
FoliageSystems->Unregister(this);
}
void FoliageComponent::OnUninitializing()
{
auto scene = GetOwner()->m_ownerScene;
auto renderScene = SceneManagers->GetRenderScene();
if(scene)
{
scene->UnCollectFoliageComponent(this);
if(renderScene)
{
renderScene->UnregisterCommand(this);
}
}
}
void FoliageComponent::SaveFoliageAsset(const file::path& directory,
const std::wstring& name)
{
// 빈 시퀀스를 명시적으로 만든다. 손대지 않은 Node를 그대로 흘리면 yaml-cpp가
// 0바이트를 내보내는데, 그렇게 저장된 자산은 LoadFoliageAsset의
// assetNode["FoliageAsset"] 검사에서 다시 열리지 않는다.
MetaYml::Node typesNode(MetaYml::NodeType::Sequence);
for (auto& type : m_foliageTypes)
{
typesNode.push_back(Meta::Serialize(&type));
}
MetaYml::Node instancesNode(MetaYml::NodeType::Sequence);
for (auto& instance : m_foliageInstances)
{
instancesNode.push_back(Meta::Serialize(&instance));
}
MetaYml::Node assetNode;
assetNode["FoliageAsset"]["Types"] = typesNode;
assetNode["FoliageAsset"]["Instances"] = instancesNode;
std::ostringstream payload;
payload << assetNode;
TextAssetAuthoringRequest request{};
request.destinationDirectory = directory;
request.name = name;
request.payload = payload.str();
TextAssetAuthoringResult result{};
if (!AssetAuthoringPort::WriteFoliage(request, result))
{
Debug->LogError(
"Foliage save requires a complete Editor authoring transaction");
return;
}
m_foliageAssetGuid = result.guid;
Debug->LogDebug("Foliage asset saved to: " + result.assetPath.string());
}
void FoliageComponent::LoadFoliageAsset(FileGuid assetGuid)
{
auto assetPath = DataSystems->GetFilePath(assetGuid);
if (assetPath.empty())
{
std::cerr << "Asset GUID not found: " << assetGuid.ToString() << std::endl;
return;
}
MetaYml::Node assetNode = MetaYml::LoadFile(assetPath.string());
if (assetNode.IsNull() || !assetNode["FoliageAsset"])
{
std::cerr << "Invalid foliage asset file: " << assetPath << std::endl;
return;
}
m_foliageTypes.clear();
m_foliageInstances.clear();
for (const auto& typeNode : assetNode["FoliageAsset"]["Types"])
{
FoliageType type;
Meta::Deserialize(&type, typeNode);
AddFoliageType(type);
}
for (const auto& instanceNode : assetNode["FoliageAsset"]["Instances"])
{
FoliageInstance instance;
Meta::Deserialize(&instance, instanceNode);
AddFoliageInstance(instance);
}
std::cout << "Foliage asset loaded successfully: " << assetPath << std::endl;
}
void FoliageComponent::AddFoliageType(const FoliageType& type)
{
m_foliageTypes.push_back(type);
}
void FoliageComponent::RemoveFoliageType(uint32 typeID)
{
if (typeID < m_foliageTypes.size())
m_foliageTypes.erase(m_foliageTypes.begin() + typeID);
}
void FoliageComponent::AddFoliageInstance(const FoliageInstance& instance)
{
auto found = std::ranges::find_if(m_foliageInstances,
[&](const FoliageInstance& existing)
{
return existing.m_position == instance.m_position;
});
if (found == m_foliageInstances.end())
{
FoliageInstance sealed = instance;
sealed.RebuildWorldMatrix();
m_foliageInstances.push_back(std::move(sealed));
}
}
void FoliageComponent::RemoveFoliageInstance(size_t index)
{
if(index < m_foliageInstances.size())
m_foliageInstances.erase(m_foliageInstances.begin()+index);
}
void FoliageComponent::AddInstanceFromTerrain(TerrainComponent* terrain, const FoliageInstance& instance)
{
if(!terrain) { return; }
FoliageInstance inst = instance;
float* heightMap = terrain->GetHeightMap();
int width = terrain->GetWidth();
int height = terrain->GetHeight();
int x = static_cast<int>(std::clamp(instance.m_position.x, 0.f, static_cast<float>(width-1)));
int y = static_cast<int>(std::clamp(instance.m_position.z, 0.f, static_cast<float>(height-1)));
int idx = y * width + x;
inst.m_position.y = heightMap[idx];
AddFoliageInstance(inst);
}
void FoliageComponent::AddRandomInstancesInBrush(TerrainComponent* terrain, const TerrainBrush& brush, uint32 typeID, int count)
{
if (!terrain || count <= 0) return;
std::mt19937 gen(std::random_device{}());
std::uniform_real_distribution<float> offset(-brush.m_radius, brush.m_radius);
std::uniform_real_distribution<float> rot(0.f, 360.f);
std::uniform_real_distribution<float> scl(0.8f, 1.2f);
for (int i = 0; i < count; ++i)
{
float dx = offset(gen);
float dz = offset(gen);
if (dx * dx + dz * dz > brush.m_radius * brush.m_radius)
{
--i;
continue;
}
FoliageInstance inst;
inst.m_position = { brush.m_center.x + dx, 0.f, brush.m_center.y + dz };
inst.m_rotation = { 0.f, rot(gen), 0.f };
float s = scl(gen);
inst.m_scale = { s, s, s };
inst.m_foliageTypeID = typeID;
AddInstanceFromTerrain(terrain, inst);
}
}
void FoliageComponent::RemoveInstancesInBrush(TerrainComponent* terrain, const TerrainBrush& brush)
{
(void)terrain;
m_foliageInstances.erase(std::remove_if(m_foliageInstances.begin(), m_foliageInstances.end(),
[&](const FoliageInstance& inst)
{
float dx = inst.m_position.x - brush.m_center.x;
float dz = inst.m_position.z - brush.m_center.y;
return dx * dx + dz * dz <= brush.m_radius * brush.m_radius;
}), m_foliageInstances.end());
}
//helper
std::vector<std::pair<size_t, size_t>> DivideRangeAuto(size_t count)
{
std::vector<std::pair<size_t, size_t>> ranges;
if (count == 0)
return ranges;
unsigned int hwThreads = std::thread::hardware_concurrency();
if (hwThreads == 0) hwThreads = 4; // ���� �⺻�� (�̰��� ��)
const size_t numSplits = hwThreads * 2 + 1;
ranges.reserve(numSplits);
const size_t chunk = (count + numSplits - 1) / numSplits; // ceil(count / numSplits)
size_t begin = 0;
for (size_t i = 0; i < numSplits; ++i)
{
size_t end = std::min(begin + chunk, count);
if (begin >= end)
break;
ranges.emplace_back(begin, end);
begin = end;
}
return ranges;
}
void FoliageComponent::UpdateFoliageCullingData(
const std::optional<math::bounding_frustum>& cameraFrustum)
{
if (m_foliageTypes.empty()) return;
const size_t count = m_foliageInstances.size();
if (count == 0) return;
auto process_range = [&](size_t begin, size_t end)
{
for (size_t i = begin; i < end; ++i)
{
if (i >= m_foliageInstances.size()) return;
auto& foliage = m_foliageInstances[i];
// ��� üũ ����: >=
if (static_cast<size_t>(foliage.m_foliageTypeID) >= m_foliageTypes.size())
continue;
foliage.RebuildWorldMatrix();
const FoliageType& foliageType = m_foliageTypes[foliage.m_foliageTypeID];
Mesh* mesh = foliageType.m_mesh.get();
if (!mesh)
{
foliage.m_isCulled = true; // ���� �⺻��
continue;
}
if(SceneManagers->IsGameStart())
{
const math::aabb worldBounds = math::transform(
mesh->GetBoundingBox(),
foliage.m_worldMatrix);
foliage.m_isCulled = cameraFrustum.has_value() &&
!worldBounds.is_empty() &&
!math::intersects(*cameraFrustum, worldBounds);
}
else
{
foliage.m_isCulled = false;
}
}
};
auto ranges = DivideRangeAuto(m_foliageInstances.size());
std::vector<std::future<void>> tasks;
tasks.reserve(ranges.size());
for (auto& [begin, end] : ranges)
{
tasks.emplace_back(std::async(std::launch::async, process_range, begin, end));
}
// �Ϸ� ���
for (auto& f : tasks)
{
if (f.valid()) f.get();
}
}
void FoliageComponent::OnDeserialized()
{
// CT6-d: 구 ComponentFactory 분기 이동 — m_foliageAssetGuid는 반영 멤버.
if (m_foliageAssetGuid == nullFileGuid)
{
Debug->LogError("FoliageComponent is missing m_foliageAssetGuid");
return;
}
LoadFoliageAsset(m_foliageAssetGuid);
auto& types = const_cast<std::vector<FoliageType>&>(GetFoliageTypes());
for (auto& type : types)
{
if (type.m_modelName.empty())
continue;
std::shared_ptr<Model> model;
std::array<std::string, 5> exts{ ".fbx", ".gltf", ".glb", ".obj", ".asset" };
for (const auto& ext : exts)
{
auto path = PathFinder::Relative("Models\\" + type.m_modelName + ext);
if (std::filesystem::exists(path))
{
model = DataSystems->LoadCachedModelShared(path.string());
break;
}
}
if (!model)
{
Debug->LogError("Failed to load model for FoliageType: " + type.m_modelName);
continue;
}
type.m_mesh = model->GetMeshShared(0);
type.m_material = model->GetMaterialShared(0);
}
SetEnabled(true); // 구 분기 말미의 강제 활성 보존
}