Blender V5.3
usd_reader_nurbs.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2021 Tangent Animation. All rights reserved.
2 * SPDX-FileCopyrightText: 2023 Blender Authors
3 *
4 * SPDX-License-Identifier: GPL-2.0-or-later
5 *
6 * Adapted from the Blender Alembic importer implementation. */
7
8#include "usd_reader_nurbs.hh"
9
10#include "BKE_curves.hh"
11
12#include "BLI_offset_indices.hh"
13#include "BLI_span.hh"
14
15#include "DNA_curves_types.h"
16
17#include <pxr/base/vt/types.h>
18
19#include <pxr/usd/usdGeom/curves.h>
20#include <pxr/usd/usdGeom/primvarsAPI.h>
21
22#include <algorithm>
23
24#include "CLG_log.h"
25
26namespace blender {
27
28static CLG_LogRef LOG = {"io.usd"};
29
30namespace io::usd {
31
32/* Store incoming USD data privately and expose Blender-friendly Spans publicly. */
34 private:
35 pxr::VtArray<pxr::GfVec3f> points_;
36 pxr::VtArray<int> counts_;
37 pxr::VtArray<int> orders_;
38 pxr::VtArray<double> knots_;
39 pxr::VtArray<double> weights_;
40 pxr::VtArray<float> widths_;
41 pxr::VtArray<pxr::GfVec3f> velocities_;
42
43 public:
45 {
46 return Span(points_.cdata(), points_.size()).cast<float3>();
47 }
49 {
50 return Span(counts_.cdata(), counts_.size());
51 }
53 {
54 return Span(orders_.cdata(), orders_.size());
55 }
57 {
58 return Span(knots_.cdata(), knots_.size());
59 }
61 {
62 return Span(weights_.cdata(), weights_.size());
63 }
65 {
66 return Span(widths_.cdata(), widths_.size());
67 }
69 {
70 return Span(velocities_.cdata(), velocities_.size()).cast<float3>();
71 }
72
73 bool load(const pxr::UsdGeomNurbsCurves &curve_prim, const pxr::UsdTimeCode time)
74 {
75 curve_prim.GetCurveVertexCountsAttr().Get(&counts_, time);
76 curve_prim.GetOrderAttr().Get(&orders_, time);
77
78 if (counts_.size() != orders_.size()) {
80 "Curve vertex and order size mismatch for NURBS prim %s",
81 curve_prim.GetPrim().GetPrimPath().GetAsString().c_str());
82 return false;
83 }
84
85 if (std::any_of(counts_.cbegin(), counts_.cend(), [](int value) { return value < 0; }) ||
86 std::any_of(orders_.cbegin(), orders_.cend(), [](int value) { return value < 0; }))
87 {
89 "Invalid curve vertex count or order value detected for NURBS prim %s",
90 curve_prim.GetPrim().GetPrimPath().GetAsString().c_str());
91 return false;
92 }
93
94 curve_prim.GetPointsAttr().Get(&points_, time);
95 curve_prim.GetKnotsAttr().Get(&knots_, time);
96 curve_prim.GetWidthsAttr().Get(&widths_, time);
97
98 curve_prim.GetPointWeightsAttr().Get(&weights_, time);
99 if (!weights_.empty() && points_.size() != weights_.size()) {
100 CLOG_WARN(&LOG,
101 "Invalid curve weights count for NURBS prim %s",
102 curve_prim.GetPrim().GetPrimPath().GetAsString().c_str());
103
104 /* Only clear, but continue to load other curve data. */
105 weights_.clear();
106 }
107
108 curve_prim.GetVelocitiesAttr().Get(&velocities_, time);
109 if (!velocities_.empty() && points_.size() != velocities_.size()) {
110 CLOG_WARN(&LOG,
111 "Invalid curve velocity count for NURBS prim %s",
112 curve_prim.GetPrim().GetPrimPath().GetAsString().c_str());
113
114 /* Only clear, but continue to load other curve data. */
115 velocities_.clear();
116 }
117
118 return true;
119 }
120};
121
128
130 const int order,
131 const bool is_cyclic)
132{
133 /* TODO: We have to convert knot values to float for usage in Blender APIs. Look into making
134 * calculate_multiplicity_sequence a template. */
135 Array<float> blender_knots(usd_knots.size());
136 for (const int knot_i : usd_knots.index_range()) {
137 blender_knots[knot_i] = float(usd_knots[knot_i]);
138 }
139
141 if (multiplicity.size() < 2) {
142 /* Invalid knot vector. Use normal mode. */
144 }
145
146 const int head = multiplicity.first();
147 const int tail = multiplicity.last();
148 const Span<int> inner = multiplicity.as_span().slice(1, multiplicity.size() - 2);
149
150 /* If the knot vector starts and ends with full multiplicity knots, then this is classified as
151 * Blender's endpoint mode. */
152 const int degree = order - 1;
153 const bool is_endpoint = is_cyclic ? (tail >= degree) : (head == order && tail >= order);
154
155 /* If all of the inner multiplicities are equal to the degree, then this is a Bezier curve. */
156 if (degree > 1 &&
157 std::all_of(inner.begin(), inner.end(), [degree](int value) { return value == degree; }))
158 {
160 }
161
162 if (is_endpoint) {
164 }
165
166 /* If all of the inner knot values are equally spaced, then this is a regular/uniform curve and
167 * we assume that our normal knot mode will match. Use custom knots otherwise. */
168 const Span<float> inner_values = blender_knots.as_span().drop_front(head).drop_back(tail);
169 if (inner_values.size() > 2) {
170 const float delta = inner_values[1] - inner_values[0];
171 if (delta < 0) {
172 /* Invalid knot vector. Use normal mode. */
174 }
175 for (int i = 2; i < inner.size(); i++) {
176 if (inner_values[i] - inner_values[i - 1] != delta) {
177 /* The knot values are not equally spaced. Use custom knots. */
179 }
180 }
181 }
182
183 /* Nothing matches. Use normal mode. */
185}
186
188 const Span<int> usd_counts,
189 const Span<int> usd_orders,
190 const Span<double> usd_knots)
191{
193 data.blender_offsets.reinitialize(usd_counts.size() + 1);
194 data.usd_offsets.reinitialize(usd_counts.size() + 1);
195 data.usd_knot_offsets.reinitialize(usd_counts.size() + 1);
196 data.is_cyclic.reinitialize(usd_counts.size());
197
198 Span<float3> usd_remaining_points = usd_points;
199 Span<double> usd_remaining_knots = usd_knots;
200
201 for (const int curve_i : usd_counts.index_range()) {
202 const int points_num = usd_counts[curve_i];
203 const int knots_num = points_num + usd_orders[curve_i];
204 const int degree = usd_orders[curve_i] - 1;
205 const Span<double> usd_current_knots = usd_remaining_knots.take_front(knots_num);
206 const Span<float3> usd_current_points = usd_remaining_points.take_front(points_num);
207 if (knots_num < 4 || knots_num != usd_current_knots.size()) {
208 data.is_cyclic[curve_i] = false;
209 }
210 else {
211 data.is_cyclic[curve_i] = usd_current_points.take_front(degree) ==
212 usd_current_points.take_back(degree);
213 }
214
215 int blender_count = usd_counts[curve_i];
216
217 /* Account for any repeated degree(order - 1) number of points from USD cyclic curves which
218 * Blender does not use internally. */
219 if (data.is_cyclic[curve_i]) {
220 blender_count -= degree;
221 }
222
223 data.blender_offsets[curve_i] = blender_count;
224 data.usd_offsets[curve_i] = points_num;
225 data.usd_knot_offsets[curve_i] = knots_num;
226
227 /* Move to next sequence of values. */
228 usd_remaining_points = usd_remaining_points.drop_front(points_num);
229 usd_remaining_knots = usd_remaining_knots.drop_front(knots_num);
230 }
231
235 return data;
236}
237
239static bool curves_topology_changed(const bke::CurvesGeometry &curves, const Span<int> usd_offsets)
240{
241 if (curves.offsets() != usd_offsets) {
242 return true;
243 }
244
245 return false;
246}
247
249 IndexRange usd_points_range)
250{
251 /* Take from the front of USD's range to exclude any duplicates at the end. */
252 return usd_points_range.take_front(blender_points_range.size());
253};
254
256{
257 if (curve_prim_.GetPointsAttr().ValueMightBeTimeVarying() ||
258 curve_prim_.GetWidthsAttr().ValueMightBeTimeVarying() ||
259 curve_prim_.GetPointWeightsAttr().ValueMightBeTimeVarying())
260 {
261 return true;
262 }
263
264 pxr::UsdGeomPrimvarsAPI pv_api(curve_prim_);
265 for (const pxr::UsdGeomPrimvar &pv : pv_api.GetPrimvarsWithValues()) {
266 if (pv.ValueMightBeTimeVarying()) {
267 return true;
268 }
269 }
270
271 return false;
272}
273
274void USDNurbsReader::read_curve_sample(Curves *curves_id, const pxr::UsdTimeCode time)
275{
276 USDCurveData usd_data;
277 if (!usd_data.load(curve_prim_, time)) {
278 return;
279 }
280
281 const Span<float3> usd_points = usd_data.points();
282 const Span<int> usd_counts = usd_data.counts();
283 const Span<int> usd_orders = usd_data.orders();
284 const Span<double> usd_knots = usd_data.knots();
285 const Span<double> usd_weights = usd_data.weights();
286 const Span<float3> usd_velocities = usd_data.velocities();
287
288 /* Calculate and set the Curves topology. */
289 CurveData data = calc_curve_offsets(usd_points, usd_counts, usd_orders, usd_knots);
290
291 // Check validity of curve counts
292 const bool all_valid = std::all_of(usd_counts.begin(), usd_counts.end(), [](int count) {
293 const int min_points = 2;
294 return count >= min_points;
295 });
296
297 bke::CurvesGeometry &curves = curves_id->geometry.wrap();
298 if (all_valid && curves_topology_changed(curves, data.blender_offsets)) {
299 curves.resize(data.blender_offsets.last(), usd_counts.size());
300 }
301
302 // Early out if there are no curves to load.
303 if (curves.is_empty()) {
304 return;
305 }
306
307 curves.offsets_for_write().copy_from(data.blender_offsets);
308 curves.fill_curve_types(CurveType::CURVE_TYPE_NURBS);
309
310 MutableSpan<float3> curves_positions = curves.positions_for_write();
311
312 /* If there's no points defined, fill positions with default values and exit. */
313 if (usd_points.is_empty()) {
314 curves_positions.fill(float3(0.0f, 0.0f, 0.0f));
315 return;
316 }
317
318 /* NOTE: USD contains duplicated points for periodic(cyclic) curves. The indices into each curve
319 * will differ from what Blender expects so we need to maintain and use separate offsets for
320 * each. A side effect of this dissonance is that all primvar/attribute loading needs to be
321 * handled in a special manner vs. what might be seen in our other USD readers. */
322 const OffsetIndices blender_points_by_curve = curves.points_by_curve();
323 const OffsetIndices usd_points_by_curve = OffsetIndices<int>(data.usd_offsets,
325 const OffsetIndices usd_knots_by_curve = OffsetIndices<int>(data.usd_knot_offsets,
327
328 /* TODO: We cannot read custom primvars for cyclic curves at the moment. */
329 const bool can_read_primvars = std::all_of(
330 data.is_cyclic.begin(), data.is_cyclic.end(), [](bool item) { return item == false; });
331
332 /* Set all curve data. */
333 for (const int curve_i : blender_points_by_curve.index_range()) {
334 const IndexRange blender_points_range = blender_points_by_curve[curve_i];
335 const IndexRange usd_points_range_de_dup = get_usd_points_range_de_dup(
336 blender_points_range, usd_points_by_curve[curve_i]);
337
338 const int copy_size = std::min(
339 {usd_points.size(), blender_points_range.size(), usd_points_range_de_dup.size()});
340 curves_positions.slice(blender_points_range.start(), copy_size)
341 .copy_from(usd_points.slice(usd_points_range_de_dup.start(), copy_size));
342 /* Fill any missing items with a default value. */
343 for (int i = copy_size; i < blender_points_range.size(); i++) {
344 curves_positions[blender_points_range.start() + i] = float3(0.0f, 0.0f, 0.0f);
345 }
346 }
347
348 MutableSpan<bool> curves_cyclic = curves.cyclic_for_write();
349 curves_cyclic.copy_from(data.is_cyclic);
350
351 MutableSpan<int8_t> curves_nurbs_orders = curves.nurbs_orders_for_write();
352 for (const int curve_i : blender_points_by_curve.index_range()) {
353 const int order = usd_orders[curve_i];
354 curves_nurbs_orders[curve_i] = int8_t(order >= 2 ? order : 2);
355 }
356
357 MutableSpan<int8_t> curves_knots_mode = curves.nurbs_knots_modes_for_write();
358 for (const int curve_i : blender_points_by_curve.index_range()) {
359 const IndexRange usd_knots_range = usd_knots_by_curve[curve_i];
360 curves_knots_mode[curve_i] = determine_knots_mode(
361 usd_knots.slice_safe(usd_knots_range), usd_orders[curve_i], data.is_cyclic[curve_i]);
362 }
363
364 /* Load in the optional weights. */
365 if (!usd_weights.is_empty()) {
366 MutableSpan<float> curves_weights = curves.nurbs_weights_for_write();
367 for (const int curve_i : blender_points_by_curve.index_range()) {
368 const IndexRange blender_points_range = blender_points_by_curve[curve_i];
369 const IndexRange usd_points_range_de_dup = get_usd_points_range_de_dup(
370 blender_points_range, usd_points_by_curve[curve_i]);
371
372 const Span<double> usd_weights_de_dup = usd_weights.slice(usd_points_range_de_dup);
373 int64_t usd_point_i = 0;
374 for (const int point_i : blender_points_range) {
375 curves_weights[point_i] = float(usd_weights_de_dup[usd_point_i]);
376 usd_point_i++;
377 }
378 }
379 }
380
381 /* Load in the optional velocities. */
382 if (!usd_velocities.is_empty()) {
383 bke::MutableAttributeAccessor attributes = curves.attributes_for_write();
384 bke::SpanAttributeWriter<float3> curves_velocity =
386
387 for (const int curve_i : blender_points_by_curve.index_range()) {
388 const IndexRange blender_points_range = blender_points_by_curve[curve_i];
389 const IndexRange usd_points_range_de_dup = get_usd_points_range_de_dup(
390 blender_points_range, usd_points_by_curve[curve_i]);
391
392 curves_velocity.span.slice(blender_points_range)
393 .copy_from(usd_velocities.slice(usd_points_range_de_dup));
394 }
395
396 curves_velocity.finish();
397 }
398
399 /* Once all of the curves metadata (orders, cyclic, knots_mode) has been set, we can prepare
400 * Blender for any custom knots that need to be loaded. */
401 MutableSpan<float> blender_custom_knots;
402 OffsetIndices<int> blender_knots_by_curve;
403 for (const int curve_i : curves.curves_range()) {
404 if (curves_knots_mode[curve_i] != NURBS_KNOT_MODE_CUSTOM) {
405 continue;
406 }
407
408 /* If this is our first time through, we need to update Blender's topology data to prepare for
409 * the incoming custom knots. */
410 if (blender_custom_knots.is_empty()) {
411 curves.nurbs_custom_knots_update_size();
412 blender_knots_by_curve = curves.nurbs_custom_knots_by_curve();
413 blender_custom_knots = curves.nurbs_custom_knots_for_write();
414 }
415
416 const IndexRange blender_knots_range = blender_knots_by_curve[curve_i];
417 const IndexRange usd_knots_range = usd_knots_by_curve[curve_i];
418 const Span<double> usd_knots_values = usd_knots.slice(usd_knots_range);
419 MutableSpan<float> blender_knots = blender_custom_knots.slice(blender_knots_range);
420 int usd_knot_i = 0;
421 for (float &blender_knot : blender_knots) {
422 blender_knot = usd_knots_values[usd_knot_i] > 0.0 ? float(usd_knots_values[usd_knot_i]) : 0;
423 usd_knot_i++;
424 }
425 }
426
427 /* Curve widths. */
428 const Span<float> usd_widths = usd_data.widths();
429 if (!usd_widths.is_empty()) {
430 MutableSpan<float> radii = curves.radius_for_write();
431
432 const pxr::TfToken widths_interp = curve_prim_.GetWidthsInterpolation();
433 if (widths_interp == pxr::UsdGeomTokens->constant || usd_widths.size() == 1) {
434 radii.fill(usd_widths[0] / 2.0f);
435 }
436 else if (widths_interp == pxr::UsdGeomTokens->varying) {
437 int point_offset = 0;
438 for (const int curve_i : curves.curves_range()) {
439 const float usd_curve_radius = usd_widths[curve_i] / 2.0f;
440 int point_count = usd_counts[curve_i];
441 if (curves_cyclic[curve_i]) {
442 point_count -= usd_orders[curve_i] - 1;
443 }
444 for (const int point : IndexRange(point_count)) {
445 radii[point_offset + point] = usd_curve_radius;
446 }
447
448 point_offset += point_count;
449 }
450 }
451 else if (widths_interp == pxr::UsdGeomTokens->vertex) {
452 for (const int curve_i : curves.curves_range()) {
453 const IndexRange blender_points_range = blender_points_by_curve[curve_i];
454 const IndexRange usd_points_range = usd_points_by_curve[curve_i];
455
456 /* Take from the front of USD's range to exclude any duplicates at the end. */
457 const IndexRange usd_points_range_de_dup = usd_points_range.take_front(
458 blender_points_range.size());
459
460 const Span<float> usd_widths_de_dup = usd_widths.slice(usd_points_range_de_dup);
461 int64_t usd_point_i = 0;
462 for (const int point_i : blender_points_range) {
463 radii[point_i] = usd_widths_de_dup[usd_point_i] / 2.0f;
464 usd_point_i++;
465 }
466 }
467 }
468 }
469
470 if (can_read_primvars) {
471 this->read_custom_data(curves, time);
472 }
473}
474
475} // namespace io::usd
476} // namespace blender
Low-level operations for curves.
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
Span< T > as_span() const
Definition BLI_array.hh:254
constexpr int64_t size() const
constexpr IndexRange()=default
constexpr int64_t start() const
constexpr IndexRange take_front(int64_t n) const
constexpr MutableSpan slice(const int64_t start, const int64_t size) const
Definition BLI_span.hh:579
constexpr bool is_empty() const
Definition BLI_span.hh:515
constexpr void fill(const T &value) const
Definition BLI_span.hh:523
constexpr void copy_from(Span< T > values) const
Definition BLI_span.hh:745
constexpr Span drop_front(int64_t n) const
Definition BLI_span.hh:175
constexpr Span slice_safe(const int64_t start, const int64_t size) const
Definition BLI_span.hh:158
constexpr Span slice(int64_t start, int64_t size) const
Definition BLI_span.hh:141
constexpr Span take_back(int64_t n) const
Definition BLI_span.hh:208
constexpr Span()=default
constexpr int64_t size() const
Definition BLI_span.hh:256
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 Span take_front(int64_t n) const
Definition BLI_span.hh:197
constexpr bool is_empty() const
Definition BLI_span.hh:264
int64_t size() const
const T & last(const int64_t n=0) const
Span< T > as_span() const
const T & first() const
GSpanAttributeWriter lookup_or_add_for_write_only_span(StringRef name, AttrDomain domain, AttrType data_type)
void read_custom_data(bke::CurvesGeometry &curves, const pxr::UsdTimeCode time) const
void read_curve_sample(Curves *curves_id, pxr::UsdTimeCode time) override
#define vertex
Vector< int > calculate_multiplicity_sequence(Span< float > knots)
static Array< int > calc_curve_offsets(const pxr::VtIntArray &usdCounts, const CurveType curve_type, bool is_cyclic)
static IndexRange get_usd_points_range_de_dup(IndexRange blender_points_range, IndexRange usd_points_range)
static CurveData calc_curve_offsets(const Span< float3 > usd_points, const Span< int > usd_counts, const Span< int > usd_orders, const Span< double > usd_knots)
static KnotsMode determine_knots_mode(const Span< double > usd_knots, const int order, const bool is_cyclic)
static bool curves_topology_changed(const bke::CurvesGeometry &curves, const Span< int > usd_offsets)
OffsetIndices< int > accumulate_counts_to_offsets(MutableSpan< int > counts_to_offsets, int start_offset=0)
BMesh Iterators.
__int64 int64_t
Definition BKE_text.h:90
@ NURBS_KNOT_MODE_ENDPOINT_BEZIER
@ NURBS_KNOT_MODE_BEZIER
@ NURBS_KNOT_MODE_ENDPOINT
@ NURBS_KNOT_MODE_NORMAL
@ NURBS_KNOT_MODE_CUSTOM
BMesh const char void * data
static CLG_LogRef LOG
Definition logging.cpp:12
VecBase< float, 3 > float3
signed char int8_t
Definition BKE_text.h:76
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
bool load(const pxr::UsdGeomNurbsCurves &curve_prim, const pxr::UsdTimeCode time)
Span< float3 > points() const
Span< float3 > velocities() const
Span< double > weights() const