Blender V5.3
io/usd/hydra/curves.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2011-2022 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#include "curves.hh"
6
7#include <pxr/imaging/hd/basisCurvesSchema.h>
8#include <pxr/imaging/hd/basisCurvesTopologySchema.h>
9#include <pxr/imaging/hd/materialBindingSchema.h>
10#include <pxr/imaging/hd/materialBindingsSchema.h>
11#include <pxr/imaging/hd/primvarSchema.h>
12#include <pxr/imaging/hd/primvarsSchema.h>
13#include <pxr/imaging/hd/retainedDataSource.h>
14#include <pxr/imaging/hd/tokens.h>
15
17#include "BLI_math_matrix_c.hh"
18#include "BLI_string.hh"
19
20#include "BKE_attribute.hh"
21#include "BKE_curves.hh"
22#include "BKE_customdata.hh"
23#include "BKE_material.hh"
24#include "BKE_particle.h"
25
27
28#include "DNA_curves_types.h"
29#include "DNA_mesh_types.h"
30#include "DNA_meshdata_types.h"
31#include "DNA_modifier_types.h"
32#include "DNA_object_types.h"
33#include "DNA_particle_types.h"
34
35#include "populate_context.hh"
36#include "util.hh"
37
38namespace blender::io::hydra {
39
40static const pxr::TfToken usd_st_token("st", pxr::TfToken::Immortal);
41
43 pxr::VtIntArray curve_vertex_counts;
44 pxr::VtVec3fArray points;
45 pxr::VtFloatArray widths;
46 pxr::VtVec2fArray uvs;
47};
48
50{
52 const Curves *curves_id = id_cast<const Curves *>(object->data);
53 const bke::CurvesGeometry &curves = curves_id->geometry.wrap();
54
55 r.curve_vertex_counts.resize(curves.curves_num());
57 curves.points_by_curve(),
58 curves.curves_range(),
60
61 const Span<float3> positions = curves.positions();
62 resize_uninitialized(r.points, positions.size());
63 for (const int i : positions.index_range()) {
64 const float3 &p = positions[i];
65 r.points[i] = pxr::GfVec3f(p.x, p.y, p.z);
66 }
67
68 const VArray<float> radii = *curves.attributes().lookup_or_default<float>(
69 "radius", bke::AttrDomain::Point, 0.01f);
70 resize_uninitialized(r.widths, curves.points_num());
71 for (const int i : curves.points_range()) {
72 r.widths[i] = radii[i] * 2.0f;
73 }
74
75 const std::optional<Span<float2>> surface_uv_coords = curves.surface_uv_coords();
76 if (surface_uv_coords) {
77 const int total = curves.curves_num();
78 const int n = std::min<int>(surface_uv_coords->size(), total);
79 resize_uninitialized(r.uvs, total);
80 for (const int i : IndexRange(n)) {
81 const float2 &uv = (*surface_uv_coords)[i];
82 r.uvs[i] = pxr::GfVec2f(uv.x, uv.y);
83 }
84 for (const int i : IndexRange(n, total - n)) {
85 r.uvs[i] = pxr::GfVec2f(0.0f, 0.0f);
86 }
87 }
88 return r;
89}
90
91/* Build the geometry-only schema sources for one basisCurves prim. */
93 const pxr::SdfPath &material_path)
94{
96 out.schema_token = pxr::HdBasisCurvesSchema::GetSchemaToken();
97
98 pxr::HdContainerDataSourceHandle topology =
99 pxr::HdBasisCurvesTopologySchema::Builder()
100 .SetCurveVertexCounts(
101 pxr::HdRetainedTypedSampledDataSource<pxr::VtIntArray>::New(r.curve_vertex_counts))
102 .SetBasis(pxr::HdRetainedTypedSampledDataSource<pxr::TfToken>::New(pxr::TfToken()))
103 .SetType(pxr::HdRetainedTypedSampledDataSource<pxr::TfToken>::New(pxr::HdTokens->linear))
104 .SetWrap(
105 pxr::HdRetainedTypedSampledDataSource<pxr::TfToken>::New(pxr::HdTokens->nonperiodic))
106 .Build();
107 out.geometry = pxr::HdBasisCurvesSchema::Builder().SetTopology(topology).Build();
108
109 /* Primvars: points (vertex), widths (vertex), st (uniform). */
110 HdContainerBuilder primvars;
111
112 if (!r.points.empty()) {
113 primvars.add(
114 pxr::HdPrimvarsSchemaTokens->points,
115 pxr::HdPrimvarSchema::Builder()
116 .SetPrimvarValue(
117 pxr::HdRetainedTypedSampledDataSource<pxr::VtVec3fArray>::New(r.points))
118 .SetInterpolation(pxr::HdPrimvarSchema::BuildInterpolationDataSource(
119 pxr::HdPrimvarSchemaTokens->vertex))
120 .SetRole(pxr::HdPrimvarSchema::BuildRoleDataSource(pxr::HdPrimvarSchemaTokens->point))
121 .Build());
122 }
123 if (!r.widths.empty()) {
124 primvars.add(pxr::HdPrimvarsSchemaTokens->widths,
125 pxr::HdPrimvarSchema::Builder()
126 .SetPrimvarValue(
127 pxr::HdRetainedTypedSampledDataSource<pxr::VtFloatArray>::New(r.widths))
128 .SetInterpolation(pxr::HdPrimvarSchema::BuildInterpolationDataSource(
129 pxr::HdPrimvarSchemaTokens->vertex))
130 .Build());
131 }
132 if (!r.uvs.empty()) {
133 primvars.add(
135 pxr::HdPrimvarSchema::Builder()
136 .SetPrimvarValue(pxr::HdRetainedTypedSampledDataSource<pxr::VtVec2fArray>::New(r.uvs))
137 .SetInterpolation(pxr::HdPrimvarSchema::BuildInterpolationDataSource(
138 pxr::HdPrimvarSchemaTokens->uniform))
139 .SetRole(pxr::HdPrimvarSchema::BuildRoleDataSource(
140 pxr::HdPrimvarSchemaTokens->textureCoordinate))
141 .Build());
142 }
143 out.primvars = pxr::HdPrimvarsSchema::BuildRetained(
144 primvars.names.size(), primvars.names.data(), primvars.values.data());
145
146 if (!material_path.IsEmpty()) {
147 pxr::HdContainerDataSourceHandle binding =
148 pxr::HdMaterialBindingSchema::Builder()
149 .SetPath(pxr::HdRetainedTypedSampledDataSource<pxr::SdfPath>::New(material_path))
150 .Build();
151 out.bindings = pxr::HdRetainedContainerDataSource::New(
152 pxr::HdMaterialBindingsSchemaTokens->allPurpose, binding);
153 }
154 return out;
155}
156
157/* Resolve a single-slot material binding for curves and hair. */
159 pxr::SdfPath path;
161};
163{
164 const int mat_count = BKE_object_material_count_eval(object);
165 const Material *material = (mat_count > 0) ? BKE_object_material_get_eval(
166 object, std::clamp(slot, 1, mat_count)) :
167 nullptr;
168 const EmittedMaterial *entry = ctx.get_or_create_material(material);
169 return {entry ? entry->path : pxr::SdfPath(), material};
170}
171
172/* Look up or build the geometry-only data source for a curves object. */
174 const BObjectInfo &info,
175 const EmittedGeometryKey &key)
176{
177 ctx.used_emitted_geometry.add(key);
178
179 if (!info.is_real_object_data() && info.object_data) {
180 ctx.instance_geometries_by_object.lookup_or_add_default(info.real_object)
181 .append_non_duplicates(info.object_data);
183 }
184
185 if (EmittedGeometry *cached = ctx.emitted_geometry.lookup_ptr(key)) {
186 for (const Material *mat : cached->materials) {
187 ctx.get_or_create_material(mat);
188 }
189 return *cached;
190 }
191
192 EmittedGeometry &entry = ctx.emitted_geometry.lookup_or_add_default(key);
195 entry.prims.append(build_curves_geometry(curves, mat.path));
196 entry.materials.append(mat.material);
197 return entry;
198}
199
201{
202 /* TODO: Using only first material. Add support for multi-material. */
203 const EmittedGeometryKey key = ctx.emitted_geometry_key(info,
204 pxr::HdPrimTypeTokens->basisCurves);
205 const EmittedGeometry &cached = get_or_build_emitted_curves(ctx, info, key);
206 if (cached.prims.is_empty()) {
207 return;
208 }
209 emitted.geometry_keys.append_non_duplicates(key);
210 for (const Material *m : cached.materials) {
211 emitted.materials.append_non_duplicates(m);
212 }
213 const Object *object = info.iter_object;
214 const pxr::SdfPath path = ctx.object_prim_id(object);
215 pxr::HdContainerDataSourceHandle prim_ds = compose_gprim_data_source(
216 cached.prims[0], gf_matrix_from_transform(object->object_to_world().ptr()), true);
217 ctx.emit_object_prim(emitted, path, pxr::HdPrimTypeTokens->basisCurves, prim_ds);
218}
219
221{
222 const EmittedGeometryKey key = ctx.emitted_geometry_key(info,
223 pxr::HdPrimTypeTokens->basisCurves);
224 const EmittedGeometry &cached = get_or_build_emitted_curves(ctx, info, key);
225 if (cached.prims.is_empty()) {
226 return;
227 }
228 const Object *source = info.real_object;
229 const pxr::SdfPath proto_root = ctx.instancer_proto_root(source);
230 const pxr::SdfPath proto_path = proto_root.AppendElementString("Curves");
231 pxr::HdContainerDataSourceHandle prim_ds = compose_gprim_data_source(
232 cached.prims[0], pxr::GfMatrix4d(1.0), true, ctx.proto_instanced_by(source));
233
234 ctx.emit_prim(proto_path, pxr::HdPrimTypeTokens->basisCurves, prim_ds);
235 ctx.all_proto_paths.append(proto_path);
236 ctx.per_proto_indices.append(pxr::VtIntArray());
237}
238
240{
242 ParticleCacheKey **cache = psys->pathcache;
243 if (!cache) {
244 return r;
245 }
246 r.curve_vertex_counts.reserve(psys->totpart);
247
248 const float scale = psys->part->rad_scale;
249 const float root = scale * psys->part->rad_root;
250 const float tip = scale * psys->part->rad_tip;
251 const float shape = psys->part->shape;
252
253 const bool has_particles = (psys->particles != nullptr);
254 const ParticleSystemModifierData *psmd = has_particles ? psys_get_modifier(object, psys) :
255 nullptr;
256 const bool emit_uvs = psmd && psmd->mesh_final &&
258 const MFace *mfaces = nullptr;
259 const MTFace *mtfaces = nullptr;
260 if (emit_uvs) {
261 mfaces = static_cast<const MFace *>(
263 mtfaces = static_cast<const MTFace *>(
265 }
266 if (has_particles) {
267 r.uvs.reserve(psys->totpart);
268 }
269
270 /* The pathcache stores positions in world space, transform to local
271 * so we can use a regular object transform with it. */
272 for (int pa_index = 0; pa_index < psys->totpart; ++pa_index) {
273 ParticleCacheKey *strand = cache[pa_index];
274 const int point_count = strand->segments + 1;
275 r.curve_vertex_counts.push_back(point_count);
276
277 for (int point_index = 0; point_index < point_count; ++point_index, ++strand) {
278 float local_co[3];
279 mul_v3_m4v3(local_co, psys->imat, strand->co);
280 r.points.push_back(pxr::GfVec3f(local_co));
281 const float x = float(point_index) / float(point_count - 1);
282 const float radius = std::pow(x, std::pow(10.0f, -shape));
283 r.widths.push_back(root + (tip - root) * radius);
284 }
285
286 if (psys->part->shape_flag & PART_SHAPE_CLOSE_TIP) {
287 r.widths[r.widths.size() - 1] = 0.0f;
288 }
289
290 if (has_particles) {
291 const ParticleData &pa = psys->particles[pa_index];
292 const int num = ELEM(pa.num_dmcache, DMCACHE_ISCHILD, DMCACHE_NOTFOUND) ? pa.num :
293 pa.num_dmcache;
294 float uv[2] = {0.0f, 0.0f};
295 if (emit_uvs && mfaces && mtfaces && !ELEM(num, DMCACHE_NOTFOUND, DMCACHE_ISCHILD)) {
296 psys_interpolate_uvs(mtfaces + num, mfaces->v4, pa.fuv, uv);
297 }
298 r.uvs.push_back(pxr::GfVec2f(uv[0], uv[1]));
299 }
300 }
301 return r;
302}
303
305{
306 const bool for_render = (DEG_get_mode(ctx.depsgraph) == DAG_EVAL_RENDER);
307 for (ParticleSystem &psys : object->particlesystem) {
308 if (!psys.part || psys.part->type != PART_HAIR) {
309 continue;
310 }
311 if (!psys_check_enabled(object, &psys, for_render)) {
312 continue;
313 }
314 if (psys_in_edit_mode(ctx.depsgraph, &psys)) {
315 continue;
316 }
317 CurvesBuilderResult hair = build_hair_data(object, &psys);
318 if (hair.curve_vertex_counts.empty()) {
319 continue;
320 }
321 const CurvesMaterial mat = resolve_curves_material(ctx, object, psys.part->omat);
322 if (mat.material) {
323 emitted.materials.append_non_duplicates(mat.material);
324 }
325 const pxr::SdfPath path = ctx.hair_prim_id(object, &psys);
326 const EmittedGeometryPrim gprim = build_curves_geometry(hair, mat.path);
327 pxr::HdContainerDataSourceHandle prim_ds = compose_gprim_data_source(
328 gprim, gf_matrix_from_transform(object->object_to_world().ptr()), true);
329 ctx.emit_object_prim(emitted, path, pxr::HdPrimTypeTokens->basisCurves, prim_ds);
330 }
331}
332
334{
335 const bool for_render = (DEG_get_mode(ctx.depsgraph) == DAG_EVAL_RENDER);
336 const pxr::SdfPath proto_root = ctx.instancer_proto_root(source);
337 const pxr::HdContainerDataSourceHandle instanced_by_ds = ctx.proto_instanced_by(source);
338
339 for (ParticleSystem &psys : source->particlesystem) {
340 if (!psys.part || psys.part->type != PART_HAIR) {
341 continue;
342 }
343 if (!psys_check_enabled(source, &psys, for_render)) {
344 continue;
345 }
346 if (psys_in_edit_mode(ctx.depsgraph, &psys)) {
347 continue;
348 }
349 CurvesBuilderResult hair = build_hair_data(source, &psys);
350 if (hair.curve_vertex_counts.empty()) {
351 continue;
352 }
353 const CurvesMaterial mat = resolve_curves_material(ctx, source, psys.part->omat);
354
355 char ps_name[32];
356 SNPRINTF(ps_name, "PS_%p", &psys);
357 const pxr::SdfPath proto_path = proto_root.AppendElementString(ps_name);
358 const EmittedGeometryPrim gprim = build_curves_geometry(hair, mat.path);
359 pxr::HdContainerDataSourceHandle prim_ds = compose_gprim_data_source(
360 gprim, pxr::GfMatrix4d(1.0), true, instanced_by_ds);
361
362 ctx.emit_prim(proto_path, pxr::HdPrimTypeTokens->basisCurves, prim_ds);
363 ctx.all_proto_paths.append(proto_path);
364 ctx.per_proto_indices.append(pxr::VtIntArray());
365 }
366}
367
368} // namespace blender::io::hydra
Low-level operations for curves.
CustomData interface, see also DNA_customdata_types.h.
General operations, lookup, etc. for materials.
#define DMCACHE_NOTFOUND
#define DMCACHE_ISCHILD
#define SNPRINTF(dst, format,...)
Object is a sort of wrapper for general info.
#define ELEM(...)
constexpr IndexRange()=default
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
float3x3 scale(float3x3 mat, float2 scale)
void emit_hair_proto(PopulateContext &ctx, Object *source)
void emit_hair_for_object(PopulateContext &ctx, Object *object, EmittedObject &emitted)
static const EmittedGeometry & get_or_build_emitted_curves(PopulateContext &ctx, const BObjectInfo &info, const EmittedGeometryKey &key)
void emit_curves_proto(PopulateContext &ctx, const BObjectInfo &info)
static EmittedGeometryPrim build_curves_geometry(const CurvesBuilderResult &r, const pxr::SdfPath &material_path)
static CurvesMaterial resolve_curves_material(PopulateContext &ctx, Object *object, const int slot)
pxr::GfMatrix4d gf_matrix_from_transform(const float m[4][4])
Definition util.hh:20
static const pxr::TfToken usd_st_token("st", pxr::TfToken::Immortal)
pxr::HdContainerDataSourceHandle compose_gprim_data_source(const EmittedGeometryPrim &gprim, const pxr::GfMatrix4d &transform, const bool visible, const pxr::HdContainerDataSourceHandle &instanced_by_overlay)
static CurvesBuilderResult build_hair_data(Object *object, ParticleSystem *psys)
void emit_curves_object(PopulateContext &ctx, const BObjectInfo &info, EmittedObject &emitted)
static CurvesBuilderResult build_curves_data(const Object *object)
void resize_uninitialized(pxr::VtArray< T > &array, const int new_size)
Definition util.hh:32
void copy_group_sizes(OffsetIndices< int > offsets, const IndexMask &mask, MutableSpan< int > sizes)
int BKE_object_material_count_eval(const Object *ob)
void mul_v3_m4v3(float r[3], const float mat[4][4], const float vec[3])
struct ParticleSystemModifierData * psys_get_modifier(struct Object *ob, struct ParticleSystem *psys)
Definition particle.cc:2190
bool psys_in_edit_mode(struct Depsgraph *depsgraph, const struct ParticleSystem *psys)
VecBase< float, 2 > float2
const void * CustomData_get_layer(const CustomData *data, eCustomDataType type)
ATTR_WARN_UNUSED_RESULT const size_t num
void psys_interpolate_uvs(const struct MTFace *tface, int quad, const float w[4], float r_uv[2])
eEvaluationMode DEG_get_mode(const Depsgraph *graph)
bool psys_check_enabled(struct Object *ob, struct ParticleSystem *psys, bool use_render_params)
Definition particle.cc:739
Material * BKE_object_material_get_eval(Object *ob, short act)
VecBase< float, 3 > float3
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
CustomData fdata_legacy
ListBaseT< struct ParticleSystem > particlesystem
struct ParticleCacheKey ** pathcache
Vector< EmittedGeometryPrim > prims
Vector< const Material * > materials
Vector< const Material * > materials
Vector< EmittedGeometryKey > geometry_keys
Vector< pxr::HdDataSourceBaseHandle > values
Definition util.hh:41
void add(const pxr::TfToken &name, const T &value)
Definition util.hh:51
Vector< pxr::TfToken > names
Definition util.hh:40
Map< const Object *, Vector< const ID * > > & instance_geometries_by_object
Set< EmittedGeometryKey > used_emitted_geometry
pxr::SdfPath object_prim_id(const Object *object) const
void emit_object_prim(EmittedObject &emitted, const pxr::SdfPath &path, const pxr::TfToken &type, const pxr::HdContainerDataSourceHandle &ds, const pxr::GfMatrix4d &geometry_xform=pxr::GfMatrix4d(1.0))
Set< const Object * > used_instance_sources
Vector< pxr::VtIntArray > per_proto_indices
const EmittedMaterial * get_or_create_material(const Material *material)
pxr::SdfPath instancer_proto_root(const Object *source) const
Map< EmittedGeometryKey, EmittedGeometry > & emitted_geometry
pxr::HdContainerDataSourceHandle proto_instanced_by(const Object *source) const
void emit_prim(const pxr::SdfPath &path, const pxr::TfToken &type, const pxr::HdContainerDataSourceHandle &ds)
pxr::SdfPath hair_prim_id(const Object *object, const ParticleSystem *psys) const
EmittedGeometryKey emitted_geometry_key(const BObjectInfo &info, const pxr::TfToken &type) const