Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
obj_io.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
9
11#include "momentum/common/log.h"
12
13#include <algorithm>
14#include <cmath>
15#include <exception>
16#include <fstream>
17#include <sstream>
18#include <string>
19#include <vector>
20
21namespace momentum {
22
23namespace {
24
26struct Corner {
27 int32_t vertex = -1;
28 int32_t texcoord = -1;
29};
30
36int64_t parseIndex(const std::string& field, const char* what, size_t lineNumber) {
37 size_t consumed = 0;
38 int64_t value = 0;
39 try {
40 value = std::stoll(field, &consumed);
41 } catch (const std::exception&) {
42 MT_THROW("OBJ line {}: {} index '{}' is not a valid integer", lineNumber, what, field);
43 }
45 consumed != field.size(),
46 "OBJ line {}: {} index '{}' has trailing characters",
47 lineNumber,
48 what,
49 field);
50 return value;
51}
52
55int32_t resolveIndex(int64_t raw, size_t count, const char* what, size_t lineNumber) {
57 raw == 0, "OBJ line {}: {} index 0 is invalid, OBJ indices are 1-based", lineNumber, what);
58 const int64_t resolved = (raw > 0) ? (raw - 1) : (static_cast<int64_t>(count) + raw);
60 resolved < 0 || resolved >= static_cast<int64_t>(count),
61 "OBJ line {}: {} index {} is out of range, {} have been read",
62 lineNumber,
63 what,
64 raw,
65 count);
66 return static_cast<int32_t>(resolved);
67}
68
70Corner
71parseCorner(const std::string& token, size_t numVertices, size_t numTexcoords, size_t lineNumber) {
72 const size_t firstSlash = token.find('/');
73 const std::string vertexField = token.substr(0, firstSlash);
75 vertexField.empty(), "OBJ line {}: face corner '{}' has no vertex index", lineNumber, token);
76
77 Corner corner;
78 corner.vertex = resolveIndex(
79 parseIndex(vertexField, "vertex", lineNumber), numVertices, "vertex", lineNumber);
80
81 if (firstSlash != std::string::npos) {
82 const size_t secondSlash = token.find('/', firstSlash + 1);
83 const std::string texcoordField = (secondSlash == std::string::npos)
84 ? token.substr(firstSlash + 1)
85 : token.substr(firstSlash + 1, secondSlash - firstSlash - 1);
86 // Empty means the `v//vn` form: a normal index but no texture coordinate.
87 if (!texcoordField.empty()) {
88 corner.texcoord = resolveIndex(
89 parseIndex(texcoordField, "texture coordinate", lineNumber),
90 numTexcoords,
91 "texture coordinate",
92 lineNumber);
93 }
94 }
95 return corner;
96}
97
98uint8_t toByteColor(float v) {
99 return static_cast<uint8_t>(std::lround(std::clamp(v, 0.0f, 1.0f) * 255.0f));
100}
101
102Mesh parseObj(std::istream& stream) {
103 Mesh mesh;
104 std::vector<Eigen::Vector2f> texcoords;
105 std::vector<Eigen::Vector3i> texcoordFaces;
106 std::vector<Corner> corners;
107
108 // Texture coordinates are kept only if *every* face has them, since texcoord_faces has to
109 // stay index-aligned with faces.
110 bool allFacesTextured = true;
111 bool anyFaceTextured = false;
112
113 std::string line;
114 size_t lineNumber = 0;
115 while (std::getline(stream, line)) {
116 ++lineNumber;
117 if (const size_t comment = line.find('#'); comment != std::string::npos) {
118 line.resize(comment);
119 }
120
121 std::istringstream fields(line);
122 std::string token;
123 if (!(fields >> token)) {
124 continue;
125 }
126
127 if (token == "v") {
128 std::vector<float> values;
129 float value = 0.0f;
130 while (fields >> value) {
131 values.push_back(value);
132 }
134 values.size() < 3,
135 "OBJ line {}: vertex needs at least 3 coordinates, got {}",
136 lineNumber,
137 values.size());
138 mesh.vertices.emplace_back(values[0], values[1], values[2]);
139 // `v x y z r g b` -- the six-float form carries a vertex colour. Four floats is the
140 // rational `w` form instead, whose weight momentum has nowhere to put.
141 if (values.size() >= 6) {
142 mesh.colors.emplace_back(
143 toByteColor(values[3]), toByteColor(values[4]), toByteColor(values[5]));
144 }
145 } else if (token == "vt") {
146 float u = 0.0f;
147 float v = 0.0f;
149 !(fields >> u >> v),
150 "OBJ line {}: texture coordinate needs at least two floats",
151 lineNumber);
152 texcoords.emplace_back(u, v);
153 } else if (token == "f") {
154 corners.clear();
155 std::string cornerToken;
156 while (fields >> cornerToken) {
157 corners.push_back(
158 parseCorner(cornerToken, mesh.vertices.size(), texcoords.size(), lineNumber));
159 }
160 if (corners.size() < 3) {
161 MT_LOGW("OBJ line {}: skipping face with {} corners", lineNumber, corners.size());
162 continue;
163 }
164
165 const bool textured =
166 std::ranges::all_of(corners, [](const Corner& c) { return c.texcoord >= 0; });
167 anyFaceTextured |= textured;
168 allFacesTextured &= textured;
169
170 mesh.polyFaceSizes.push_back(static_cast<uint32_t>(corners.size()));
171 for (const Corner& c : corners) {
172 mesh.polyFaces.push_back(static_cast<uint32_t>(c.vertex));
173 if (textured) {
174 mesh.polyTexcoordFaces.push_back(static_cast<uint32_t>(c.texcoord));
175 }
176 }
177
178 for (size_t i = 2; i < corners.size(); ++i) {
179 mesh.faces.emplace_back(corners[0].vertex, corners[i - 1].vertex, corners[i].vertex);
180 if (textured) {
181 texcoordFaces.emplace_back(
182 corners[0].texcoord, corners[i - 1].texcoord, corners[i].texcoord);
183 }
184 }
185 }
186 // `vn`, `g`, `o`, `s`, `usemtl` and `mtllib` are deliberately ignored; see the header.
187 }
188
189 MT_THROW_IF(mesh.vertices.empty(), "OBJ file contains no vertices");
190 MT_THROW_IF(mesh.faces.empty(), "OBJ file contains no faces");
191
192 if (anyFaceTextured && allFacesTextured) {
193 mesh.texcoords = std::move(texcoords);
194 mesh.texcoord_faces = std::move(texcoordFaces);
195 } else {
196 if (anyFaceTextured) {
197 MT_LOGW(
198 "OBJ file texture-maps only some of its {} faces; loading it untextured",
199 mesh.faces.size());
200 }
201 mesh.polyTexcoordFaces.clear();
202 }
203
204 if (mesh.colors.size() != mesh.vertices.size()) {
205 if (!mesh.colors.empty()) {
206 MT_LOGW(
207 "OBJ file gives colours for {} of {} vertices; discarding them",
208 mesh.colors.size(),
209 mesh.vertices.size());
210 }
211 mesh.colors.assign(mesh.vertices.size(), Vector3b::Constant(255));
212 }
213 mesh.confidence.assign(mesh.vertices.size(), 1.0f);
214 mesh.updateNormals();
215 return mesh;
216}
217
218} // namespace
219
220Mesh loadObj(const filesystem::path& filepath) {
221 std::ifstream file(filepath);
222 MT_THROW_IF(!file.is_open(), "Failed to open OBJ file: {}", filepath.string());
223 return parseObj(file);
224}
225
226Mesh loadObj(std::span<const std::byte> bytes) {
227 std::istringstream stream(std::string(reinterpret_cast<const char*>(bytes.data()), bytes.size()));
228 return parseObj(stream);
229}
230
231} // namespace momentum
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
Definition exception.h:31
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Definition exception.h:55
#define MT_LOGW(...)
Definition log.h:180
MeshT< float > Mesh
Definition fwd.h:20
Mesh loadObj(const filesystem::path &filepath)
Loads a mesh from a Wavefront OBJ file.
Definition obj_io.cpp:220