Lagrange
Loading...
Searching...
No Matches
project_attributes_directional.h
1/*
2 * Copyright 2020 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12#pragma once
13
14#include <lagrange/MeshTrait.h>
15#include <lagrange/bvh/project_attributes_closest_vertex.h>
16#include <lagrange/create_mesh.h>
17#include <lagrange/legacy/inline.h>
18#include <lagrange/raycasting/Options.h>
19#include <lagrange/raycasting/create_ray_caster.h>
20#include <lagrange/raycasting/legacy/project_attributes_closest_point.h>
21#include <lagrange/utils/safe_cast.h>
22
23// clang-format off
24#include <lagrange/utils/warnoff.h>
25#include <igl/bounding_box_diagonal.h>
26#include <lagrange/utils/warnon.h>
27// clang-format on
28
29#include <tbb/parallel_for.h>
30
31#include <algorithm>
32#include <string>
33#include <type_traits>
34#include <vector>
35
36namespace lagrange {
37namespace raycasting {
38LAGRANGE_LEGACY_INLINE
39namespace legacy {
40
72template <
73 typename SourceMeshType,
74 typename TargetMeshType,
75 typename DerivedVector,
76 typename DefaultScalar = typename SourceMeshType::Scalar>
77void project_attributes_directional(
78 const SourceMeshType& source,
79 TargetMeshType& target,
80 const std::vector<std::string>& names,
81 const Eigen::MatrixBase<DerivedVector>& direction,
82 CastMode cast_mode = CastMode::BothWays,
84 DefaultScalar default_value = DefaultScalar(0),
85 std::function<void(typename TargetMeshType::Index, bool)> user_callback = nullptr,
86 EmbreeRayCaster<ScalarOf<SourceMeshType>>* ray_caster = nullptr,
87 std::function<bool(IndexOf<TargetMeshType>)> skip_vertex = nullptr)
88{
89 static_assert(MeshTrait<SourceMeshType>::is_mesh(), "Input type is not Mesh");
90 static_assert(MeshTrait<TargetMeshType>::is_mesh(), "Output type is not Mesh");
91 la_runtime_assert(source.get_vertex_per_facet() == 3);
92
93 // Typedef festival because templates...
94 using Scalar = typename SourceMeshType::Scalar;
95 using Index = typename TargetMeshType::Index;
96 using SourceArray = typename SourceMeshType::AttributeArray;
97 using TargetArray = typename SourceMeshType::AttributeArray;
98 using Point = typename EmbreeRayCaster<Scalar>::Point;
99 using Direction = typename EmbreeRayCaster<Scalar>::Direction;
100 using RayCasterIndex = typename EmbreeRayCaster<Scalar>::Index;
101 using Scalar4 = typename EmbreeRayCaster<Scalar>::Scalar4;
102 using Index4 = typename EmbreeRayCaster<Scalar>::Index4;
103 using Point4 = typename EmbreeRayCaster<Scalar>::Point4;
104 using Direction4 = typename EmbreeRayCaster<Scalar>::Direction4;
105 using Mask4 = typename EmbreeRayCaster<Scalar>::Mask4;
106
107 // We need to convert to a shared_ptr AND the ray caster will make another copy of the data..
108 std::unique_ptr<EmbreeRayCaster<Scalar>> engine;
109 if (!ray_caster) {
110 auto mesh = lagrange::to_shared_ptr(
111 lagrange::create_mesh(source.get_vertices(), source.get_facets()));
112 // Robust mode gives slightly more accurate results...
113 engine = create_ray_caster<Scalar>(EMBREE_ROBUST, BUILD_QUALITY_HIGH);
114
115 // Gosh why do I need to specify a transform here?
116 engine->add_mesh(mesh, Eigen::Matrix<Scalar, 4, 4>::Identity());
117
118 // Do a dummy raycast to trigger scene update, otherwise `cast()` will not work in
119 // multithread mode... (this is why we need const-safety...)
120 engine->cast(Point(0, 0, 0), Direction(0, 0, 1));
121 ray_caster = engine.get();
122 } else {
123 logger().debug("Using provided ray-caster");
124 }
125
126 // Store pointer to source/target arrays
127 std::vector<const SourceArray*> source_attrs;
128 source_attrs.reserve(names.size());
129 std::vector<TargetArray> target_attrs(names.size());
130 for (size_t k = 0; k < names.size(); ++k) {
131 const auto& name = names[k];
132 la_runtime_assert(source.has_vertex_attribute(name));
133 source_attrs.push_back(&source.get_vertex_attribute(name));
134 if (target.has_vertex_attribute(name)) {
135 target.export_vertex_attribute(name, target_attrs[k]);
136 } else {
137 target_attrs[k].resize(target.get_num_vertices(), source_attrs[k]->cols());
138 }
139 }
140
141 auto diag = igl::bounding_box_diagonal(source.get_vertices());
142
143 // Using `char` instead of `bool` because we write concurrently to this
144 std::vector<char> is_hit;
145 if (wrap_mode != FallbackMode::Constant) {
146 is_hit.assign(target.get_num_vertices(), false);
147 }
148
149 Index num_vertices = target.get_num_vertices();
150 Index num_packets = (num_vertices + 3) / 4;
151
152 Direction4 dirs;
153 dirs.row(0) = direction.normalized().transpose();
154 for (int i = 1; i < 4; ++i) {
155 dirs.row(i) = dirs.row(0);
156 }
157 Direction4 dirs2 = -dirs;
158
159 tbb::parallel_for(Index(0), num_packets, [&](Index packet_index) {
160 Index batchsize = std::min(num_vertices - (packet_index << 2), 4);
161 Mask4 mask = Mask4::Constant(-1);
162 Point4 origins;
163
164 int num_skipped_in_packet = 0;
165 for (Index b = 0; b < batchsize; ++b) {
166 Index i = (packet_index << 2) + b;
167 if (skip_vertex && skip_vertex(i)) {
168 logger().trace("skipping vertex: {}", i);
169 if (!is_hit.empty()) {
170 is_hit[i] = true;
171 }
172 mask(b) = 0;
173 ++num_skipped_in_packet;
174 continue;
175 }
176
177 origins.row(b) = target.get_vertices().row(i);
178 }
179
180 if (num_skipped_in_packet == batchsize) return;
181
182 for (Index b = batchsize; b < 4; ++b) {
183 mask(b) = 0;
184 }
185
186 Index4 mesh_indices;
187 Index4 instance_indices;
188 Index4 facet_indices;
189 Scalar4 ray_depths;
190 Point4 barys;
191 Point4 normals;
192 uint8_t hits = ray_caster->cast4(
193 batchsize,
194 origins,
195 dirs,
196 mask,
197 mesh_indices,
198 instance_indices,
199 facet_indices,
200 ray_depths,
201 barys,
202 normals);
203
204 if (cast_mode == CastMode::BothWays) {
205 // Try again in the other direction. Slightly offset ray origin, and keep closest point.
206 Point4 origins2 = origins + Scalar(1e-6) * diag * dirs;
207 Index4 mesh_indices2;
208 Index4 instance_indices2;
209 Index4 facet_indices2;
210 Scalar4 ray_depths2;
211 Point4 barys2;
212 Point4 norms2;
213 uint8_t hits2 = ray_caster->cast4(
214 batchsize,
215 origins2,
216 dirs2,
217 mask,
218 mesh_indices2,
219 instance_indices2,
220 facet_indices2,
221 ray_depths2,
222 barys2,
223 norms2);
224
225 for (Index b = 0; b < batchsize; ++b) {
226 if (!mask(b)) continue;
227 auto len2 = std::abs(Scalar(1e-6) * diag - ray_depths2(b));
228 bool hit = hits & (1 << b);
229 bool hit2 = hits2 & (1 << b);
230 if (hit2 && (!hit || len2 < ray_depths(b))) {
231 hits |= 1 << b;
232 mesh_indices(b) = mesh_indices2(b);
233 facet_indices(b) = facet_indices2(b);
234 barys.row(b) = barys2.row(b);
235 }
236 }
237 }
238 for (Index b = 0; b < batchsize; ++b) {
239 if (!mask(b)) continue;
240 bool hit = hits & (1 << b);
241 Index i = (packet_index << 2) + b;
242 if (hit) {
243 // Hit occurred, interpolate data
245 facet_indices(b) >= 0 &&
246 facet_indices(b) < static_cast<RayCasterIndex>(source.get_num_facets()));
247 auto face = source.get_facets().row(facet_indices(b));
248 for (size_t k = 0; k < source_attrs.size(); ++k) {
249 target_attrs[k].row(i).setZero();
250 for (int lv = 0; lv < 3; ++lv) {
251 target_attrs[k].row(i) += source_attrs[k]->row(face[lv]) * barys(b, lv);
252 }
253 }
254 } else {
255 // Not hit. Set values according to wrap_mode + call user-callback at the end if
256 // needed
257 for (size_t k = 0; k < source_attrs.size(); ++k) {
258 switch (wrap_mode) {
260 target_attrs[k].row(i).setConstant(safe_cast<Scalar>(default_value));
261 break;
262 default: break;
263 }
264 }
265 }
266 if (!is_hit.empty()) {
267 is_hit[i] = hit;
268 }
269 if (user_callback) {
270 user_callback(i, hit);
271 }
272 }
273 });
274
275 // Not super pretty way, we still need to separately add/create the attribute,
276 // THEN import it without copy. Would be better if we could get a ref to it.
277 for (size_t k = 0; k < names.size(); ++k) {
278 const auto& name = names[k];
279 target.add_vertex_attribute(name);
280 target.import_vertex_attribute(name, target_attrs[k]);
281 }
282
283 // If there is any vertex without a hit, we defer to the relevant functions with filtering
284 if (wrap_mode != FallbackMode::Constant) {
285 bool all_hit = std::all_of(is_hit.begin(), is_hit.end(), [](char x) { return bool(x); });
286 if (!all_hit) {
287 if (wrap_mode == FallbackMode::ClosestPoint) {
288 project_attributes_closest_point(source, target, names, ray_caster, [&](Index i) {
289 return bool(is_hit[i]);
290 });
291 } else if (wrap_mode == FallbackMode::ClosestVertex) {
292 ::lagrange::bvh::project_attributes_closest_vertex(
293 source,
294 target,
295 names,
296 [&](Index i) { return bool(is_hit[i]); });
297 } else {
298 throw std::runtime_error("not implemented");
299 }
300 }
301 }
302}
303
304} // namespace legacy
305} // namespace raycasting
306} // namespace lagrange
A wrapper for Embree's raycasting API to compute ray intersections with (instances of) meshes.
Definition EmbreeRayCaster.h:59
LA_CORE_API spdlog::logger & logger()
Retrieves the current logger.
Definition Logger.cpp:40
@ Scalar
Mesh attribute must have exactly 1 channel.
Definition AttributeFwd.h:56
#define la_runtime_assert(...)
Runtime assertion check.
Definition assert.h:174
constexpr auto safe_cast(SourceType value) -> std::enable_if_t<!std::is_same< SourceType, TargetType >::value, TargetType >
Perform safe cast from SourceType to TargetType, where "safe" means:
Definition safe_cast.h:50
Raycasting operations.
Definition ClosestPointResult.h:22
FallbackMode
Fallback mode for vertices without a hit.
Definition Options.h:49
@ ClosestPoint
Interpolate attribute from the closest point on the source mesh.
Definition Options.h:55
@ ClosestVertex
Copy attribute from the closest vertex on the source mesh.
Definition Options.h:54
@ Constant
Fill with a constant value (defaults to 0).
Definition Options.h:53
CastMode
Ray-casting mode.
Definition Options.h:41
@ BothWays
Cast a ray both forward and backward in the prescribed direction.
Definition Options.h:45
Main namespace for Lagrange.
auto create_mesh(const Eigen::MatrixBase< DerivedV > &vertices, const Eigen::MatrixBase< DerivedF > &facets)
This function create a new mesh given the vertex and facet arrays by copying data into the Mesh objec...
Definition create_mesh.h:39
std::shared_ptr< T > to_shared_ptr(std::unique_ptr< T > &&ptr)
Helper for automatic type deduction for unique_ptr to shared_ptr conversion.
Definition common.h:88