Blender V5.3
stl_export.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 <memory>
10
11#include "BKE_context.hh"
12#include "BKE_lib_id.hh"
13#include "BKE_mesh_wrapper.hh"
14#include "BKE_report.hh"
15#include "BKE_scene.hh"
16
17#include "BLI_string.hh"
18#include "BLI_string_utils.hh"
19
21
22#include "DNA_layer_types.h"
23#include "DNA_mesh_types.h"
24#include "DNA_object_types.h"
25#include "DNA_scene_types.h"
26
27#include "ED_util.hh"
28
29#include "BLI_math_matrix_c.hh"
31#include "BLI_math_vector.hh"
33
34#include "IO_mesh_utils.hh"
35#include "IO_stl.hh"
36
37#include "stl_data.hh"
38#include "stl_export.hh"
39#include "stl_export_writer.hh"
40
41#include "CLG_log.h"
42
43namespace blender {
44
45static CLG_LogRef LOG = {"io.stl"};
46
47namespace io::stl {
48
49void export_frame(Depsgraph *depsgraph,
50 float scene_unit_scale,
51 const STLExportParams &export_params)
52{
53 std::unique_ptr<FileWriter> writer;
54
55 /* If not exporting in batch, create single writer for all objects. */
56 if (!export_params.use_batch) {
57 try {
58 writer = std::make_unique<FileWriter>(export_params.filepath, export_params.ascii_format);
59 }
60 catch (const std::runtime_error &ex) {
61 CLOG_ERROR(&LOG, "Error: %s", ex.what());
62 BKE_reportf(export_params.reports,
64 "STL Export: Cannot open file '%s'",
65 export_params.filepath);
66 return;
67 }
68 }
69
70 DEGObjectIterSettings deg_iter_settings{};
71 deg_iter_settings.depsgraph = depsgraph;
75
76 DEG_OBJECT_ITER_BEGIN (&deg_iter_settings, object) {
77 if (object->type != OB_MESH) {
78 continue;
79 }
80
81 if (export_params.export_selected_objects && !(object->base_flag & BASE_SELECTED)) {
82 continue;
83 }
84
85 /* If exporting in batch, create writer for each iteration over objects. */
86 if (export_params.use_batch) {
87 /* Get object name by skipping initial "OB" prefix. */
88 char object_name[sizeof(object->id.name) - 2];
89 STRNCPY(object_name, object->id.name + 2);
90 BLI_path_make_safe_filename(object_name);
91 /* Replace spaces with underscores. */
92 BLI_string_replace_char(object_name, ' ', '_');
93
94 /* Include object name in the exported file name. */
95 char filepath[FILE_MAX];
96 STRNCPY(filepath, export_params.filepath);
97 /* When basename is just ".stl", regular path functions would
98 * treat it as a hidden file called ".stl". Remove the extension
99 * before trying to add a suffix. */
100 const char *basename = BLI_path_basename(filepath);
101 if (basename != nullptr && BLI_strcasecmp(basename, ".stl") == 0) {
102 *const_cast<char *>(basename) = '\0';
103 }
104
105 BLI_path_suffix(filepath, FILE_MAX, object_name, "");
106 /* Make sure we have `.stl` extension (case insensitive). */
107 if (!BLI_path_extension_check(filepath, ".stl")) {
108 BLI_path_extension_ensure(filepath, FILE_MAX, ".stl");
109 }
110
111 try {
112 writer = std::make_unique<FileWriter>(filepath, export_params.ascii_format);
113 }
114 catch (const std::runtime_error &ex) {
115 CLOG_ERROR(&LOG, "Error: %s", ex.what());
117 export_params.reports, RPT_ERROR, "STL Export: Cannot open file '%s'", filepath);
118 return;
119 }
120 }
121
122 Object *obj_eval = DEG_get_evaluated(depsgraph, object);
123
124 MeshCoerceForExport coerce;
126 coerce, depsgraph, obj_eval, export_params.apply_modifiers);
127
128 /* Ensure data exists if currently in edit mode. */
130
131 /* Calculate transform. */
132 float global_scale = export_params.global_scale * scene_unit_scale;
133 float axes_transform[3][3];
134 unit_m3(axes_transform);
135 float xform[4][4];
136 /* +Y-forward and +Z-up are the default Blender axis settings. */
138 export_params.forward_axis, export_params.up_axis, IO_AXIS_Y, IO_AXIS_Z, axes_transform);
139 mul_m4_m3m4(xform, axes_transform, obj_eval->object_to_world().ptr());
140 /* mul_m4_m3m4 does not transform last row of obmat, i.e. location data. */
141 mul_v3_m3v3(xform[3], axes_transform, obj_eval->object_to_world().location());
142 xform[3][3] = obj_eval->object_to_world()[3][3];
143
144 const bool mirrored = is_negative_m4(xform);
145
146 /* Write triangles. */
147 const Span<float3> positions = mesh->vert_positions();
148 const Span<int> corner_verts = mesh->corner_verts();
149 for (const int3 &tri : mesh->corner_tris()) {
151 for (int i = 0; i < 3; i++) {
152 /* Reverse face order for mirrored objects. */
153 int idx = mirrored ? 2 - i : i;
154 float3 pos = positions[corner_verts[tri[idx]]];
155 mul_m4_v3(xform, pos);
156 pos *= global_scale;
157 data.vertices[i] = pos;
158 }
159 data.normal = math::normal_tri(data.vertices[0], data.vertices[1], data.vertices[2]);
160 writer->write_triangle(data);
161 }
162 }
164}
165
166void exporter_main(const bContext *C, const STLExportParams &export_params)
167{
168 Main *bmain = CTX_data_main(C);
169 Scene *scene = CTX_data_scene(C);
170 ViewLayer *view_layer = CTX_data_view_layer(C);
171
173
174 Depsgraph *depsgraph = DEG_graph_new(bmain, scene, view_layer, export_params.evaluation_mode);
175
176 if (export_params.collection[0]) {
177 Collection *collection = reinterpret_cast<Collection *>(
178 BKE_libblock_find_name(bmain, ID_GR, export_params.collection));
179 if (!collection) {
180 BKE_reportf(export_params.reports,
181 RPT_ERROR,
182 "STL Export: Unable to find collection '%s'",
183 export_params.collection);
184
185 DEG_graph_free(depsgraph);
186 return;
187 }
188
189 DEG_graph_build_from_collection(depsgraph, collection);
190 }
191 else {
193 }
194 BKE_scene_graph_update_tagged(depsgraph, bmain);
195
196 float scene_unit_scale = 1.0f;
197 if ((scene->unit.system != USER_UNIT_NONE) && export_params.use_scene_unit) {
198 scene_unit_scale = scene->unit.scale_length;
199 }
200
201 export_frame(depsgraph, scene_unit_scale, export_params);
202
203 DEG_graph_free(depsgraph);
204}
205
206} // namespace io::stl
207} // 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 is a sort of wrapper for general info.
#define C
Definition RandGen.cpp:29
void export_frame(Depsgraph *depsgraph, float scene_unit_scale, const STLExportParams &export_params)
Definition stl_export.cc:49
void exporter_main(const bContext *C, const STLExportParams &export_params)
const Mesh * mesh_coerce_for_export_setup(MeshCoerceForExport &coerce, Depsgraph *depsgraph, Object *obj_eval, const bool apply_modifiers)
Definition mesh_utils.cc:19
VecBase< T, 3 > normal_tri(const VecBase< T, 3 > &v1, const VecBase< T, 3 > &v2, const VecBase< T, 3 > &v3)
BMesh Iterators.
int char char int BLI_strcasecmp(const char *s1, const char *s2) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1
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
bool ED_editors_flush_edits(Main *bmain)
Definition ed_util.cc:335
void DEG_graph_build_from_view_layer(Depsgraph *graph)
void DEG_graph_build_from_collection(Depsgraph *graph, Collection *collection)
void DEG_graph_free(Depsgraph *graph)
Definition depsgraph.cc:307
void BLI_string_replace_char(char *str, char src, char dst) ATTR_NONNULL(1)
bool bool BLI_path_suffix(char *path, size_t path_maxncpy, const char *suffix, const char *sep) ATTR_NONNULL(1
Depsgraph * DEG_graph_new(Main *bmain, Scene *scene, ViewLayer *view_layer, eEvaluationMode mode)
Definition depsgraph.cc:279
void BKE_mesh_wrapper_ensure_mdata(Mesh *mesh)
bool is_negative_m4(const float mat[4][4])
ViewLayer * CTX_data_view_layer(const bContext *C)
void mul_m4_v3(const float M[4][4], float r[3])
void void void const char * BLI_path_basename(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
bool BLI_path_extension_ensure(char *path, size_t path_maxncpy, const char *ext) ATTR_NONNULL(1
VecBase< int32_t, 3 > int3
BMesh const char void * data
T * DEG_get_evaluated(const Depsgraph *depsgraph, T *id)
@ DEG_ITER_OBJECT_FLAG_LINKED_VIA_SET
@ DEG_ITER_OBJECT_FLAG_LINKED_DIRECTLY
void BKE_scene_graph_update_tagged(Depsgraph *depsgraph, Main *bmain)
Definition scene.cc:2867
bool mat3_from_axis_conversion(int src_forward, int src_up, int dst_forward, int dst_up, float r_mat[3][3])
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)
void unit_m3(float m[3][3])
bool BLI_path_extension_check(const char *path, const char *ext) ATTR_NONNULL(1
static CLG_LogRef LOG
Definition logging.cpp:12
Scene * CTX_data_scene(const bContext *C)
bool BLI_path_make_safe_filename(char *filename) ATTR_NONNULL(1)
VecBase< float, 3 > float3
void mul_v3_m3v3(float r[3], const float M[3][3], const float a[3])
void mul_m4_m3m4(float R[4][4], const float A[3][3], const float B[4][4])
eEvaluationMode evaluation_mode
Definition IO_stl.hh:47
char collection[MAX_ID_NAME - 2]
Definition IO_stl.hh:50
ReportList * reports
Definition IO_stl.hh:52
char filepath[FILE_MAX]
Definition IO_stl.hh:40
struct UnitSettings unit