28 int32_t texcoord = -1;
36int64_t parseIndex(
const std::string& field,
const char* what,
size_t lineNumber) {
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);
45 consumed != field.size(),
46 "OBJ line {}: {} index '{}' has trailing characters",
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",
66 return static_cast<int32_t
>(resolved);
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);
78 corner.vertex = resolveIndex(
79 parseIndex(vertexField,
"vertex", lineNumber), numVertices,
"vertex", lineNumber);
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);
87 if (!texcoordField.empty()) {
88 corner.texcoord = resolveIndex(
89 parseIndex(texcoordField,
"texture coordinate", lineNumber),
98uint8_t toByteColor(
float v) {
99 return static_cast<uint8_t
>(std::lround(std::clamp(v, 0.0f, 1.0f) * 255.0f));
102Mesh parseObj(std::istream& stream) {
104 std::vector<Eigen::Vector2f> texcoords;
105 std::vector<Eigen::Vector3i> texcoordFaces;
106 std::vector<Corner> corners;
110 bool allFacesTextured =
true;
111 bool anyFaceTextured =
false;
114 size_t lineNumber = 0;
115 while (std::getline(stream, line)) {
117 if (
const size_t comment = line.find(
'#'); comment != std::string::npos) {
118 line.resize(comment);
121 std::istringstream fields(line);
123 if (!(fields >> token)) {
128 std::vector<float> values;
130 while (fields >> value) {
131 values.push_back(value);
135 "OBJ line {}: vertex needs at least 3 coordinates, got {}",
138 mesh.vertices.emplace_back(values[0], values[1], values[2]);
141 if (values.size() >= 6) {
142 mesh.colors.emplace_back(
143 toByteColor(values[3]), toByteColor(values[4]), toByteColor(values[5]));
145 }
else if (token ==
"vt") {
150 "OBJ line {}: texture coordinate needs at least two floats",
152 texcoords.emplace_back(u, v);
153 }
else if (token ==
"f") {
155 std::string cornerToken;
156 while (fields >> cornerToken) {
158 parseCorner(cornerToken, mesh.vertices.size(), texcoords.size(), lineNumber));
160 if (corners.size() < 3) {
161 MT_LOGW(
"OBJ line {}: skipping face with {} corners", lineNumber, corners.size());
165 const bool textured =
166 std::ranges::all_of(corners, [](
const Corner& c) {
return c.texcoord >= 0; });
167 anyFaceTextured |= textured;
168 allFacesTextured &= textured;
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));
174 mesh.polyTexcoordFaces.push_back(
static_cast<uint32_t
>(c.texcoord));
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);
181 texcoordFaces.emplace_back(
182 corners[0].texcoord, corners[i - 1].texcoord, corners[i].texcoord);
189 MT_THROW_IF(mesh.vertices.empty(),
"OBJ file contains no vertices");
190 MT_THROW_IF(mesh.faces.empty(),
"OBJ file contains no faces");
192 if (anyFaceTextured && allFacesTextured) {
193 mesh.texcoords = std::move(texcoords);
194 mesh.texcoord_faces = std::move(texcoordFaces);
196 if (anyFaceTextured) {
198 "OBJ file texture-maps only some of its {} faces; loading it untextured",
201 mesh.polyTexcoordFaces.clear();
204 if (mesh.colors.size() != mesh.vertices.size()) {
205 if (!mesh.colors.empty()) {
207 "OBJ file gives colours for {} of {} vertices; discarding them",
209 mesh.vertices.size());
211 mesh.colors.assign(mesh.vertices.size(), Vector3b::Constant(255));
213 mesh.confidence.assign(mesh.vertices.size(), 1.0f);
214 mesh.updateNormals();
221 std::ifstream file(filepath);
222 MT_THROW_IF(!file.is_open(),
"Failed to open OBJ file: {}", filepath.string());
223 return parseObj(file);
227 std::istringstream stream(std::string(
reinterpret_cast<const char*
>(bytes.data()), bytes.size()));
228 return parseObj(stream);
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Mesh loadObj(const filesystem::path &filepath)
Loads a mesh from a Wavefront OBJ file.