Blender V5.3
usd_writer_mesh.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2019 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4#include "usd_writer_mesh.hh"
5
10#include "usd_skel_convert.hh"
11#include "usd_utils.hh"
12
13#include <pxr/usd/usdGeom/mesh.h>
14#include <pxr/usd/usdGeom/primvarsAPI.h>
15#include <pxr/usd/usdShade/material.h>
16#include <pxr/usd/usdShade/materialBindingAPI.h>
17#include <pxr/usd/usdSkel/bindingAPI.h>
18
19#include "IO_mesh_utils.hh"
20
21#include "BLI_array_utils.hh"
22#include "BLI_assert.hh"
24
26#include "BKE_attribute.hh"
27#include "BKE_lib_id.hh"
28#include "BKE_material.hh"
29#include "BKE_mesh.hh"
30#include "BKE_mesh_mapping.hh"
31#include "BKE_mesh_wrapper.hh"
32#include "BKE_object.hh"
33#include "BKE_report.hh"
34#include "BKE_subdiv.hh"
35
36#include "bmesh.hh"
37#include "bmesh_tools.hh"
38
39#include "DEG_depsgraph.hh"
40
41#include "DNA_key_types.h"
42#include "DNA_material_types.h"
43#include "DNA_modifier_types.h"
44#include "DNA_object_types.h"
45
46#include "CLG_log.h"
47
48namespace blender {
49
50static CLG_LogRef LOG = {"io.usd"};
51
52namespace io::usd {
53
57
59{
60 return context->is_object_visible(usd_export_context_.export_params.evaluation_mode);
61}
62
63/* Get the last subdiv modifier, regardless of enable/disable status */
65{
67
68 /* Return the subdiv modifier if it is the last modifier and has
69 * the required mode enabled. */
70
71 ModifierData *md = obj->modifiers.last();
72
73 if (!md) {
74 return nullptr;
75 }
76
77 /* Determine if the modifier is enabled for the current evaluation mode. */
78 ModifierMode mod_mode = (eval_mode == DAG_EVAL_RENDER) ? eModifierMode_Render :
80
81 if ((md->mode & mod_mode) != mod_mode) {
82 return nullptr;
83 }
84
85 if (md->type == eModifierType_Subsurf) {
86 return reinterpret_cast<SubsurfModifierData *>(md);
87 }
88
89 return nullptr;
90}
91
93{
94 Object *object_eval = context.object;
95 bool needsfree = false;
96 Mesh *mesh = get_export_mesh(object_eval, needsfree);
97
98 if (mesh == nullptr) {
99 return;
100 }
101
103 const bool tag_only = false;
104 const int quad_method = usd_export_context_.export_params.quad_method;
105 const int ngon_method = usd_export_context_.export_params.ngon_method;
106
107 BMeshCreateParams bmesh_create_params{};
108 BMeshFromMeshParams bmesh_from_mesh_params{};
109 bmesh_from_mesh_params.calc_face_normal = true;
110 bmesh_from_mesh_params.calc_vert_normal = true;
111 BMesh *bm = BKE_mesh_to_bmesh_ex(mesh, &bmesh_create_params, &bmesh_from_mesh_params);
112
113 BM_mesh_triangulate(bm, quad_method, ngon_method, 4, tag_only, nullptr, nullptr, nullptr);
114
115 Mesh *triangulated_mesh = BKE_mesh_from_bmesh_for_eval_nomain(bm, nullptr, mesh);
117
118 if (needsfree) {
120 }
121 mesh = triangulated_mesh;
122 needsfree = true;
123 }
124
125 try {
126 /* Fetch the subdiv modifier, if one exists and it is the last modifier. */
129
130 write_mesh(context, mesh, subsurfData);
131
132 auto prim = usd_export_context_.stage->GetPrimAtPath(usd_export_context_.usd_path);
133 if (prim.IsValid() && object_eval) {
134 prim.SetActive((object_eval->duplicator_visibility_flag & OB_DUPLI_FLAG_RENDER) != 0);
135 add_to_prim_map(prim.GetPath(), &mesh->id);
137 }
138
139 if (needsfree) {
141 }
142 }
143 catch (...) {
144 if (needsfree) {
146 }
147 throw;
148 }
149}
150
151void USDGenericMeshWriter::write_custom_data(const Object *obj,
152 const Mesh *mesh,
153 const pxr::UsdGeomMesh &usd_mesh)
154{
155 const bke::AttributeAccessor attributes = mesh->attributes();
156
157 const StringRef active_uvmap_name = mesh->default_uv_map_name();
158
159 attributes.foreach_attribute([&](const bke::AttributeIter &iter) {
160 /* Skip "internal" Blender properties and attributes processed elsewhere.
161 * Skip edge domain because USD doesn't have a good conversion for them. */
162 if (iter.name[0] == '.' || bke::attribute_name_is_anonymous(iter.name) ||
164 ELEM(iter.name,
165 "position",
166 "material_index",
167 "velocity",
168 "crease_vert",
169 "custom_normal",
170 "sharp_face"))
171 {
172 return;
173 }
174
177 iter.name.rfind("skel:") == 0)
178 {
179 /* If we're exporting armatures or shape keys to UsdSkel, we skip any
180 * attributes that have names with the "skel:" namespace, to avoid possible
181 * conflicts. Such attribute might have been previously imported into Blender
182 * from USD, but can no longer be considered valid. */
183 return;
184 }
185
188 {
189 /* This attribute is likely a vertex group for the armature modifier,
190 * and it may conflict with skinning data that will be written to
191 * the USD mesh, so we skip it. Such vertex groups will instead be
192 * handled in #export_deform_verts(). */
193 return;
194 }
195
196 /* UV Data. */
199 this->write_uv_data(mesh, usd_mesh, iter, active_uvmap_name);
200 }
201 }
202
203 else {
204 this->write_generic_data(mesh, usd_mesh, iter);
205 }
206 });
207}
208
209static std::optional<pxr::TfToken> convert_blender_domain_to_usd(
210 const bke::AttrDomain blender_domain)
211{
212 switch (blender_domain) {
214 return pxr::UsdGeomTokens->faceVarying;
216 return pxr::UsdGeomTokens->vertex;
218 return pxr::UsdGeomTokens->uniform;
219
220 /* Notice: Edge types are not supported in USD! */
221 default:
222 return std::nullopt;
223 }
224}
225
226void USDGenericMeshWriter::write_generic_data(const Mesh *mesh,
227 const pxr::UsdGeomMesh &usd_mesh,
228 const bke::AttributeIter &attr)
229{
230 const pxr::TfToken pv_name(
232 const bool use_color3f_type = pv_name == usdtokens::displayColor;
233 const std::optional<pxr::TfToken> pv_interp = convert_blender_domain_to_usd(attr.domain);
234 const std::optional<pxr::SdfValueTypeName> pv_type = convert_blender_type_to_usd(
235 attr.data_type, use_color3f_type);
236
237 if (!pv_interp || !pv_type) {
240 "Mesh '%s', Attribute '%s' (domain %d, type %d) cannot be converted to USD",
241 BKE_id_name(mesh->id),
242 attr.name.c_str(),
243 int8_t(attr.domain),
244 int(attr.data_type));
245 return;
246 }
247
248 const GVArray attribute = *attr.get();
249 if (attribute.is_empty()) {
250 return;
251 }
252
253 const pxr::UsdTimeCode time = get_export_time_code();
254 const pxr::UsdGeomPrimvarsAPI pv_api = pxr::UsdGeomPrimvarsAPI(usd_mesh);
255
256 pxr::UsdGeomPrimvar pv_attr = pv_api.CreatePrimvar(pv_name, *pv_type, *pv_interp);
257
259}
260
261void USDGenericMeshWriter::write_uv_data(const Mesh *mesh,
262 const pxr::UsdGeomMesh &usd_mesh,
263 const bke::AttributeIter &attr,
264 const StringRef active_uvmap_name)
265{
266 const VArray<float2> buffer = *attr.get<float2>(bke::AttrDomain::Corner);
267 if (buffer.is_empty()) {
268 return;
269 }
270
271 /* Optionally rename active UV map to "st", to follow USD conventions
272 * and better work with MaterialX shader nodes. */
273 const StringRef name = usd_export_context_.export_params.rename_uvmaps &&
274 active_uvmap_name == attr.name ?
275 "st" :
276 attr.name;
277
278 /* Construct the UvVertMap containing the connectivity data for the UVs. */
279 const OffsetIndices<int> faces = mesh->faces();
280 const Span<int> corner_verts = mesh->corner_verts();
281 const VArraySpan<float2> uv_data(buffer);
282 UvVertMap *uv_vert_map = BKE_mesh_uv_vert_map_create(
283 faces, corner_verts, uv_data, mesh->verts_num, float2(STD_UV_CONNECT_LIMIT), false);
284
285 /* This will only be a nullptr if the `faces` are empty OR allocating space for
286 * the VertMap fails. */
287 if (!uv_vert_map) {
288 CLOG_WARN(&LOG,
289 "Couldn't resolve UV connectivity for mesh %s",
290 usd_export_context_.usd_path.GetAsString().c_str());
291 return;
292 }
293
294 /* From the connectivity data, extract the unique uvs and a mapping of corner index
295 * to the index of the corresponding unique uv for that corner. */
296 pxr::VtArray<pxr::GfVec2f> unique_uvs;
297 unique_uvs.reserve(mesh->verts_num);
298 Array<int> corner_to_uv_index(corner_verts.size(), -1);
299 for (int vertex_index = 0; vertex_index < mesh->verts_num; vertex_index++) {
300 const UvMapVert *uv_vert = BKE_mesh_uv_vert_map_get_vert(uv_vert_map, vertex_index);
301
302 /* Loop over all of the face vertices connected to this mesh vertex and accumulate the
303 * unique UVs. */
304 for (; uv_vert; uv_vert = uv_vert->next) {
305 const int corner_index = faces[uv_vert->face_index].start() + uv_vert->loop_of_face_index;
306 const float2 uv = uv_data[corner_index];
307 if (uv_vert->separate) {
308 unique_uvs.push_back(pxr::GfVec2f(uv.x, uv.y));
309 }
310 corner_to_uv_index[corner_index] = unique_uvs.size() - 1;
311 }
312 }
313 BKE_mesh_uv_vert_map_free(uv_vert_map);
314
315 /* Finally, build the USD indices array. */
316 pxr::VtIntArray indices;
317 indices.reserve(corner_verts.size());
318 for (const int corner_idx : corner_verts.index_range()) {
319 indices.push_back(corner_to_uv_index[corner_idx]);
320 }
321
322 const pxr::UsdTimeCode time = get_export_time_code();
323 const pxr::TfToken pv_name(
325 const pxr::UsdGeomPrimvarsAPI pv_api = pxr::UsdGeomPrimvarsAPI(usd_mesh);
326
327 pxr::UsdGeomPrimvar pv_uv = pv_api.CreatePrimvar(
328 pv_name, pxr::SdfValueTypeNames->TexCoord2fArray, pxr::UsdGeomTokens->faceVarying);
329 set_attribute(pv_uv, unique_uvs, time, usd_value_writer_);
330
331 pxr::UsdAttribute attr_indices = pv_uv.CreateIndicesAttr();
332 if (!attr_indices.HasValue()) {
333 attr_indices.Set(indices, time);
334 }
335 usd_value_writer_.SetAttribute(attr_indices, pxr::VtValue(indices), time);
336}
337
342
344 pxr::VtArray<pxr::GfVec3f> points;
345 pxr::VtIntArray face_vertex_counts;
346 pxr::VtIntArray face_indices;
348
349 /* The length of this array specifies the number of creases on the surface. Each element gives
350 * the number of (must be adjacent) vertices in each crease, whose indices are linearly laid out
351 * in the 'creaseIndices' attribute. Since each crease must be at least one edge long, each
352 * element of this array should be greater than one. */
353 pxr::VtIntArray crease_lengths;
354 /* The indices of all vertices forming creased edges. The size of this array must be equal to the
355 * sum of all elements of the 'creaseLengths' attribute. */
356 pxr::VtIntArray crease_vertex_indices;
357 /* The per-crease or per-edge sharpness for all creases (Usd.Mesh.SHARPNESS_INFINITE for a
358 * perfectly sharp crease). Since 'creaseLengths' encodes the number of vertices in each crease,
359 * the number of elements in this array will be either `len(creaseLengths)` or the sum over all X
360 * of `(creaseLengths[X] - 1)`. Note that while the RI spec allows each crease to have either a
361 * single sharpness or a value per-edge, USD will encode either a single sharpness per crease on
362 * a mesh, or sharpness's for all edges making up the creases on a mesh. */
363 pxr::VtFloatArray crease_sharpnesses;
364
365 /* The lengths of this array specifies the number of sharp corners (or vertex crease) on the
366 * surface. Each value is the index of a vertex in the mesh's vertex list. */
367 pxr::VtIntArray corner_indices;
368 /* The per-vertex sharpnesses. The lengths of this array must match that of `corner_indices`. */
369 pxr::VtFloatArray corner_sharpnesses;
370};
371
372void USDGenericMeshWriter::write_mesh(HierarchyContext &context,
373 Mesh *mesh,
374 const SubsurfModifierData *subsurfData)
375{
376 pxr::UsdTimeCode time = get_export_time_code();
377 pxr::UsdStageRefPtr stage = usd_export_context_.stage;
378 const pxr::SdfPath &usd_path = usd_export_context_.usd_path;
379
380 pxr::UsdGeomMesh usd_mesh = pxr::UsdGeomMesh::Define(stage, usd_path);
381 write_visibility(context, time, usd_mesh);
382
383 USDMeshData usd_mesh_data;
384 /* Ensure data exists if currently in edit mode. */
386 get_geometry_data(mesh, usd_mesh_data);
387
388 pxr::UsdAttribute attr_points = usd_mesh.CreatePointsAttr(pxr::VtValue(), true);
389 pxr::UsdAttribute attr_face_vertex_counts = usd_mesh.CreateFaceVertexCountsAttr(pxr::VtValue(),
390 true);
391 pxr::UsdAttribute attr_face_vertex_indices = usd_mesh.CreateFaceVertexIndicesAttr(pxr::VtValue(),
392 true);
393
394 if (!attr_points.HasValue()) {
395 /* Provide the initial value as default. This makes USD write the value as constant if they
396 * don't change over time. */
397 attr_points.Set(usd_mesh_data.points, pxr::UsdTimeCode::Default());
398 attr_face_vertex_counts.Set(usd_mesh_data.face_vertex_counts, pxr::UsdTimeCode::Default());
399 attr_face_vertex_indices.Set(usd_mesh_data.face_indices, pxr::UsdTimeCode::Default());
400 }
401
402 usd_value_writer_.SetAttribute(attr_points, pxr::VtValue(usd_mesh_data.points), time);
403 usd_value_writer_.SetAttribute(
404 attr_face_vertex_counts, pxr::VtValue(usd_mesh_data.face_vertex_counts), time);
405 usd_value_writer_.SetAttribute(
406 attr_face_vertex_indices, pxr::VtValue(usd_mesh_data.face_indices), time);
407
408 if (!usd_mesh_data.crease_lengths.empty()) {
409 pxr::UsdAttribute attr_crease_lengths = usd_mesh.CreateCreaseLengthsAttr(pxr::VtValue(), true);
410 pxr::UsdAttribute attr_crease_indices = usd_mesh.CreateCreaseIndicesAttr(pxr::VtValue(), true);
411 pxr::UsdAttribute attr_crease_sharpness = usd_mesh.CreateCreaseSharpnessesAttr(pxr::VtValue(),
412 true);
413
414 if (!attr_crease_lengths.HasValue()) {
415 attr_crease_lengths.Set(usd_mesh_data.crease_lengths, pxr::UsdTimeCode::Default());
416 attr_crease_indices.Set(usd_mesh_data.crease_vertex_indices, pxr::UsdTimeCode::Default());
417 attr_crease_sharpness.Set(usd_mesh_data.crease_sharpnesses, pxr::UsdTimeCode::Default());
418 }
419
420 usd_value_writer_.SetAttribute(
421 attr_crease_lengths, pxr::VtValue(usd_mesh_data.crease_lengths), time);
422 usd_value_writer_.SetAttribute(
423 attr_crease_indices, pxr::VtValue(usd_mesh_data.crease_vertex_indices), time);
424 usd_value_writer_.SetAttribute(
425 attr_crease_sharpness, pxr::VtValue(usd_mesh_data.crease_sharpnesses), time);
426 }
427
428 if (!usd_mesh_data.corner_indices.empty() &&
429 usd_mesh_data.corner_indices.size() == usd_mesh_data.corner_sharpnesses.size())
430 {
431 pxr::UsdAttribute attr_corner_indices = usd_mesh.CreateCornerIndicesAttr(pxr::VtValue(), true);
432 pxr::UsdAttribute attr_corner_sharpnesses = usd_mesh.CreateCornerSharpnessesAttr(
433 pxr::VtValue(), true);
434
435 if (!attr_corner_indices.HasValue()) {
436 attr_corner_indices.Set(usd_mesh_data.corner_indices, pxr::UsdTimeCode::Default());
437 attr_corner_sharpnesses.Set(usd_mesh_data.corner_sharpnesses, pxr::UsdTimeCode::Default());
438 }
439
440 usd_value_writer_.SetAttribute(
441 attr_corner_indices, pxr::VtValue(usd_mesh_data.corner_indices), time);
442 usd_value_writer_.SetAttribute(
443 attr_corner_sharpnesses, pxr::VtValue(usd_mesh_data.corner_sharpnesses), time);
444 }
445
446 write_custom_data(context.object, mesh, usd_mesh);
447 write_surface_velocity(mesh, usd_mesh);
448
449 const pxr::TfToken subdiv_scheme = get_subdiv_scheme(subsurfData);
450
451 /* Normals can be animated, so ensure these are written for each frame,
452 * unless a subdiv modifier is used, in which case normals are computed,
453 * not stored with the mesh. */
455 subdiv_scheme == pxr::UsdGeomTokens->none)
456 {
457 write_normals(mesh, usd_mesh);
458 }
459
460 this->author_extent(usd_mesh, mesh->bounds_min_max(), time);
461
462 /* TODO(Sybren): figure out what happens when the face groups change. */
464 return;
465 }
466
467 /* The subdivision scheme is a uniform according to spec,
468 * so this value cannot be animated. */
469 write_subdiv(subdiv_scheme, usd_mesh, subsurfData);
470
472 assign_materials(context, usd_mesh, usd_mesh_data.face_groups);
473 }
474}
475
476pxr::TfToken USDGenericMeshWriter::get_subdiv_scheme(const SubsurfModifierData *subsurfData)
477{
478 /* Default to setting the subdivision scheme to None. */
479 pxr::TfToken subdiv_scheme = pxr::UsdGeomTokens->none;
480
481 if (subsurfData) {
482 if (subsurfData->subdivType == SUBSURF_TYPE_CATMULL_CLARK) {
484 /* If a subdivision modifier exists, and it uses Catmull-Clark, then apply Catmull-Clark
485 * SubD scheme. */
486 subdiv_scheme = pxr::UsdGeomTokens->catmullClark;
487 }
488 }
489 else {
490 /* "Simple" is currently the only other subdivision type provided by Blender, */
491 /* and we do not yet provide a corresponding representation for USD export. */
494 "USD export: Simple subdivision not supported, exporting subdivided mesh");
495 }
496 }
497
498 return subdiv_scheme;
499}
500
501void USDGenericMeshWriter::write_subdiv(const pxr::TfToken &subdiv_scheme,
502 const pxr::UsdGeomMesh &usd_mesh,
503 const SubsurfModifierData *subsurfData)
504{
505 usd_mesh.CreateSubdivisionSchemeAttr().Set(subdiv_scheme);
506 if (subdiv_scheme == pxr::UsdGeomTokens->catmullClark) {
507 /* For Catmull-Clark, also consider the various interpolation modes. */
508 /* For reference, see
509 * https://graphics.pixar.com/opensubdiv/docs/subdivision_surfaces.html#face-varying-interpolation-rules
510 */
511 switch (subsurfData->uv_smooth) {
513 usd_mesh.CreateFaceVaryingLinearInterpolationAttr().Set(pxr::UsdGeomTokens->all);
514 break;
516 usd_mesh.CreateFaceVaryingLinearInterpolationAttr().Set(pxr::UsdGeomTokens->cornersOnly);
517 break;
519 usd_mesh.CreateFaceVaryingLinearInterpolationAttr().Set(pxr::UsdGeomTokens->cornersPlus1);
520 break;
522 usd_mesh.CreateFaceVaryingLinearInterpolationAttr().Set(pxr::UsdGeomTokens->cornersPlus2);
523 break;
525 usd_mesh.CreateFaceVaryingLinearInterpolationAttr().Set(pxr::UsdGeomTokens->boundaries);
526 break;
528 usd_mesh.CreateFaceVaryingLinearInterpolationAttr().Set(pxr::UsdGeomTokens->none);
529 break;
530 default:
531 BLI_assert_msg(0, "Unsupported UV smoothing mode.");
532 }
533
534 /* For reference, see
535 * https://graphics.pixar.com/opensubdiv/docs/subdivision_surfaces.html#boundary-interpolation-rules
536 */
537 switch (subsurfData->boundary_smooth) {
539 usd_mesh.CreateInterpolateBoundaryAttr().Set(pxr::UsdGeomTokens->edgeOnly);
540 break;
542 usd_mesh.CreateInterpolateBoundaryAttr().Set(pxr::UsdGeomTokens->edgeAndCorner);
543 break;
544 default:
545 BLI_assert_msg(0, "Unsupported boundary smoothing mode.");
546 }
547 }
548}
549
550static void get_positions(const Mesh *mesh, USDMeshData &usd_mesh_data)
551{
552 const Span<pxr::GfVec3f> positions = mesh->vert_positions().cast<pxr::GfVec3f>();
553 usd_mesh_data.points = pxr::VtArray<pxr::GfVec3f>(positions.begin(), positions.end());
554}
555
556static void get_loops_polys(const Mesh *mesh, USDMeshData &usd_mesh_data)
557{
558 /* Only construct face groups (a.k.a. geometry subsets) when we need them for material
559 * assignments. */
560 const bke::AttributeAccessor attributes = mesh->attributes();
561 const VArray<int> material_indices = *attributes.lookup_or_default<int>(
562 "material_index", bke::AttrDomain::Face, 0);
563 if (!material_indices.is_single() && mesh->totcol > 1) {
564 const VArraySpan<int> indices_span(material_indices);
565 for (const int i : indices_span.index_range()) {
566 usd_mesh_data.face_groups.lookup_or_add_default(indices_span[i]).push_back(i);
567 }
568 }
569
570 usd_mesh_data.face_vertex_counts.resize(mesh->faces_num);
571 const OffsetIndices faces = mesh->faces();
573 faces,
574 faces.index_range(),
575 MutableSpan(usd_mesh_data.face_vertex_counts.data(), mesh->faces_num));
576
577 const Span<int> corner_verts = mesh->corner_verts();
578 usd_mesh_data.face_indices = pxr::VtIntArray(corner_verts.begin(), corner_verts.end());
579}
580
581static void get_edge_creases(const Mesh *mesh, USDMeshData &usd_mesh_data)
582{
583 const bke::AttributeAccessor attributes = mesh->attributes();
584 const bke::AttributeReader attribute = attributes.lookup<float>("crease_edge",
586 if (!attribute) {
587 return;
588 }
589 const VArraySpan creases(*attribute);
590 const Span<int2> edges = mesh->edges();
591 for (const int i : edges.index_range()) {
592 const float crease = std::clamp(creases[i], 0.0f, 1.0f);
593
594 if (crease != 0.0f) {
595 usd_mesh_data.crease_vertex_indices.push_back(edges[i][0]);
596 usd_mesh_data.crease_vertex_indices.push_back(edges[i][1]);
597 usd_mesh_data.crease_lengths.push_back(2);
598 usd_mesh_data.crease_sharpnesses.push_back(bke::subdiv::crease_to_sharpness(crease));
599 }
600 }
601}
602
603static void get_vert_creases(const Mesh *mesh, USDMeshData &usd_mesh_data)
604{
605 const bke::AttributeAccessor attributes = mesh->attributes();
606 const bke::AttributeReader attribute = attributes.lookup<float>("crease_vert",
608 if (!attribute) {
609 return;
610 }
611 const VArraySpan creases(*attribute);
612 for (const int i : creases.index_range()) {
613 const float crease = std::clamp(creases[i], 0.0f, 1.0f);
614
615 if (crease != 0.0f) {
616 usd_mesh_data.corner_indices.push_back(i);
617 usd_mesh_data.corner_sharpnesses.push_back(bke::subdiv::crease_to_sharpness(crease));
618 }
619 }
620}
621
622void USDGenericMeshWriter::get_geometry_data(const Mesh *mesh, USDMeshData &usd_mesh_data)
623{
624 get_positions(mesh, usd_mesh_data);
625 get_loops_polys(mesh, usd_mesh_data);
626 get_edge_creases(mesh, usd_mesh_data);
627 get_vert_creases(mesh, usd_mesh_data);
628}
629
630void USDGenericMeshWriter::assign_materials(const HierarchyContext &context,
631 const pxr::UsdGeomMesh &usd_mesh,
632 const MaterialFaceGroups &usd_face_groups)
633{
634 const int totcol = BKE_object_material_count_eval(context.object);
635 if (totcol == 0) {
636 return;
637 }
638
639 /* Binding a material to a geometry subset isn't supported by the Hydra GL viewport yet,
640 * which is why we always bind the first material to the entire mesh. See
641 * https://github.com/PixarAnimationStudios/USD/issues/542 for more info. */
642 bool mesh_material_bound = false;
643 auto mesh_prim = usd_mesh.GetPrim();
644 pxr::UsdShadeMaterialBindingAPI material_binding_api(mesh_prim);
645 for (int mat_num = 0; mat_num < totcol; mat_num++) {
646 Material *material = BKE_object_material_get_eval(context.object, mat_num + 1);
647 if (material == nullptr) {
648 continue;
649 }
650
651 pxr::UsdShadeMaterial usd_material = ensure_usd_material(context, material);
652 material_binding_api.Bind(usd_material);
653
654 /* USD seems to support neither per-material nor per-face-group double-sidedness, so we just
655 * use the flag from the first non-empty material slot. */
656 usd_mesh.CreateDoubleSidedAttr(
657 pxr::VtValue((material->blend_flag & MA_BL_CULL_BACKFACE) == 0));
658
659 mesh_material_bound = true;
660 break;
661 }
662
663 if (mesh_material_bound) {
664 /* USD will require that prims with material bindings have the #MaterialBindingAPI applied
665 * schema. While Bind() above will create the binding attribute, Apply() needs to be called as
666 * well to add the #MaterialBindingAPI schema to the prim itself. */
667 pxr::UsdShadeMaterialBindingAPI::Apply(mesh_prim);
668 }
669 else {
670 /* Blender defaults to double-sided, but USD to single-sided. */
671 usd_mesh.CreateDoubleSidedAttr(pxr::VtValue(true));
672 }
673
674 if (!mesh_material_bound || usd_face_groups.size() < 2) {
675 /* Either all material slots were empty or there is only one material in use. As geometry
676 * subsets are only written when actually used to assign a material, and the mesh already has
677 * the material assigned, there is no need to continue. */
678 return;
679 }
680
681 /* Define a geometry subset per material. */
682 for (const MaterialFaceGroups::Item &face_group : usd_face_groups.items()) {
683 short material_number = face_group.key;
684 const pxr::VtIntArray &face_indices = face_group.value;
685
686 Material *material = BKE_object_material_get_eval(context.object, material_number + 1);
687 if (material == nullptr) {
688 continue;
689 }
690
691 pxr::UsdShadeMaterial usd_material = ensure_usd_material(context, material);
692 pxr::TfToken material_name = usd_material.GetPath().GetNameToken();
693
694 pxr::UsdGeomSubset usd_face_subset = material_binding_api.CreateMaterialBindSubset(
695 material_name, face_indices);
696 auto subset_prim = usd_face_subset.GetPrim();
697 auto subset_material_api = pxr::UsdShadeMaterialBindingAPI(subset_prim);
698 subset_material_api.Bind(usd_material);
699 /* Apply the #MaterialBindingAPI applied schema, as required by USD. */
700 pxr::UsdShadeMaterialBindingAPI::Apply(subset_prim);
701 }
702}
703
704void USDGenericMeshWriter::write_normals(const Mesh *mesh, pxr::UsdGeomMesh &usd_mesh)
705{
706 pxr::UsdTimeCode time = get_export_time_code();
707
708 Span<float3> src_normals;
709 pxr::VtVec3fArray loop_normals;
710 pxr::TfToken interpolation;
711 switch (mesh->normals_domain()) {
713 src_normals = mesh->vert_normals();
714 interpolation = pxr::UsdGeomTokens->vertex;
715 break;
716 }
718 src_normals = mesh->face_normals();
719 interpolation = pxr::UsdGeomTokens->uniform;
720 break;
721 }
723 src_normals = mesh->corner_normals();
724 interpolation = pxr::UsdGeomTokens->faceVarying;
725 break;
726 }
727 }
728
729 loop_normals.resize(src_normals.size());
730 MutableSpan dst_normals(reinterpret_cast<float3 *>(loop_normals.data()), loop_normals.size());
731 array_utils::copy(src_normals, dst_normals);
732 pxr::UsdAttribute attr_normals = usd_mesh.CreateNormalsAttr(pxr::VtValue(), true);
733 if (!attr_normals.HasValue()) {
734 attr_normals.Set(loop_normals, pxr::UsdTimeCode::Default());
735 }
736 usd_value_writer_.SetAttribute(attr_normals, pxr::VtValue(loop_normals), time);
737 usd_mesh.SetNormalsInterpolation(interpolation);
738}
739
740void USDGenericMeshWriter::write_surface_velocity(const Mesh *mesh,
741 const pxr::UsdGeomMesh &usd_mesh)
742{
743 /* Export velocity attribute output by fluid sim, sequence cache modifier
744 * and geometry nodes. */
745 const VArraySpan velocity = *mesh->attributes().lookup<float3>("velocity",
747 if (velocity.is_empty()) {
748 return;
749 }
750
751 /* Export per-vertex velocity vectors. */
752 Span<pxr::GfVec3f> data = velocity.cast<pxr::GfVec3f>();
753 pxr::VtVec3fArray usd_velocities;
754 usd_velocities.assign(data.begin(), data.end());
755
756 pxr::UsdTimeCode time = get_export_time_code();
757 pxr::UsdAttribute attr_vel = usd_mesh.CreateVelocitiesAttr(pxr::VtValue(), true);
758 if (!attr_vel.HasValue()) {
759 attr_vel.Set(usd_velocities, pxr::UsdTimeCode::Default());
760 }
761
762 usd_value_writer_.SetAttribute(attr_vel, usd_velocities, time);
763}
764
766 : USDGenericMeshWriter(ctx), write_skinned_mesh_(false), write_blend_shapes_(false)
767{
768}
769
771{
772 write_skinned_mesh_ = false;
773 write_blend_shapes_ = false;
774
776
777 /* We can write a skinned mesh if exporting armatures is enabled and the object has an armature
778 * modifier. */
779 write_skinned_mesh_ = params.export_armatures &&
781
782 /* We can write blend shapes if exporting shape keys is enabled and the object has shape keys. */
783 write_blend_shapes_ = params.export_shapekeys && is_mesh_with_shape_keys(context.object);
784}
785
787{
788 pxr::UsdStageRefPtr stage = usd_export_context_.stage;
789
790 pxr::UsdPrim mesh_prim = stage->GetPrimAtPath(usd_export_context_.usd_path);
791
792 if (!mesh_prim.IsValid()) {
793 CLOG_WARN(&LOG,
794 "%s: couldn't get valid mesh prim for mesh %s",
795 __func__,
796 usd_export_context_.usd_path.GetAsString().c_str());
797 return;
798 }
799
800 pxr::UsdSkelBindingAPI skel_api = pxr::UsdSkelBindingAPI::Apply(mesh_prim);
801
802 if (!skel_api) {
803 CLOG_WARN(&LOG,
804 "Couldn't apply UsdSkelBindingAPI to mesh prim %s",
805 usd_export_context_.usd_path.GetAsString().c_str());
806 return;
807 }
808
809 const Object *arm_obj = get_armature_modifier_obj(*context.object,
811
812 if (!arm_obj) {
813 CLOG_WARN(&LOG,
814 "Couldn't get armature modifier object for skinned mesh %s",
815 usd_export_context_.usd_path.GetAsString().c_str());
816 return;
817 }
818
819 Vector<StringRef> bone_names;
822
823 if (bone_names.is_empty()) {
824 CLOG_WARN(&LOG,
825 "No armature bones for skinned mesh %s",
826 usd_export_context_.usd_path.GetAsString().c_str());
827 return;
828 }
829
830 bool needsfree = false;
831 Mesh *mesh = get_export_mesh(context.object, needsfree);
832
833 if (mesh == nullptr) {
834 return;
835 }
836
837 try {
838 export_deform_verts(mesh, skel_api, bone_names);
839
840 if (needsfree) {
842 }
843 }
844 catch (...) {
845 if (needsfree) {
847 }
848 throw;
849 }
850}
851
853{
854 pxr::UsdStageRefPtr stage = usd_export_context_.stage;
855
856 pxr::UsdPrim mesh_prim = stage->GetPrimAtPath(usd_export_context_.usd_path);
857
858 if (!mesh_prim.IsValid()) {
859 CLOG_WARN(&LOG,
860 "Couldn't get valid mesh prim for mesh %s",
861 mesh_prim.GetPath().GetAsString().c_str());
862 return;
863 }
864
866 context.object,
867 mesh_prim,
869}
870
872{
873 set_skel_export_flags(context);
874
875 if (frame_has_been_written_ && (write_skinned_mesh_ || write_blend_shapes_)) {
876 /* When writing skinned meshes or blend shapes, we only write the rest mesh once,
877 * so we return early after the first frame has been written. However, we still
878 * update blend shape weights if needed. */
879 if (write_blend_shapes_) {
880 add_shape_key_weights_sample(context.object);
881 }
882 return;
883 }
884
886
887 if (write_skinned_mesh_) {
888 init_skinned_mesh(context);
889 }
890
891 if (write_blend_shapes_) {
892 init_blend_shapes(context);
893 add_shape_key_weights_sample(context.object);
894 }
895}
896
897Mesh *USDMeshWriter::get_export_mesh(Object *object_eval, bool &r_needsfree)
898{
899 if (write_blend_shapes_) {
900 r_needsfree = true;
901 /* We return the pre-modified mesh with the verts in the shape key
902 * basis positions. */
903 return get_shape_key_basis_mesh(object_eval);
904 }
905
906 if (write_skinned_mesh_) {
907 /* We must export the skinned mesh in its rest pose. We therefore
908 * return the pre-modified mesh, so that the armature modifier isn't
909 * applied. Objects without a pre-modified mesh of their own (curves,
910 * NURBS surfaces, ...) get one converted on demand. */
911 MeshCoerceForExport coerce;
913 coerce, usd_export_context_.depsgraph, object_eval, false);
914 r_needsfree = coerce.owned != nullptr;
915 coerce.owned = nullptr;
916 return const_cast<Mesh *>(mesh);
917 }
918
919 /* Return the fully evaluated mesh. */
920 r_needsfree = false;
921 return BKE_object_get_evaluated_mesh(object_eval);
922}
923
925{
926 if (!obj) {
927 return;
928 }
929
930 const Key *key = get_mesh_shape_key(obj);
931 if (!key) {
932 return;
933 }
934
935 pxr::UsdStageRefPtr stage = usd_export_context_.stage;
936
937 pxr::UsdPrim mesh_prim = stage->GetPrimAtPath(usd_export_context_.usd_path);
938
939 if (!mesh_prim.IsValid()) {
940 CLOG_WARN(&LOG,
941 "Couldn't get valid mesh prim for mesh %s",
942 usd_export_context_.usd_path.GetAsString().c_str());
943 return;
944 }
945
946 pxr::VtFloatArray weights = get_blendshape_weights(key);
947 pxr::UsdTimeCode time = get_export_time_code();
948
949 /* Save the weights samples to a temporary privar which will be copied to
950 * a skeleton animation later. */
951 pxr::UsdAttribute temp_weights_attr = pxr::UsdGeomPrimvarsAPI(mesh_prim).CreatePrimvar(
952 TempBlendShapeWeightsPrimvarName, pxr::SdfValueTypeNames->FloatArray);
953
954 if (!temp_weights_attr) {
955 CLOG_WARN(&LOG,
956 "Couldn't create primvar %s on prim %s",
958 mesh_prim.GetPath().GetAsString().c_str());
959 return;
960 }
961
962 temp_weights_attr.Set(weights, time);
963}
964
965} // namespace io::usd
966} // namespace blender
General operations, lookup, etc. for materials.
#define STD_UV_CONNECT_LIMIT
General operations, lookup, etc. for blender objects.
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
Object is a sort of wrapper for general info.
#define ELEM(...)
#define BLI_assert_msg(a, msg)
AttributeSet attributes
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
Value & lookup_or_add_default(const Key &key)
Definition BLI_map.hh:639
int64_t size() const
Definition BLI_map.hh:976
MapItem< short, pxr::VtArray< int > > Item
Definition BLI_map.hh:132
ItemIterator items() const &
Definition BLI_map.hh:902
constexpr const T * end() const
Definition BLI_span.hh:228
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
constexpr const T * begin() const
Definition BLI_span.hh:224
constexpr const char * c_str() const
bool is_empty() const
GAttributeReader lookup_or_default(StringRef name, AttrDomain domain, AttrType data_type, const void *default_value=nullptr) const
void foreach_attribute(const FunctionRef< void(const AttributeIter &)> fn) const
GAttributeReader lookup(const StringRef name) const
GAttributeReader get() const
constexpr IndexRange index_range() const
constexpr int64_t rfind(char c, int64_t pos=INT64_MAX) const
constexpr bool is_empty() const
pxr::UsdShadeMaterial ensure_usd_material(const HierarchyContext &context, Material *material) const
void author_extent(const pxr::UsdGeomBoundable &boundable, const pxr::UsdTimeCode time)
const pxr::SdfPath & usd_path() const
void add_to_prim_map(const pxr::SdfPath &usd_path, const ID *id) const
pxr::UsdTimeCode get_export_time_code() const
pxr::UsdUtilsSparseValueWriter usd_value_writer_
USDAbstractWriter(const USDExporterContext &usd_export_context)
void write_id_properties(const pxr::UsdPrim &prim, const ID &id, pxr::UsdTimeCode=pxr::UsdTimeCode::Default()) const
void write_visibility(const HierarchyContext &context, const pxr::UsdTimeCode time, const pxr::UsdGeomImageable &usd_geometry)
const USDExporterContext usd_export_context_
USDGenericMeshWriter(const USDExporterContext &ctx)
void do_write(HierarchyContext &context) override
bool is_supported(const HierarchyContext *context) const override
virtual Mesh * get_export_mesh(Object *object_eval, bool &r_needsfree)=0
virtual void free_export_mesh(Mesh *mesh)
void do_write(HierarchyContext &context) override
USDMeshWriter(const USDExporterContext &ctx)
void add_shape_key_weights_sample(const Object *obj)
void init_skinned_mesh(const HierarchyContext &context)
void init_blend_shapes(const HierarchyContext &context)
Mesh * get_export_mesh(Object *object_eval, bool &r_needsfree) override
void set_skel_export_flags(const HierarchyContext &context)
#define attribute(slot)
bool all(VecOp< bool, D >) RET
void copy(const GVArray &src, GMutableSpan dst, exec_mode::Mode mode=exec_mode::parallel)
BLI_INLINE float crease_to_sharpness(float crease)
bool attribute_name_is_anonymous(const StringRef name)
std::string time(const std::tm &date_time, TimeFormat format=TimeFormat::H24)
int context(const bContext *C, const char *member, bContextDataResult *result)
void get_positions(const Span< float3 > positions, std::vector< Imath::V3f > &points)
static void get_loops_polys(const Mesh *mesh, USDMeshData &usd_mesh_data)
static const SubsurfModifierData * get_last_subdiv_modifier(eEvaluationMode eval_mode, Object *obj)
static void get_vert_creases(const Mesh *mesh, USDMeshData &usd_mesh_data)
Map< short, pxr::VtArray< int > > MaterialFaceGroups
void copy_blender_attribute_to_primvar(const GVArray &attribute, const bke::AttrType data_type, const pxr::UsdTimeCode time, const pxr::UsdGeomPrimvar &primvar, pxr::UsdUtilsSparseValueWriter &value_writer)
void get_armature_bone_names(const Object *ob_arm, const bool use_deform, Vector< StringRef > &r_names)
void export_deform_verts(const Mesh *mesh, const pxr::UsdSkelBindingAPI &skel_api, const Span< StringRef > bone_names)
std::optional< pxr::SdfValueTypeName > convert_blender_type_to_usd(const bke::AttrType blender_type, bool use_color3f_type)
static void get_positions(const Mesh *mesh, USDMeshData &usd_mesh_data)
bool is_armature_modifier_bone_name(const Object &obj, const StringRefNull name, const Depsgraph *depsgraph)
static std::optional< pxr::TfToken > convert_blender_domain_to_usd(const bke::AttrDomain blender_domain, bool is_bezier)
void create_blend_shapes(pxr::UsdStageRefPtr stage, const Object *obj, const pxr::UsdPrim &mesh_prim, bool allow_unicode)
const Key * get_mesh_shape_key(const Object *obj)
static void get_edge_creases(const Mesh *mesh, USDMeshData &usd_mesh_data)
pxr::TfToken TempBlendShapeWeightsPrimvarName
void set_attribute(const pxr::UsdAttribute &attr, const USDT value, pxr::UsdTimeCode time, pxr::UsdUtilsSparseValueWriter &value_writer)
const Object * get_armature_modifier_obj(const Object &obj, const Depsgraph *depsgraph)
pxr::VtFloatArray get_blendshape_weights(const Key *key)
bool can_export_skinned_mesh(const Object &obj, const Depsgraph *depsgraph)
std::string make_safe_primvar_name(const StringRef name, bool allow_unicode)
Definition usd_utils.cc:88
Mesh * get_shape_key_basis_mesh(Object *obj)
bool is_mesh_with_shape_keys(const Object *obj)
const Mesh * mesh_coerce_for_export_setup(MeshCoerceForExport &coerce, Depsgraph *depsgraph, Object *obj_eval, const bool apply_modifiers)
Definition mesh_utils.cc:19
void copy_group_sizes(OffsetIndices< int > offsets, const IndexMask &mask, MutableSpan< int > sizes)
const pxr::TfToken displayColor("displayColor", pxr::TfToken::Immortal)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
void BKE_mesh_uv_vert_map_free(UvVertMap *vmap)
int BKE_object_material_count_eval(const Object *ob)
@ RPT_WARNING
Definition BKE_report.hh:40
void BM_mesh_free(BMesh *bm)
BMesh Free Mesh.
UvMapVert * BKE_mesh_uv_vert_map_get_vert(UvVertMap *vmap, unsigned int v)
@ SUBSURF_UV_SMOOTH_PRESERVE_CORNERS_AND_JUNCTIONS
@ SUBSURF_UV_SMOOTH_PRESERVE_BOUNDARIES
@ SUBSURF_UV_SMOOTH_PRESERVE_CORNERS
@ SUBSURF_UV_SMOOTH_PRESERVE_CORNERS_JUNCTIONS_AND_CONCAVE
void BKE_mesh_wrapper_ensure_mdata(Mesh *mesh)
const char * BKE_id_name(const ID &id)
VecBase< float, 2 > float2
BMesh * BKE_mesh_to_bmesh_ex(const Mesh *mesh, const BMeshCreateParams *create_params, const BMeshFromMeshParams *convert_params)
BMesh const char void * data
UvVertMap * BKE_mesh_uv_vert_map_create(OffsetIndices< int > faces, Span< int > corner_verts, Span< float2 > uv_map, int verts_num, const float2 &limit, bool use_winding)
void BKE_id_free(Main *bmain, void *idv)
void BKE_reportf(ReportList *reports, eReportType type, const char *format,...) ATTR_PRINTF_FORMAT(3
Definition report.cc:191
Mesh * BKE_mesh_from_bmesh_for_eval_nomain(BMesh *bm, const CustomData_MeshMasks *cd_mask_extra, const Mesh *me_settings)
@ SUBSURF_BOUNDARY_SMOOTH_PRESERVE_CORNERS
@ SUBSURF_BOUNDARY_SMOOTH_ALL
Material * BKE_object_material_get_eval(Object *ob, short act)
static CLG_LogRef LOG
Definition logging.cpp:12
void BM_mesh_triangulate(BMesh *bm, const int quad_method, const int ngon_method, const int min_vertices, const bool tag_only, BMOperator *op, BMOpSlot *slot_facemap_out, BMOpSlot *slot_facemap_double_out)
VecBase< float, 3 > float3
signed char int8_t
Definition BKE_text.h:76
Mesh * BKE_object_get_evaluated_mesh(const Object *object_eval)
Definition object.cc:4436
PipelineCompute loop_normals(loop_normals_main)
eObject_DuplicatorVisibilityFlag duplicator_visibility_flag
enum eEvaluationMode evaluation_mode
Definition usd.hh:149
SubdivExportMode export_subdiv
Definition usd.hh:148
pxr::VtArray< pxr::GfVec3f > points
float x
float y