Blender V5.0
usd_export_test.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
5#include "testing/testing.h"
7
8#include <pxr/base/tf/stringUtils.h>
9#include <pxr/base/vt/types.h>
10#include <pxr/base/vt/value.h>
11#include <pxr/usd/sdf/types.h>
12#include <pxr/usd/usd/common.h>
13#include <pxr/usd/usd/prim.h>
14#include <pxr/usd/usd/stage.h>
15#include <pxr/usd/usdGeom/mesh.h>
16
17#include "DNA_image_types.h"
18#include "DNA_material_types.h"
19#include "DNA_mesh_types.h"
20#include "DNA_node_types.h"
21
22#include "BKE_context.hh"
23#include "BKE_lib_id.hh"
24#include "BKE_main.hh"
25
26#include "BLI_fileops.h"
27#include "BLI_listbase.h"
29#include "BLI_path_utils.hh"
30
31#include "BLO_readfile.hh"
32
33#include "BKE_node_runtime.hh"
34
35#include "DEG_depsgraph.hh"
36
37#include "usd.hh"
38#include "usd_utils.hh"
40
41namespace blender::io::usd {
42
43const StringRefNull simple_scene_filename = "usd/usd_simple_scene.blend";
44const StringRefNull materials_filename = "usd/usd_materials_export.blend";
45const StringRefNull output_filename = "output.usd";
46
47static const bNode *find_node_for_type_in_graph(const bNodeTree *nodetree,
48 const blender::StringRefNull type_idname);
49
51 protected:
52 bContext *context = nullptr;
53
54 public:
56 const eEvaluationMode eval_mode = DAG_EVAL_VIEWPORT)
57 {
58 if (!blendfile_load(filepath.c_str())) {
59 return false;
60 }
61 depsgraph_create(eval_mode);
62
66
67 return true;
68 }
69
70 void SetUp() override
71 {
72 BlendfileLoadingBaseTest::SetUp();
73 }
74
75 void TearDown() override
76 {
79 context = nullptr;
80
81 if (BLI_exists(output_filename.c_str())) {
82 BLI_delete(output_filename.c_str(), false, false);
83 }
84 }
85
86 pxr::UsdPrim get_first_child_mesh(const pxr::UsdPrim prim)
87 {
88 for (auto child : prim.GetChildren()) {
89 if (child.IsA<pxr::UsdGeomMesh>()) {
90 return child;
91 }
92 }
93 return pxr::UsdPrim();
94 }
95
100 void compare_blender_node_to_usd_prim(const bNode *bsdf_node, const pxr::UsdPrim &bsdf_prim)
101 {
102 ASSERT_NE(bsdf_node, nullptr);
103 ASSERT_TRUE(bool(bsdf_prim));
104
105 for (const auto *socket : bsdf_node->input_sockets()) {
106 const pxr::TfToken attribute_token = blender::io::usd::token_for_input(socket->name);
107 if (attribute_token.IsEmpty()) {
108 /* This socket is not translated between Blender and USD. */
109 continue;
110 }
111
112 const pxr::UsdAttribute bsdf_attribute = bsdf_prim.GetAttribute(attribute_token);
113 pxr::SdfPathVector paths;
114 bsdf_attribute.GetConnections(&paths);
115 if (!paths.empty() || !bsdf_attribute.IsValid()) {
116 /* Skip if the attribute is connected or has an error. */
117 continue;
118 }
119
120 const float socket_value_f = *socket->default_value_typed<float>();
121 const float3 socket_value_3f = *socket->default_value_typed<float3>();
122 float attribute_value_f;
123 pxr::GfVec3f attribute_value_3f;
124
125 switch (socket->type) {
126 case SOCK_FLOAT:
127 bsdf_attribute.Get(&attribute_value_f, 0.0);
128 EXPECT_FLOAT_EQ(socket_value_f, attribute_value_f);
129 break;
130
131 case SOCK_VECTOR:
132 bsdf_attribute.Get(&attribute_value_3f, 0.0);
133 EXPECT_FLOAT_EQ(socket_value_3f[0], attribute_value_3f[0]);
134 EXPECT_FLOAT_EQ(socket_value_3f[1], attribute_value_3f[1]);
135 EXPECT_FLOAT_EQ(socket_value_3f[2], attribute_value_3f[2]);
136 break;
137
138 case SOCK_RGBA:
139 bsdf_attribute.Get(&attribute_value_3f, 0.0);
140 EXPECT_FLOAT_EQ(socket_value_3f[0], attribute_value_3f[0]);
141 EXPECT_FLOAT_EQ(socket_value_3f[1], attribute_value_3f[1]);
142 EXPECT_FLOAT_EQ(socket_value_3f[2], attribute_value_3f[2]);
143 break;
144
145 default:
146 FAIL() << "Socket " << socket->name << " has unsupported type " << socket->type;
147 break;
148 }
149 }
150 }
151
153 const pxr::UsdPrim &image_prim)
154 {
155 const Image *image = reinterpret_cast<Image *>(image_node->id);
156
157 const pxr::UsdShadeShader image_shader(image_prim);
158 const pxr::UsdShadeInput file_input = image_shader.GetInput(pxr::TfToken("file"));
159 EXPECT_TRUE(bool(file_input));
160
161 pxr::VtValue file_val;
162 EXPECT_TRUE(file_input.Get(&file_val));
163 EXPECT_TRUE(file_val.IsHolding<pxr::SdfAssetPath>());
164
165 pxr::SdfAssetPath image_prim_asset = file_val.Get<pxr::SdfAssetPath>();
166
167 /* The path is expected to be relative, but that means in Blender the
168 * path will start with //.
169 */
170 EXPECT_EQ(
171 BLI_path_cmp_normalized(image->filepath + 2, image_prim_asset.GetAssetPath().c_str()), 0);
172 }
173
174 /*
175 * Determine if a Blender Mesh matches a UsdGeomMesh prim by checking counts
176 * on vertices, faces, face indices, and normals.
177 */
178 void compare_blender_mesh_to_usd_prim(const Mesh *mesh, const pxr::UsdGeomMesh &mesh_prim)
179 {
180 pxr::VtIntArray face_indices;
181 pxr::VtIntArray face_counts;
182 pxr::VtVec3fArray positions;
183 pxr::VtVec3fArray normals;
184
185 /* Our export doesn't use `primvars:normals` so we're not
186 * looking for that to be written here. */
187 mesh_prim.GetFaceVertexIndicesAttr().Get(&face_indices, 0.0);
188 mesh_prim.GetFaceVertexCountsAttr().Get(&face_counts, 0.0);
189 mesh_prim.GetPointsAttr().Get(&positions, 0.0);
190 mesh_prim.GetNormalsAttr().Get(&normals, 0.0);
191
192 EXPECT_EQ(mesh->verts_num, positions.size());
193 EXPECT_EQ(mesh->faces_num, face_counts.size());
194 EXPECT_EQ(mesh->corners_num, face_indices.size());
195 EXPECT_EQ(mesh->corners_num, normals.size());
196 }
197};
198
199TEST_F(UsdExportTest, usd_export_rain_mesh)
200{
201 if (!load_file_and_depsgraph(simple_scene_filename)) {
202 FAIL() << "Unable to load file: " << simple_scene_filename;
203 return;
204 }
205
206 /* File sanity check. */
207 EXPECT_EQ(BLI_listbase_count(&bfile->main->objects), 3);
208
210 params.export_materials = false;
211 params.export_normals = true;
212 params.export_uvmaps = false;
213
214 bool result = USD_export(context, output_filename.c_str(), &params, false, nullptr);
215 ASSERT_TRUE(result) << "Writing to " << output_filename << " failed!";
216
217 pxr::UsdStageRefPtr stage = pxr::UsdStage::Open(output_filename);
218 ASSERT_TRUE(bool(stage)) << "Unable to load Stage from " << output_filename;
219
220 /*
221 * Run the mesh comparison for all Meshes in the original scene.
222 */
223 LISTBASE_FOREACH (Object *, object, &bfile->main->objects) {
224 const Mesh *mesh = static_cast<Mesh *>(object->data);
225 const StringRefNull object_name(object->id.name + 2);
226
227 const pxr::SdfPath sdf_path("/" + pxr::TfMakeValidIdentifier(object_name.c_str()));
228 pxr::UsdPrim prim = stage->GetPrimAtPath(sdf_path);
229 EXPECT_TRUE(bool(prim));
230
231 const pxr::UsdGeomMesh mesh_prim(get_first_child_mesh(prim));
232 EXPECT_TRUE(bool(mesh_prim));
233
234 compare_blender_mesh_to_usd_prim(mesh, mesh_prim);
235 }
236}
237
238static const bNode *find_node_for_type_in_graph(const bNodeTree *nodetree,
239 const blender::StringRefNull type_idname)
240{
241 auto found_nodes = nodetree->nodes_by_type(type_idname);
242 if (found_nodes.size() == 1) {
243 return found_nodes[0];
244 }
245
246 return nullptr;
247}
248
249/*
250 * Export Material test-- export a scene with a material, then read it back
251 * in and check that the BSDF and Image Texture nodes translated correctly
252 * by comparing values between the exported USD stage and the objects in
253 * memory.
254 */
255TEST_F(UsdExportTest, usd_export_material)
256{
257 if (!load_file_and_depsgraph(materials_filename)) {
258 FAIL() << "Unable to load file: " << materials_filename;
259 return;
260 }
261
262 /* File sanity checks. */
263 EXPECT_EQ(BLI_listbase_count(&bfile->main->objects), 6);
264 /* There is 1 additional material because of the "Dots Stroke". */
265 EXPECT_EQ(BLI_listbase_count(&bfile->main->materials), 7);
266
267 Material *material = reinterpret_cast<Material *>(
268 BKE_libblock_find_name(bfile->main, ID_MA, "Material"));
269
270 EXPECT_TRUE(bool(material));
271
273 params.export_materials = true;
274 params.export_normals = true;
275 params.export_textures = false;
276 params.export_uvmaps = true;
277 params.generate_preview_surface = true;
278 params.generate_materialx_network = false;
279 params.convert_world_material = false;
280 params.relative_paths = false;
281
282 const bool result = USD_export(context, output_filename.c_str(), &params, false, nullptr);
283 ASSERT_TRUE(result) << "Unable to export stage to " << output_filename;
284
285 pxr::UsdStageRefPtr stage = pxr::UsdStage::Open(output_filename);
286 ASSERT_NE(stage, nullptr) << "Unable to open exported stage: " << output_filename;
287
288 material->nodetree->ensure_topology_cache();
289 const bNode *bsdf_node = find_node_for_type_in_graph(material->nodetree,
290 "ShaderNodeBsdfPrincipled");
291
292 const std::string prim_name = pxr::TfMakeValidIdentifier(bsdf_node->name);
293 const pxr::UsdPrim bsdf_prim = stage->GetPrimAtPath(
294 pxr::SdfPath("/_materials/Material/" + prim_name));
295
296 compare_blender_node_to_usd_prim(bsdf_node, bsdf_prim);
297
298 const bNode *image_node = find_node_for_type_in_graph(material->nodetree, "ShaderNodeTexImage");
299 ASSERT_NE(image_node, nullptr);
300 ASSERT_NE(image_node->storage, nullptr);
301
302 const std::string image_prim_name = pxr::TfMakeValidIdentifier(image_node->name);
303
304 const pxr::UsdPrim image_prim = stage->GetPrimAtPath(
305 pxr::SdfPath("/_materials/Material/" + image_prim_name));
306
307 ASSERT_TRUE(bool(image_prim)) << "Unable to find Material prim from exported stage "
309
310 compare_blender_image_to_usd_image_shader(image_node, image_prim);
311}
312
314{
315 /* ASCII variations. */
316 ASSERT_EQ(make_safe_name("", false), std::string("_"));
317 ASSERT_EQ(make_safe_name("|", false), std::string("_"));
318 ASSERT_EQ(make_safe_name("1", false), std::string("_1"));
319 ASSERT_EQ(make_safe_name("1Test", false), std::string("_1Test"));
320
321 ASSERT_EQ(make_safe_name("Test", false), std::string("Test"));
322 ASSERT_EQ(make_safe_name("Test|$bézier @ world", false), std::string("Test__b__zier___world"));
323 ASSERT_EQ(make_safe_name("Test|ハローワールド", false),
324 std::string("Test______________________"));
325 ASSERT_EQ(make_safe_name("Test|Γεια σου κόσμε", false),
326 std::string("Test___________________________"));
327 ASSERT_EQ(make_safe_name("Test|∧hello ○ wórld", false), std::string("Test____hello_____w__rld"));
328
329 /* Unicode variations. */
330 ASSERT_EQ(make_safe_name("", true), std::string("_"));
331 ASSERT_EQ(make_safe_name("|", true), std::string("_"));
332 ASSERT_EQ(make_safe_name("1", true), std::string("_1"));
333 ASSERT_EQ(make_safe_name("1Test", true), std::string("_1Test"));
334
335 ASSERT_EQ(make_safe_name("Test", true), std::string("Test"));
336 ASSERT_EQ(make_safe_name("Test|$bézier @ world", true), std::string("Test__bézier___world"));
337 ASSERT_EQ(make_safe_name("Test|ハローワールド", true), std::string("Test_ハローワールド"));
338 ASSERT_EQ(make_safe_name("Test|Γεια σου κόσμε", true), std::string("Test_Γεια_σου_κόσμε"));
339 ASSERT_EQ(make_safe_name("Test|∧hello ○ wórld", true), std::string("Test__hello___wórld"));
340}
341
342} // namespace blender::io::usd
void CTX_data_main_set(bContext *C, Main *bmain)
void CTX_free(bContext *C)
void CTX_data_scene_set(bContext *C, Scene *scene)
bContext * CTX_create()
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:1710
EXPECT_EQ(BLI_expr_pylike_eval(expr, nullptr, 0, &result), EXPR_PYLIKE_INVALID)
File and directory operations.
int BLI_exists(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:360
int BLI_delete(const char *path, bool dir, bool recursive) ATTR_NONNULL()
#define LISTBASE_FOREACH(type, var, list)
int BLI_listbase_count(const ListBase *listbase) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:524
int BLI_path_cmp_normalized(const char *p1, const char *p2) ATTR_NONNULL(1
external readfile function prototypes.
eEvaluationMode
@ DAG_EVAL_VIEWPORT
@ ID_MA
@ SOCK_VECTOR
@ SOCK_FLOAT
@ SOCK_RGBA
virtual void depsgraph_create(eEvaluationMode depsgraph_evaluation_mode)
bool blendfile_load(const char *filepath)
constexpr const char * c_str() const
pxr::UsdPrim get_first_child_mesh(const pxr::UsdPrim prim)
void compare_blender_image_to_usd_image_shader(const bNode *image_node, const pxr::UsdPrim &image_prim)
void compare_blender_node_to_usd_prim(const bNode *bsdf_node, const pxr::UsdPrim &bsdf_prim)
void compare_blender_mesh_to_usd_prim(const Mesh *mesh, const pxr::UsdGeomMesh &mesh_prim)
bool load_file_and_depsgraph(const StringRefNull &filepath, const eEvaluationMode eval_mode=DAG_EVAL_VIEWPORT)
static float normals[][3]
uiWidgetBaseParameters params[MAX_WIDGET_BASE_BATCH]
static const bNode * find_node_for_type_in_graph(const bNodeTree *nodetree, const blender::StringRefNull type_idname)
pxr::TfToken token_for_input(const StringRef input_name)
TEST_F(UsdExportTest, usd_export_rain_mesh)
TEST(utilities, make_safe_name)
std::string make_safe_name(const StringRef name, bool allow_unicode)
Definition usd_utils.cc:18
const StringRefNull simple_scene_filename
const StringRefNull materials_filename
bool USD_export(const bContext *C, const char *filepath, const USDExportParams *params, bool as_background_job, ReportList *reports)
const StringRefNull output_filename
VecBase< float, 3 > float3
char filepath[1024]
struct bNodeTree * nodetree
int corners_num
int faces_num
int verts_num
struct ID * id
char name[64]
void * storage