载入中...
搜索中...
未找到
ModelNormals.cpp
浏览该文件的文档.
1#include "model3d/ModelData.h"
2
3#include "common/Diagnostic.h"
4#include "common/Result.h"
5#include "image/ImageData.h"
6
7#include <assimp/mesh.h>
8#include <assimp/vector3.h>
9
10#include <algorithm>
11#include <cmath>
12#include <memory>
13#include <string>
14#include <string_view>
15#include <utility>
16
17namespace eve {
18namespace model3d {
19namespace {
20
21eve::Diagnostic invalidArg(std::string message, std::string path) {
23}
24
25eve::Diagnostic unsupported(std::string message, std::string path) {
27}
28
29aiVector3D unitOrUp(float x, float y, float z) {
30 const float length = std::sqrt(x * x + y * y + z * z);
31 if (!std::isfinite(length) || length <= 1e-12f)
32 return aiVector3D(0.f, 0.f, 1.f);
33 return aiVector3D(x / length, y / length, z / length);
34}
35
36bool ensureNormals(aiMesh *mesh) {
37 if (!mesh || mesh->mNumVertices == 0 || !mesh->mVertices)
38 return false;
39 if (mesh->mNormals)
40 return true;
41 mesh->mNormals = new aiVector3D[mesh->mNumVertices];
42 for (unsigned i = 0; i < mesh->mNumVertices; ++i)
43 mesh->mNormals[i] = aiVector3D(0.f, 0.f, 1.f);
44 return true;
45}
46
47bool meshAabbCenter(const aiMesh *mesh, aiVector3D *out) {
48 if (!mesh || mesh->mNumVertices == 0 || !mesh->mVertices)
49 return false;
50 aiVector3D lo = mesh->mVertices[0];
51 aiVector3D hi = mesh->mVertices[0];
52 for (unsigned i = 1; i < mesh->mNumVertices; ++i) {
53 const aiVector3D &p = mesh->mVertices[i];
54 lo.x = std::min(lo.x, p.x);
55 lo.y = std::min(lo.y, p.y);
56 lo.z = std::min(lo.z, p.z);
57 hi.x = std::max(hi.x, p.x);
58 hi.y = std::max(hi.y, p.y);
59 hi.z = std::max(hi.z, p.z);
60 }
61 *out = aiVector3D((lo.x + hi.x) * 0.5f, (lo.y + hi.y) * 0.5f, (lo.z + hi.z) * 0.5f);
62 return true;
63}
64
65void applyRadial(aiMesh *mesh, const aiVector3D &origin) {
66 for (unsigned i = 0; i < mesh->mNumVertices; ++i) {
67 const aiVector3D &p = mesh->mVertices[i];
68 mesh->mNormals[i] = unitOrUp(p.x - origin.x, p.y - origin.y, p.z - origin.z);
69 }
70}
71
72struct Vec2 {
73 float x = 0.f;
74 float y = 0.f;
75};
76
77struct Vec3 {
78 float x = 0.f;
79 float y = 0.f;
80 float z = 0.f;
81};
82
83Vec3 add(const Vec3 &a, const Vec3 &b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
84Vec3 sub(const Vec3 &a, const Vec3 &b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
85Vec3 scale(const Vec3 &a, float s) { return {a.x * s, a.y * s, a.z * s}; }
86float dot3(const Vec3 &a, const Vec3 &b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
87Vec3 cross3(const Vec3 &a, const Vec3 &b) {
88 return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x};
89}
90Vec3 normalize3(const Vec3 &a) {
91 const aiVector3D n = unitOrUp(a.x, a.y, a.z);
92 return {n.x, n.y, n.z};
93}
94
95bool barycentric2(const Vec2 &p, const Vec2 &a, const Vec2 &b, const Vec2 &c, float *wa, float *wb,
96 float *wc) {
97 const float den = (b.y - c.y) * (a.x - c.x) + (c.x - b.x) * (a.y - c.y);
98 if (!std::isfinite(den) || std::fabs(den) <= 1e-12f)
99 return false;
100 *wa = ((b.y - c.y) * (p.x - c.x) + (c.x - b.x) * (p.y - c.y)) / den;
101 *wb = ((c.y - a.y) * (p.x - c.x) + (a.x - c.x) * (p.y - c.y)) / den;
102 *wc = 1.f - *wa - *wb;
103 return true;
104}
105
106image::ImageData::Colorf encodeNormal(const Vec3 &n) {
108 c.r = std::clamp(n.x * 0.5f + 0.5f, 0.f, 1.f);
109 c.g = std::clamp(n.y * 0.5f + 0.5f, 0.f, 1.f);
110 c.b = std::clamp(n.z * 0.5f + 0.5f, 0.f, 1.f);
111 c.a = 1.f;
112 return c;
113}
114
115Vec3 toTangent(const Vec3 &objectNormal, const Vec3 &pos0, const Vec3 &pos1, const Vec3 &pos2,
116 const Vec2 &uv0, const Vec2 &uv1, const Vec2 &uv2) {
117 const Vec3 e1 = sub(pos1, pos0);
118 const Vec3 e2 = sub(pos2, pos0);
119 const float du1 = uv1.x - uv0.x;
120 const float dv1 = uv1.y - uv0.y;
121 const float du2 = uv2.x - uv0.x;
122 const float dv2 = uv2.y - uv0.y;
123 const float det = du1 * dv2 - du2 * dv1;
124 Vec3 geometric = normalize3(cross3(e1, e2));
125 if (dot3(geometric, objectNormal) < 0.f)
126 geometric = scale(geometric, -1.f);
127 Vec3 tangent;
128 Vec3 bitangent;
129 if (!std::isfinite(det) || std::fabs(det) <= 1e-12f) {
130 tangent = {1.f, 0.f, 0.f};
131 if (std::fabs(dot3(tangent, geometric)) > 0.9f)
132 tangent = {0.f, 1.f, 0.f};
133 tangent = normalize3(sub(tangent, scale(geometric, dot3(tangent, geometric))));
134 bitangent = normalize3(cross3(geometric, tangent));
135 } else {
136 const float inv = 1.f / det;
137 tangent = normalize3(add(scale(e1, dv2 * inv), scale(e2, -dv1 * inv)));
138 bitangent = normalize3(add(scale(e1, -du2 * inv), scale(e2, du1 * inv)));
139 tangent = normalize3(sub(tangent, scale(geometric, dot3(tangent, geometric))));
140 const Vec3 reconstructed = cross3(geometric, tangent);
141 if (dot3(reconstructed, bitangent) < 0.f)
142 bitangent = scale(reconstructed, -1.f);
143 else
144 bitangent = reconstructed;
145 }
146 return {dot3(objectNormal, tangent), dot3(objectNormal, bitangent),
147 dot3(objectNormal, geometric)};
148}
149
150} // namespace
151
152eve::Result<void> ModelData::setVertexNormal(int meshIndex, int vertexIndex, float x, float y,
153 float z) {
154 aiMesh *mesh = meshAtMutable(meshIndex);
155 if (!mesh || vertexIndex < 0 || static_cast<unsigned>(vertexIndex) >= mesh->mNumVertices)
157 invalidArg("invalid mesh or vertex index", "model3d.setVertexNormal"));
158 if (!ensureNormals(mesh))
160 invalidArg("mesh has no vertices", "model3d.setVertexNormal"));
161 mesh->mNormals[vertexIndex] = unitOrUp(x, y, z);
163}
164
165eve::Result<void> ModelData::applyVertexNormals(int meshIndex, std::string_view kind) {
166 aiMesh *mesh = meshAtMutable(meshIndex);
167 if (!mesh)
169 invalidArg("invalid mesh index", "model3d.applyVertexNormals"));
170 aiVector3D origin;
171 if (!meshAabbCenter(mesh, &origin))
173 invalidArg("mesh has no vertices", "model3d.applyVertexNormals"));
174 return applyVertexNormalsFrom(meshIndex, kind, origin.x, origin.y, origin.z);
175}
176
178 float originX, float originY, float originZ) {
179 aiMesh *mesh = meshAtMutable(meshIndex);
180 if (!mesh)
182 invalidArg("invalid mesh index", "model3d.applyVertexNormalsFrom"));
183 if (kind != "radial")
185 unsupported("unknown vertex-normal kind", "model3d.applyVertexNormalsFrom.kind"));
186 if (!ensureNormals(mesh))
188 invalidArg("mesh has no vertices", "model3d.applyVertexNormalsFrom"));
189 applyRadial(mesh, aiVector3D(originX, originY, originZ));
191}
192
194 int meshIndex, int width, int height, int uvChannel, std::string_view space) const {
195 using ImagePtr = std::unique_ptr<image::ImageData>;
196 const aiMesh *mesh = meshAt(meshIndex);
197 if (!mesh)
199 invalidArg("invalid mesh index", "model3d.bakeNormalMap"));
200 if (width <= 0 || height <= 0)
202 invalidArg("normal map size must be positive", "model3d.bakeNormalMap.size"));
203 if (space != "tangent" && space != "object")
205 unsupported("space must be \"tangent\" or \"object\"", "model3d.bakeNormalMap.space"));
206 if (!mesh->HasNormals())
207 return eve::Result<ImagePtr>::failure(unsupported(
208 "mesh has no vertex normals; apply or set them before baking",
209 "model3d.bakeNormalMap.normals"));
210 if (uvChannel < 0 || uvChannel >= AI_MAX_NUMBER_OF_TEXTURECOORDS ||
211 !mesh->HasTextureCoords(static_cast<unsigned>(uvChannel)))
213 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "requested UV channel is not present",
214 "model3d.bakeNormalMap.channel"));
215
216 for (unsigned f = 0; f < mesh->mNumFaces; ++f) {
217 if (mesh->mFaces[f].mNumIndices != 3)
218 return eve::Result<ImagePtr>::failure(unsupported(
219 "normal-map baking requires triangulated faces", "model3d.bakeNormalMap.triangle"));
220 }
221
222 auto image = std::make_unique<image::ImageData>(width, height, "RGBA8");
224 fill.r = 0.5f;
225 fill.g = 0.5f;
226 fill.b = 1.f;
227 fill.a = 1.f;
228 for (int y = 0; y < height; ++y)
229 for (int x = 0; x < width; ++x)
230 image->setPixel(x, y, fill);
231
232 const float widthF = static_cast<float>(width);
233 const float heightF = static_cast<float>(height);
234 const bool tangentSpace = space == "tangent";
235
236 for (unsigned f = 0; f < mesh->mNumFaces; ++f) {
237 const aiFace &face = mesh->mFaces[f];
238 const unsigned i0 = face.mIndices[0];
239 const unsigned i1 = face.mIndices[1];
240 const unsigned i2 = face.mIndices[2];
241 const Vec3 p0{mesh->mVertices[i0].x, mesh->mVertices[i0].y, mesh->mVertices[i0].z};
242 const Vec3 p1{mesh->mVertices[i1].x, mesh->mVertices[i1].y, mesh->mVertices[i1].z};
243 const Vec3 p2{mesh->mVertices[i2].x, mesh->mVertices[i2].y, mesh->mVertices[i2].z};
244 const Vec3 n0{mesh->mNormals[i0].x, mesh->mNormals[i0].y, mesh->mNormals[i0].z};
245 const Vec3 n1{mesh->mNormals[i1].x, mesh->mNormals[i1].y, mesh->mNormals[i1].z};
246 const Vec3 n2{mesh->mNormals[i2].x, mesh->mNormals[i2].y, mesh->mNormals[i2].z};
247 const aiVector3D &t0 = mesh->mTextureCoords[uvChannel][i0];
248 const aiVector3D &t1 = mesh->mTextureCoords[uvChannel][i1];
249 const aiVector3D &t2 = mesh->mTextureCoords[uvChannel][i2];
250 const Vec2 uv0{t0.x, t0.y};
251 const Vec2 uv1{t1.x, t1.y};
252 const Vec2 uv2{t2.x, t2.y};
253 const Vec2 pix0{uv0.x * widthF, (1.f - uv0.y) * heightF};
254 const Vec2 pix1{uv1.x * widthF, (1.f - uv1.y) * heightF};
255 const Vec2 pix2{uv2.x * widthF, (1.f - uv2.y) * heightF};
256
257 const int minX = std::max(0, static_cast<int>(std::floor(std::min({pix0.x, pix1.x, pix2.x}))));
258 const int maxX =
259 std::min(width - 1, static_cast<int>(std::ceil(std::max({pix0.x, pix1.x, pix2.x}))));
260 const int minY = std::max(0, static_cast<int>(std::floor(std::min({pix0.y, pix1.y, pix2.y}))));
261 const int maxY =
262 std::min(height - 1, static_cast<int>(std::ceil(std::max({pix0.y, pix1.y, pix2.y}))));
263
264 for (int y = minY; y <= maxY; ++y) {
265 for (int x = minX; x <= maxX; ++x) {
266 const Vec2 sample{static_cast<float>(x) + 0.5f, static_cast<float>(y) + 0.5f};
267 float wa = 0.f, wb = 0.f, wc = 0.f;
268 if (!barycentric2(sample, pix0, pix1, pix2, &wa, &wb, &wc))
269 continue;
270 constexpr float kEps = -1e-4f;
271 if (wa < kEps || wb < kEps || wc < kEps)
272 continue;
273 Vec3 object = normalize3(add(add(scale(n0, wa), scale(n1, wb)), scale(n2, wc)));
274 const Vec3 encoded =
275 tangentSpace ? toTangent(object, p0, p1, p2, uv0, uv1, uv2) : object;
276 image->setPixel(x, y, encodeNormal(encoded));
277 }
278 }
279 }
280
281 return eve::Result<ImagePtr>::success(std::move(image));
282}
283
284} // namespace model3d
285} // namespace eve
double z
double y
double x
const std::string & s
glm::vec4 p[6]
Stable, structured diagnostics shared by engine modules.
std::string message
vk::UniqueImage image
uint32_t i1
Definition Grass.cpp:61
uint32_t i2
Definition Grass.cpp:61
uint32_t i0
Definition Grass.cpp:61
glm::vec3 n
Definition Grass.cpp:63
std::int32_t c
std::uint32_t height
std::uint32_t width
float length
std::array< float, 3 > scale
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanMeshSettings mesh
glm::dvec3 origin
float f
std::string path
Definition PlayHost.cpp:111
Move-only, checked operation results for the common layer.
ScriptStructure out
std::string kind
Json object
A structured explanation of a failed, degraded, or noteworthy result.
Definition Diagnostic.h:94
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
medialoader::Colorf Colorf
Definition ImageData.h:41
eve::Result< void > applyVertexNormalsFrom(int meshIndex, std::string_view kind, float originX, float originY, float originZ)
Like applyVertexNormals, but "radial" uses an explicit origin.
eve::Result< void > applyVertexNormals(int meshIndex, std::string_view kind)
Replace every vertex normal on a mesh from a named procedure.
eve::Result< void > setVertexNormal(int meshIndex, int vertexIndex, float x, float y, float z)
Write one unit (or zero) object-space vertex normal. Allocates the normal stream when the mesh has po...
eve::Result< std::unique_ptr< image::ImageData > > bakeNormalMap(int meshIndex, int width, int height, int uvChannel=0, std::string_view space="tangent") const
Rasterize current object-space vertex normals into an RGBA8 normal map.
void cross3(float ax, float ay, float az, float bx, float by, float bz, float &x, float &y, float &z)
ForceVector add(ForceVector a, ForceVector b)
Definition ForceMath.h:13
Vec3 sub(Vec3 a, Vec3 b)
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16