-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTangentGeneration.cpp
More file actions
400 lines (355 loc) · 17.4 KB
/
Copy pathTangentGeneration.cpp
File metadata and controls
400 lines (355 loc) · 17.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
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
#include "TangentGeneration.h"
#include "mikktspace.h"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <execution>
#include <unordered_map>
#include <utility>
#include <vector>
namespace experiment::importer
{
namespace
{
// 이름이 다른 TU 의 동류 헬퍼와 겹치면 안 된다 — 유니티 빌드가 두 TU 를
// 합치면 같은 익명 네임스페이스로 병합돼 재정의가 된다.
struct TangentWorkspace final
{
const ImportedMesh* mesh{};
const std::vector<math::vector2>* coordinates{};
// 코너 c(= 면*3 + 정점) 의 결과. mikktspace 가 여기 채운다.
std::vector<math::vector4> cornerTangents{};
[[nodiscard]] std::size_t FaceCount() const noexcept
{
return mesh->indices.size() / 3;
}
[[nodiscard]] std::uint32_t VertexOf(int face, int vert) const noexcept
{
return mesh->indices[static_cast<std::size_t>(face) * 3
+ static_cast<std::size_t>(vert)];
}
};
[[nodiscard]] TangentWorkspace& Workspace(const SMikkTSpaceContext* context)
{
return *static_cast<TangentWorkspace*>(context->m_pUserData);
}
int MikkGetNumFaces(const SMikkTSpaceContext* context)
{
return static_cast<int>(Workspace(context).FaceCount());
}
int MikkGetNumVerticesOfFace(const SMikkTSpaceContext*, const int)
{
return 3; // 이 패스는 삼각형만 받는다(호출 전에 검사한다).
}
void MikkGetPosition(const SMikkTSpaceContext* context, float out[],
const int face, const int vert)
{
const TangentWorkspace& work = Workspace(context);
const math::vector3& p = work.mesh->streams.positions[work.VertexOf(face, vert)];
out[0] = p.x; out[1] = p.y; out[2] = p.z;
}
void MikkGetNormal(const SMikkTSpaceContext* context, float out[],
const int face, const int vert)
{
const TangentWorkspace& work = Workspace(context);
const math::vector3& n = work.mesh->streams.normals[work.VertexOf(face, vert)];
out[0] = n.x; out[1] = n.y; out[2] = n.z;
}
void MikkGetTexCoord(const SMikkTSpaceContext* context, float out[],
const int face, const int vert)
{
const TangentWorkspace& work = Workspace(context);
const math::vector2& uv = (*work.coordinates)[work.VertexOf(face, vert)];
out[0] = uv.x; out[1] = uv.y;
}
void MikkSetTSpaceBasic(const SMikkTSpaceContext* context,
const float tangent[], const float sign, const int face, const int vert)
{
TangentWorkspace& work = Workspace(context);
const std::size_t corner = static_cast<std::size_t>(face) * 3
+ static_cast<std::size_t>(vert);
// w 는 handedness. bitangent = w * cross(normal, tangent) 규약이며
// SceneToModelDraft 가 같은 규약으로 bitangent 를 푼다.
work.cornerTangents[corner] = { tangent[0], tangent[1], tangent[2], sign };
}
// ── 재용접 ──────────────────────────────────────────────────────
// 키는 (원본 정점, 탄젠트 4성분의 비트값)이다. mikktspace 가 한 그룹으로
// 묶은 코너들에는 **같은 값을 써 넣으므로** 정확 비교로 충분하다.
// epsilon 을 두면 붙이면 안 되는 이음매를 붙일 위험이 생긴다.
struct WeldKey final
{
std::uint32_t vertex{};
std::uint32_t bits[4]{};
[[nodiscard]] bool operator==(const WeldKey& other) const noexcept
{
return vertex == other.vertex
&& bits[0] == other.bits[0] && bits[1] == other.bits[1]
&& bits[2] == other.bits[2] && bits[3] == other.bits[3];
}
};
struct WeldKeyHash final
{
[[nodiscard]] std::size_t operator()(const WeldKey& key) const noexcept
{
std::size_t hash = key.vertex;
for (const std::uint32_t bit : key.bits)
{
hash ^= static_cast<std::size_t>(bit) + 0x9e3779b97f4a7c15ULL
+ (hash << 6) + (hash >> 2);
}
return hash;
}
};
[[nodiscard]] std::uint32_t FloatBits(float value) noexcept
{
std::uint32_t bits = 0;
std::memcpy(&bits, &value, sizeof(bits));
// -0.0 과 +0.0 은 같은 값으로 취급한다. 부호만 다른 0 이 정점을
// 쓸데없이 쪼개면 재용접이 제 일을 못 한다.
if (bits == 0x80000000u) bits = 0u;
return bits;
}
[[nodiscard]] WeldKey MakeWeldKey(std::uint32_t vertex, const math::vector4& t) noexcept
{
WeldKey key;
key.vertex = vertex;
key.bits[0] = FloatBits(t.x);
key.bits[1] = FloatBits(t.y);
key.bits[2] = FloatBits(t.z);
key.bits[3] = FloatBits(t.w);
return key;
}
// 원본 정점 하나를 새 스트림 끝에 복사한다. 비어 있는 스트림은 비운 채로
// 둔다 — "속성 없음"을 센티널이 아니라 빈 스트림으로 표현하는 규약이다.
//
// ★ 스트림을 손으로 나열하지 않는다(V1). 목록의 정본은
// VertexStreams::ValueStreams() 하나이고, 새 스트림은 자동으로 따라온다.
void AppendVertex(const VertexStreams& source, std::uint32_t vertex,
const math::vector4& tangent, VertexStreams& out)
{
// tangents — 이 패스가 직접 채운다(mikktspace 결과, 아래 push_back).
AppendValueStreams(source, vertex, out, &VertexStreams::tangents);
out.tangents.push_back(tangent);
AppendSkin(source, vertex, out);
}
}
bool GenerateTangents(ImportedMesh& mesh, const std::string& context,
ImportNoteSink& notes, TangentGenerationStats& stats, std::uint32_t uvSet)
{
using Clock = std::chrono::steady_clock;
const auto elapsedMs = [](Clock::time_point from) {
return std::chrono::duration<double, std::milli>(
Clock::now() - from).count();
};
VertexStreams& streams = mesh.streams;
if (!streams.tangents.empty()) return false; // 이미 있다 — 손대지 않는다
const std::size_t vertexCount = streams.VertexCount();
if (vertexCount == 0 || mesh.indices.empty())
{
return false;
}
if (streams.normals.size() != vertexCount)
{
notes.Warn(ImportNoteCode::MissingVertexAttribute, context,
"법선이 없어 탄젠트를 생성할 수 없다 — 법선 생성이 먼저다.");
return false;
}
const auto& coordinates = uvSet == 1 ? streams.uv1 : streams.uv0;
if (uvSet > 1 || coordinates.size() != vertexCount)
{
notes.Warn(ImportNoteCode::MissingVertexAttribute, context,
"선택된 UV가 없어 탄젠트를 생성할 수 없다 — 탄젠트는 UV 로 정의된다.");
return false;
}
if (mesh.indices.size() % 3 != 0)
{
notes.Warn(ImportNoteCode::InvalidVertexStreams, context,
"인덱스가 삼각형 배수가 아니라 탄젠트 생성을 건너뛴다.");
return false;
}
TangentWorkspace work;
work.mesh = &mesh;
work.coordinates = &coordinates;
work.cornerTangents.assign(mesh.indices.size(), math::vector4{});
SMikkTSpaceInterface interface_{};
interface_.m_getNumFaces = &MikkGetNumFaces;
interface_.m_getNumVerticesOfFace = &MikkGetNumVerticesOfFace;
interface_.m_getPosition = &MikkGetPosition;
interface_.m_getNormal = &MikkGetNormal;
interface_.m_getTexCoord = &MikkGetTexCoord;
interface_.m_setTSpaceBasic = &MikkSetTSpaceBasic;
SMikkTSpaceContext mikkContext{};
mikkContext.m_pInterface = &interface_;
mikkContext.m_pUserData = &work;
const auto mikkBegin = Clock::now();
const tbool mikkOk = genTangSpaceDefault(&mikkContext);
stats.mikktspaceMs += elapsedMs(mikkBegin);
if (mikkOk == 0)
{
notes.Warn(ImportNoteCode::MissingVertexAttribute, context,
"mikktspace 가 탄젠트 생성에 실패했다 — 탄젠트 없이 진행한다.");
return false;
}
// ── 법선 직교화 ──────────────────────────────────────────────────
// mikktspace 는 퇴화 삼각형의 코너에 **이웃의 탄젠트 공간을 물려준다**
// (헤더가 명시한 동작). 물려받은 탄젠트는 이 정점의 법선과 직교하지
// 않아 TBN 이 찌그러진다 — 실측: Gunner 코너 309/31470, 최대 |dot| 0.98.
// legacy(Assimp CalcTangentSpace)는 재직교화를 하므로 0건이었다.
//
// 직교 성분만 남긴다. **이미 직교인 코너에는 항등 연산**이라 정상
// 데이터에서는 mikktspace 출력이 한 비트도 바뀌지 않고, 퇴화 코너만
// 바로잡힌다(Suzanne 은 보정 0건으로 실측 확인).
const auto orthoBegin = Clock::now();
std::size_t reorthogonalized = 0;
for (std::size_t corner = 0; corner < mesh.indices.size(); ++corner)
{
const math::vector3& rawNormal = streams.normals[mesh.indices[corner]];
const float normalLength = std::sqrt(rawNormal.x * rawNormal.x
+ rawNormal.y * rawNormal.y + rawNormal.z * rawNormal.z);
if (normalLength <= 1e-6f) continue; // 법선이 없으면 손댈 근거가 없다
const math::vector3 n{ rawNormal.x / normalLength,
rawNormal.y / normalLength, rawNormal.z / normalLength };
math::vector4& t = work.cornerTangents[corner];
const float projection = n.x * t.x + n.y * t.y + n.z * t.z;
const float before = std::sqrt(t.x * t.x + t.y * t.y + t.z * t.z);
if (before <= 1e-6f) continue;
if (std::abs(projection) / before <= 1e-4f) continue; // 이미 직교
math::vector3 orthogonal{ t.x - n.x * projection,
t.y - n.y * projection, t.z - n.z * projection };
float length = std::sqrt(orthogonal.x * orthogonal.x
+ orthogonal.y * orthogonal.y + orthogonal.z * orthogonal.z);
if (length <= 1e-6f)
{
// 탄젠트가 법선과 완전히 평행이라 투영하면 아무것도 남지 않는다.
// 방향을 지어낼 근거가 없으므로 법선에 수직인 임의 축을 쓴다.
const math::vector3 axis = std::abs(n.x) < 0.9f
? math::vector3{ 1.0f, 0.0f, 0.0f } : math::vector3{ 0.0f, 1.0f, 0.0f };
orthogonal = { axis.y * n.z - axis.z * n.y,
axis.z * n.x - axis.x * n.z, axis.x * n.y - axis.y * n.x };
length = std::sqrt(orthogonal.x * orthogonal.x
+ orthogonal.y * orthogonal.y + orthogonal.z * orthogonal.z);
if (length <= 1e-6f) continue;
}
t.x = orthogonal.x / length;
t.y = orthogonal.y / length;
t.z = orthogonal.z / length;
++reorthogonalized;
}
stats.reorthogonalizeMs += elapsedMs(orthoBegin);
if (reorthogonalized > 0)
{
notes.Info(ImportNoteCode::MissingVertexAttribute, context,
"퇴화 삼각형이 이웃 탄젠트를 물려받아 법선과 어긋난 코너 "
+ std::to_string(reorthogonalized) + "/"
+ std::to_string(mesh.indices.size()) + "개를 재직교화했다.");
}
// ★ 여기서부터가 규약의 핵심이다. 코너 결과를 기존 인덱스에 그대로
// 써 넣으면 이음매에서 마지막 면이 이겨 탄젠트가 뭉개진다.
const auto weldBegin = Clock::now();
VertexStreams welded;
welded.positions.reserve(vertexCount);
welded.tangents.reserve(vertexCount);
if (streams.HasSkin())
{
welded.influenceOffsets.push_back(0);
welded.influences.reserve(streams.influences.size());
}
std::unordered_map<WeldKey, std::uint32_t, WeldKeyHash> lookup;
lookup.reserve(vertexCount * 2);
std::vector<std::uint32_t> newIndices;
newIndices.reserve(mesh.indices.size());
for (std::size_t corner = 0; corner < mesh.indices.size(); ++corner)
{
const std::uint32_t original = mesh.indices[corner];
const math::vector4& tangent = work.cornerTangents[corner];
const WeldKey key = MakeWeldKey(original, tangent);
const auto found = lookup.find(key);
if (found != lookup.end())
{
newIndices.push_back(found->second);
continue;
}
const auto fresh = static_cast<std::uint32_t>(welded.positions.size());
AppendVertex(streams, original, tangent, welded);
lookup.emplace(key, fresh);
newIndices.push_back(fresh);
}
if (welded.positions.size() > vertexCount)
{
notes.Info(ImportNoteCode::MissingVertexAttribute, context,
"탄젠트 이음매 때문에 정점 "
+ std::to_string(welded.positions.size() - vertexCount)
+ "개가 분리됐다(mikktspace 규약 — 기존 인덱스 재사용 금지).");
}
streams = std::move(welded);
mesh.indices = std::move(newIndices);
stats.weldMs += elapsedMs(weldBegin);
return true;
}
TangentGenerationStats GenerateMissingTangents(ImportedScene& scene,
const ImportOptions& options, ImportNoteSink& notes)
{
TangentGenerationStats stats;
if (!options.generateMissingTangents || scene.meshes.empty()) return stats;
// ★ 메시 단위 병렬. 실측에서 이 패스가 임포트의 60% 안팎이고 그 중
// 84~100% 가 mikktspace 안이었다(Gunner 15.4/18.3ms). 알고리즘은
// 원본 무수정 규약이라 손댈 수 없으므로 남은 지렛대가 이것이다.
// 원본 헤더가 genTangSpaceDefault 를 "thread safe" 로 명시하고,
// 메시마다 컨텍스트·작업 공간·출력이 완전히 분리된다.
//
// ★ 결과는 결정론적이어야 한다. 노트·통계를 공유 객체에 바로 쓰면
// 스레드 순서에 따라 로그가 뒤바뀌므로, 메시별로 따로 모아
// **인덱스 순서대로** 합친다.
struct MeshOutcome final
{
bool generated{};
std::size_t before{};
std::size_t after{};
ImportNoteSink notes{};
TangentGenerationStats stats{};
};
std::vector<MeshOutcome> outcomes(scene.meshes.size());
std::vector<std::size_t> order(scene.meshes.size());
for (std::size_t i = 0; i < order.size(); ++i) order[i] = i;
const auto runOne = [&](std::size_t i)
{
ImportedMesh& mesh = scene.meshes[i];
MeshOutcome& outcome = outcomes[i];
outcome.before = mesh.streams.VertexCount();
const uint32_t uvSet = IsInRange(mesh.material, scene.materials.size())
? scene.materials[mesh.material.Value()].normal.uvSet : 0;
outcome.generated = GenerateTangents(mesh,
"meshes[" + std::to_string(i) + "]", outcome.notes, outcome.stats, uvSet);
outcome.after = outcome.generated
? mesh.streams.VertexCount() : outcome.before;
};
// 메시가 하나뿐이면 병렬화가 이득이 없고 스케줄링 비용만 든다.
if (scene.meshes.size() == 1)
{
runOne(0);
}
else
{
std::for_each(std::execution::par, order.begin(), order.end(), runOne);
}
for (const MeshOutcome& outcome : outcomes)
{
notes.Absorb(outcome.notes.View().empty()
? std::vector<ImportNote>{}
: std::vector<ImportNote>(outcome.notes.View().begin(),
outcome.notes.View().end()));
stats.verticesBefore += outcome.before;
stats.verticesAfter += outcome.after;
if (outcome.generated) ++stats.meshesProcessed;
else ++stats.meshesSkipped;
// 구간 시간은 스레드마다 겹쳐 돌므로 **합이 벽시계보다 크다.**
// 어디에 쓰였는지 보는 용도이지 경과 시간이 아니다.
stats.mikktspaceMs += outcome.stats.mikktspaceMs;
stats.reorthogonalizeMs += outcome.stats.reorthogonalizeMs;
stats.weldMs += outcome.stats.weldMs;
}
return stats;
}
}