Blender V5.3
obj_exporter.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <cstdio>
10#include <memory>
11#include <system_error>
12
14#include "DNA_curve_enums.h"
15#include "DNA_curve_types.h"
16#include "DNA_layer_types.h"
17#include "DNA_scene_types.h"
18
19#include "BKE_context.hh"
20#include "BKE_lib_id.hh"
21#include "BKE_report.hh"
22#include "BKE_scene.hh"
23
24#include "BLI_path_utils.hh"
25#include "BLI_string.hh"
26#include "BLI_task.hh"
27#include "BLI_vector.hh"
28
30
31#include "ED_object.hh"
32
33#include "obj_export_mesh.hh"
34#include "obj_export_nurbs.hh"
35#include "obj_exporter.hh"
36
38
39#include "CLG_log.h"
40
41namespace blender {
42
43static CLG_LogRef LOG = {"io.obj"};
44
45namespace io::obj {
46
48 const eEvaluationMode eval_mode,
49 Collection *collection)
50{
51 Scene *scene = CTX_data_scene(C);
52 Main *bmain = CTX_data_main(C);
53 ViewLayer *view_layer = CTX_data_view_layer(C);
54
55 /* If a collection was provided, use it. */
56 if (collection) {
57 depsgraph_ = DEG_graph_new(bmain, scene, view_layer, eval_mode);
58 needs_free_ = true;
59 DEG_graph_build_from_collection(depsgraph_, collection);
60 BKE_scene_graph_evaluated_ensure(depsgraph_, bmain);
61 }
62 else if (eval_mode == DAG_EVAL_RENDER) {
63 depsgraph_ = DEG_graph_new(bmain, scene, view_layer, eval_mode);
64 needs_free_ = true;
66 BKE_scene_graph_evaluated_ensure(depsgraph_, bmain);
67 }
68 else {
70 needs_free_ = false;
71 }
72}
73
75{
76 if (needs_free_) {
77 DEG_graph_free(depsgraph_);
78 }
79}
80
82{
83 return depsgraph_;
84}
85
90
91static void print_exception_error(const std::system_error &ex)
92{
93 CLOG_ERROR(&LOG, "[%s] %s", ex.code().category().name(), ex.what());
94}
95
96static bool is_curve_nurbs_compatible(const Nurb *nurb)
97{
98 while (nurb) {
99 if (nurb->type == CU_BEZIER || nurb->pntsv != 1) {
100 return false;
101 }
102 nurb = nurb->next;
103 }
104 return true;
105}
106
112std::pair<Vector<std::unique_ptr<OBJMesh>>, Vector<std::unique_ptr<IOBJCurve>>>
113filter_supported_objects(Depsgraph *depsgraph, const OBJExportParams &export_params)
114{
115 Vector<std::unique_ptr<OBJMesh>> r_exportable_meshes;
116 Vector<std::unique_ptr<IOBJCurve>> r_exportable_nurbs;
117 DEGObjectIterSettings deg_iter_settings{};
118 deg_iter_settings.depsgraph = depsgraph;
119 deg_iter_settings.flags = DEG_ITER_OBJECT_FLAG_LINKED_DIRECTLY |
122 DEG_OBJECT_ITER_BEGIN (&deg_iter_settings, object) {
123 if (export_params.export_selected_objects && !(object->base_flag & BASE_SELECTED)) {
124 continue;
125 }
126 switch (object->type) {
127 case OB_SURF:
128 /* Evaluated surface objects appear as mesh objects from the iterator. */
129 break;
130 case OB_MESH:
131 r_exportable_meshes.append(std::make_unique<OBJMesh>(depsgraph, export_params, object));
132 break;
133 case OB_CURVES_LEGACY: {
134 Curve *curve = id_cast<Curve *>(object->data);
135 Nurb *nurb{curve->nurb.first()};
136 if (!nurb) {
137 /* An empty curve. Not yet supported to export these as meshes. */
138 if (export_params.export_curves_as_nurbs) {
139 IOBJCurve *obj_curve = new OBJLegacyCurve(depsgraph, object);
140 r_exportable_nurbs.append(std::unique_ptr<IOBJCurve>(obj_curve));
141 }
142 break;
143 }
144 if (export_params.export_curves_as_nurbs && is_curve_nurbs_compatible(nurb)) {
145 /* Export in parameter form: control points. */
146 IOBJCurve *obj_curve = new OBJLegacyCurve(depsgraph, object);
147 r_exportable_nurbs.append(std::unique_ptr<IOBJCurve>(obj_curve));
148 }
149 else {
150 /* Export in mesh form: edges and vertices. */
151 r_exportable_meshes.append(std::make_unique<OBJMesh>(depsgraph, export_params, object));
152 }
153 break;
154 }
155 default:
156 /* Other object types are not supported. */
157 break;
158 }
159 }
161 return {std::move(r_exportable_meshes), std::move(r_exportable_nurbs)};
162}
163
164static void write_mesh_objects(const Span<std::unique_ptr<OBJMesh>> exportable_as_mesh,
165 OBJWriter &obj_writer,
166 MTLWriter *mtl_writer,
167 const OBJExportParams &export_params)
168{
169 /* Parallelization is over meshes/objects, which means
170 * we have to have the output text buffer for each object,
171 * and write them all into the file at the end. */
172 size_t count = exportable_as_mesh.size();
173 Array<FormatHandler> buffers(count);
174
175 /* Serial: gather material indices, ensure normals & edges. */
176 Vector<Vector<int>> mtlindices;
177 if (mtl_writer) {
178 if (export_params.export_materials) {
179 obj_writer.write_mtllib_name(mtl_writer->mtl_file_path());
180 }
181 mtlindices.reserve(count);
182 }
183 for (const auto &obj_mesh : exportable_as_mesh) {
184 OBJMesh &obj = *obj_mesh;
185 if (mtl_writer) {
186 mtlindices.append(mtl_writer->add_materials(obj));
187 }
188 }
189
190 /* Parallel over meshes: store normal coords & indices, uv coords and indices. */
191 threading::parallel_for(IndexRange(count), 1, [&](IndexRange range) {
192 for (const int i : range) {
193 OBJMesh &obj = *exportable_as_mesh[i];
194 if (export_params.export_normals) {
195 obj.store_normal_coords_and_indices();
196 }
197 if (export_params.export_uv) {
198 obj.store_uv_coords_and_indices();
199 }
200 }
201 });
202
203 /* Serial: calculate index offsets; these are sequentially added
204 * over all meshes, and requite normal/uv indices to be calculated. */
205 Vector<IndexOffsets> index_offsets;
206 index_offsets.reserve(count);
207 IndexOffsets offsets{0, 0, 0};
208 for (const auto &obj_mesh : exportable_as_mesh) {
209 OBJMesh &obj = *obj_mesh;
210 index_offsets.append(offsets);
211 offsets.vertex_offset += obj.tot_vertices();
212 offsets.uv_vertex_offset += obj.tot_uv_vertices();
213 offsets.normal_offset += obj.get_normal_coords().size();
214 }
215
216 /* Parallel over meshes: main result writing. */
217 threading::parallel_for(IndexRange(count), 1, [&](IndexRange range) {
218 for (const int i : range) {
219 OBJMesh &obj = *exportable_as_mesh[i];
220 auto &fh = buffers[i];
221
222 obj_writer.write_object_name(fh, obj);
223 obj_writer.write_vertex_coords(fh, obj, export_params.export_colors);
224
225 if (obj.tot_faces() > 0) {
226 if (export_params.export_smooth_groups) {
227 obj.calc_smooth_groups(export_params.smooth_groups_bitflags);
228 }
229 if (export_params.export_materials) {
230 obj.calc_face_order();
231 }
232 if (export_params.export_normals) {
233 obj_writer.write_normals(fh, obj);
234 }
235 if (export_params.export_uv) {
236 obj_writer.write_uv_coords(fh, obj);
237 }
238 /* This function takes a 0-indexed slot index for the obj_mesh object and
239 * returns the material name that we are using in the `.obj` file for it. */
240 const auto *obj_mtlindices = mtlindices.is_empty() ? nullptr : &mtlindices[i];
241 auto matname_fn = [&](int s) -> const char * {
242 if (!obj_mtlindices || s < 0 || s >= obj_mtlindices->size()) {
243 return nullptr;
244 }
245 return mtl_writer->mtlmaterial_name((*obj_mtlindices)[s]);
246 };
247 obj_writer.write_face_elements(fh, index_offsets[i], obj, matname_fn);
248 }
249 obj_writer.write_edges_indices(fh, index_offsets[i], obj);
250
251 /* Nothing will need this object's data after this point, release
252 * various arrays here. */
253 obj.clear();
254 }
255 });
256
257 /* Write all the object text buffers into the output file. */
258 FILE *f = obj_writer.get_outfile();
259 for (auto &b : buffers) {
260 b.write_to_file(f);
261 }
262}
263
267static void write_nurbs_curve_objects(const Span<std::unique_ptr<IOBJCurve>> exportable_as_nurbs,
268 const OBJWriter &obj_writer)
269{
270 FormatHandler fh;
271 /* #OBJCurve doesn't have any dynamically allocated memory, so it's fine
272 * to wait for #Vector to clean the objects up. */
273 for (const std::unique_ptr<IOBJCurve> &obj_curve : exportable_as_nurbs) {
274 obj_writer.write_nurbs_curve(fh, *obj_curve);
275 }
276 fh.write_to_file(obj_writer.get_outfile());
277}
278
279static bool open_stream_writers(const OBJExportParams &export_params,
280 const char *filepath,
281 std::unique_ptr<OBJWriter> &r_frame_writer,
282 std::unique_ptr<MTLWriter> &r_mtl_writer)
283{
284 try {
285 r_frame_writer = std::make_unique<OBJWriter>(filepath, export_params);
286 }
287 catch (const std::system_error &ex) {
289 BKE_reportf(export_params.reports, RPT_ERROR, "OBJ Export: Cannot open file '%s'", filepath);
290 return false;
291 }
292 if (!r_frame_writer) {
293 BLI_assert_msg(false, "File should be writable by now.");
294 return false;
295 }
296 if (export_params.export_materials || export_params.export_material_groups) {
297 try {
298 r_mtl_writer = std::make_unique<MTLWriter>(filepath, export_params.export_materials);
299 }
300 catch (const std::system_error &ex) {
302 BKE_reportf(export_params.reports,
304 "OBJ Export: Cannot create mtl file for '%s'",
305 filepath);
306 }
307 }
308 return true;
309}
310
311static void write_materials(MTLWriter *mtl_writer, const OBJExportParams &export_params)
312{
313 BLI_assert(mtl_writer);
314 mtl_writer->write_header(export_params.blen_filepath);
315 char dest_dir[FILE_MAX];
316 if (export_params.file_base_for_tests[0] == '\0') {
317 BLI_path_split_dir_part(export_params.filepath, dest_dir, sizeof(dest_dir));
318 }
319 else {
320 STRNCPY(dest_dir, export_params.file_base_for_tests);
321 }
322 BLI_path_slash_native(dest_dir);
323 BLI_path_normalize(dest_dir);
324 mtl_writer->write_materials(export_params.blen_filepath,
325 export_params.path_mode,
326 dest_dir,
327 export_params.export_pbr_extensions);
328}
329
330void export_objects(const OBJExportParams &export_params,
331 const Span<std::unique_ptr<OBJMesh>> meshes,
332 const Span<std::unique_ptr<IOBJCurve>> curves,
333 const char *filepath)
334{
335 /* Open */
336 std::unique_ptr<OBJWriter> obj_writer;
337 std::unique_ptr<MTLWriter> mtl_writer;
338 if (!open_stream_writers(export_params, filepath, obj_writer, mtl_writer)) {
339 return;
340 }
341
342 /* Write */
343 obj_writer->write_header();
344 write_mesh_objects(meshes, *obj_writer, mtl_writer.get(), export_params);
345 write_nurbs_curve_objects(curves, *obj_writer);
346 if (mtl_writer && export_params.export_materials) {
347 write_materials(mtl_writer.get(), export_params);
348 }
349}
350
351void export_frame(Depsgraph *depsgraph, const OBJExportParams &export_params, const char *filepath)
352{
353 auto [exportable_as_mesh, exportable_as_nurbs] = filter_supported_objects(depsgraph,
354 export_params);
355
356 if (exportable_as_mesh.size() == 0 && exportable_as_nurbs.size() == 0) {
357 BKE_reportf(export_params.reports, RPT_WARNING, "OBJ Export: No information to write");
358 return;
359 }
360
361 export_objects(export_params, exportable_as_mesh, exportable_as_nurbs, filepath);
362}
363
364bool append_frame_to_filename(const char *filepath,
365 const int frame,
366 char r_filepath_with_frames[FILE_MAX])
367{
368 BLI_strncpy(r_filepath_with_frames, filepath, FILE_MAX);
369 BLI_path_extension_strip(r_filepath_with_frames);
370 BLI_path_frame(r_filepath_with_frames, FILE_MAX, frame, 4);
371 return BLI_path_extension_replace(r_filepath_with_frames, FILE_MAX, ".obj");
372}
373
374void exporter_main(bContext *C, const OBJExportParams &export_params)
375{
377
378 Collection *collection = nullptr;
379 if (export_params.collection[0]) {
380 Main *bmain = CTX_data_main(C);
381 collection = reinterpret_cast<Collection *>(
382 BKE_libblock_find_name(bmain, ID_GR, export_params.collection));
383 if (!collection) {
384 BKE_reportf(export_params.reports,
385 RPT_ERROR,
386 "OBJ Export: Unable to find collection '%s'",
387 export_params.collection);
388 return;
389 }
390 }
391
392 OBJDepsgraph obj_depsgraph(C, export_params.export_eval_mode, collection);
393 Scene *scene = DEG_get_input_scene(obj_depsgraph.get());
394 const char *filepath = export_params.filepath;
395
396 /* Single frame export, i.e. no animation. */
397 if (!export_params.export_animation) {
398 fmt::println("Writing to {}", filepath);
399 export_frame(obj_depsgraph.get(), export_params, filepath);
400 return;
401 }
402
403 char filepath_with_frames[FILE_MAX];
404 /* Used to reset the Scene to its original state. */
405 const int original_frame = scene->r.cfra;
406
407 for (int frame = export_params.start_frame; frame <= export_params.end_frame; frame++) {
408 const bool filepath_ok = append_frame_to_filename(filepath, frame, filepath_with_frames);
409 if (!filepath_ok) {
410 CLOG_ERROR(&LOG, "File Path too long: %s", filepath_with_frames);
411 return;
412 }
413
414 scene->r.cfra = frame;
415 obj_depsgraph.update_for_newframe();
416 fmt::println("Writing to {}", filepath_with_frames);
417 export_frame(obj_depsgraph.get(), export_params, filepath_with_frames);
418 }
419 scene->r.cfra = original_frame;
420}
421} // namespace io::obj
422} // namespace blender
#define FILE_MAX
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
#define DEG_OBJECT_ITER_BEGIN(settings_, instance_)
#define DEG_OBJECT_ITER_END
Object groups, one object can be in many groups at once.
#define C
Definition RandGen.cpp:29
#define BLI_assert_msg(a, msg)
constexpr IndexRange()=default
void append(const T &value)
bool is_empty() const
void reserve(const int64_t min_capacity)
Vector< int > add_materials(const OBJMesh &mesh_to_export)
void write_header(const char *blen_filepath)
void write_materials(const char *blen_filepath, ePathReferenceMode path_mode, const char *dest_dir, bool write_pbr)
const char * mtlmaterial_name(int index)
OBJDepsgraph(const bContext *C, eEvaluationMode eval_mode, Collection *collection)
OBJLegacyCurve(const Depsgraph *depsgraph, Object *curve_object)
void write_normals(FormatHandler &fh, OBJMesh &obj_mesh_data)
void write_mtllib_name(StringRefNull mtl_filepath) const
void write_uv_coords(FormatHandler &fh, OBJMesh &obj_mesh_data) const
void write_nurbs_curve(FormatHandler &fh, const IOBJCurve &obj_nurbs_data) const
void write_face_elements(FormatHandler &fh, const IndexOffsets &offsets, const OBJMesh &obj_mesh_data, FunctionRef< const char *(int)> matname_fn)
void write_vertex_coords(FormatHandler &fh, const OBJMesh &obj_mesh_data, bool write_colors) const
void write_edges_indices(FormatHandler &fh, const IndexOffsets &offsets, const OBJMesh &obj_mesh_data) const
void write_object_name(FormatHandler &fh, const OBJMesh &obj_mesh_data) const
bool mode_set(bContext *C, eObjectMode mode)
static void print_exception_error(const std::system_error &ex)
static void write_materials(MTLWriter *mtl_writer, const OBJExportParams &export_params)
void export_objects(const OBJExportParams &export_params, const Span< std::unique_ptr< OBJMesh > > meshes, const Span< std::unique_ptr< IOBJCurve > > curves, const char *filepath)
std::pair< Vector< std::unique_ptr< OBJMesh > >, Vector< std::unique_ptr< IOBJCurve > > > filter_supported_objects(Depsgraph *depsgraph, const OBJExportParams &export_params)
bool append_frame_to_filename(const char *filepath, const int frame, char r_filepath_with_frames[FILE_MAX])
static bool open_stream_writers(const OBJExportParams &export_params, const char *filepath, std::unique_ptr< OBJWriter > &r_frame_writer, std::unique_ptr< MTLWriter > &r_mtl_writer)
static bool is_curve_nurbs_compatible(const Nurb *nurb)
static void write_mesh_objects(const Span< std::unique_ptr< OBJMesh > > exportable_as_mesh, OBJWriter &obj_writer, MTLWriter *mtl_writer, const OBJExportParams &export_params)
static void write_nurbs_curve_objects(const Span< std::unique_ptr< IOBJCurve > > exportable_as_nurbs, const OBJWriter &obj_writer)
void exporter_main(bContext *C, const OBJExportParams &export_params)
void export_frame(Depsgraph *depsgraph, const OBJExportParams &export_params, const char *filepath)
void parallel_for(const IndexRange range, const int64_t grain_size, const Function &function, const TaskSizeHints &size_hints=detail::TaskSizeHints_Static(1))
Definition BLI_task.hh:69
BMesh Iterators.
bool bool BLI_path_extension_strip(char *path) ATTR_NONNULL(1)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
void BKE_scene_graph_update_for_newframe(Depsgraph *depsgraph)
Definition scene.cc:2953
char * STRNCPY(char(&dst)[N], const char *src)
ID * BKE_libblock_find_name(Main *bmain, short type, const char *name, const std::optional< Library * > lib=std::nullopt) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition lib_id.cc:1808
@ RPT_WARNING
Definition BKE_report.hh:40
void DEG_graph_build_from_collection(Depsgraph *graph, Collection *collection)
void DEG_graph_free(Depsgraph *graph)
Definition depsgraph.cc:307
Depsgraph * DEG_graph_new(Main *bmain, Scene *scene, ViewLayer *view_layer, eEvaluationMode mode)
Definition depsgraph.cc:279
bool BLI_path_frame(char *path, size_t path_maxncpy, int frame, int digits) ATTR_NONNULL(1)
void BLI_path_slash_native(char *path) ATTR_NONNULL(1)
ViewLayer * CTX_data_view_layer(const bContext *C)
void BKE_scene_graph_evaluated_ensure(Depsgraph *depsgraph, Main *bmain)
Definition scene.cc:2872
char * BLI_strncpy(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
void void BLI_path_split_dir_part(const char *filepath, char *dir, size_t dir_maxncpy) ATTR_NONNULL(1
Depsgraph * CTX_data_ensure_evaluated_depsgraph(const bContext *C, bool rna_write_check=false)
@ DEG_ITER_OBJECT_FLAG_LINKED_VIA_SET
@ DEG_ITER_OBJECT_FLAG_LINKED_DIRECTLY
void DEG_graph_build_for_all_objects(Depsgraph *graph)
int BLI_path_normalize(char *path) ATTR_NONNULL(1)
bool BLI_path_extension_replace(char *path, size_t path_maxncpy, const char *ext) ATTR_NONNULL(1
void BKE_reportf(ReportList *reports, eReportType type, const char *format,...) ATTR_PRINTF_FORMAT(3
Definition report.cc:191
Main * CTX_data_main(const bContext *C)
Scene * DEG_get_input_scene(const Depsgraph *graph)
static CLG_LogRef LOG
Definition logging.cpp:12
Scene * CTX_data_scene(const bContext *C)
ListBaseT< Nurb > nurb
struct Nurb * next
eEvaluationMode export_eval_mode
char collection[MAX_ID_NAME - 2]
ePathReferenceMode path_mode
char file_base_for_tests[FILE_MAX]
struct RenderData r