Lagrange
Loading...
Searching...
No Matches
occluded_sampler_common.h
1/*
2 * Copyright 2026 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/Logger.h>
15#include <lagrange/internal/constants.h>
16#include <lagrange/raycasting/RayCaster.h>
17#include <lagrange/scene/SimpleScene.h>
18#include <lagrange/scene/simple_scene_bbox.h>
19#include <lagrange/utils/AdjacencyList.h>
20#include <lagrange/utils/assert.h>
21#include <lagrange/utils/geometry3d.h>
22#include <lagrange/utils/range.h>
23#include <lagrange/views.h>
24
25#include <Eigen/Core>
26#include <Eigen/Geometry>
27
28#include <algorithm>
29#include <array>
30#include <atomic>
31#include <chrono>
32#include <cmath>
33#include <cstddef>
34#include <cstdint>
35#include <limits>
36#include <numeric>
37#include <optional>
38#include <vector>
39
40namespace lagrange::raycasting::detail {
41
51inline double binomial_upper_tail(uint64_t n, uint64_t num_trials, double p)
52{
53 if (n == 0) return 1.0;
54 if (n > num_trials) return 0.0;
55 const double q = 1.0 - p;
56 double pmf = std::pow(q, static_cast<double>(num_trials)); // pmf(0)
57 double cdf = pmf; // P(X <= 0)
58 for (uint64_t k = 1; k < n; ++k) {
59 pmf *= static_cast<double>(num_trials - k + 1) / static_cast<double>(k) * (p / q);
60 cdf += pmf;
61 }
62 return 1.0 - cdf; // P(X >= n) = 1 - P(X <= n-1)
63}
64
69inline bool is_confidently_visible(uint64_t n, uint64_t num_trials, double threshold, double alpha)
70{
71 if (n == 0 || num_trials == 0) return false;
72 if (threshold <= 0.0) return true; // any escape clears a zero threshold
73 if (threshold >= 1.0) return false; // a bounded Bernoulli mean cannot be strictly above 1
74 if (static_cast<double>(n) <= static_cast<double>(num_trials) * threshold) return false;
75
76 constexpr uint64_t exact_cap = 1000;
77 if (num_trials <= exact_cap) return binomial_upper_tail(n, num_trials, threshold) <= alpha;
78
79 const double variance = static_cast<double>(num_trials) * threshold * (1.0 - threshold);
80 const double z = (static_cast<double>(n) - 0.5 - static_cast<double>(num_trials) * threshold) /
81 std::sqrt(variance);
82 return 0.5 * std::erfc(z / std::sqrt(2.0)) <= alpha;
83}
84
87namespace betting {
88
89// Choose a predictable betting fraction and clamp it so every wealth factor remains positive.
90[[nodiscard]] constexpr double compute_lambda(double running_mean, double running_var, double y0)
91{
92 const double lambda = (running_mean - y0) / std::max(running_var, 1e-9);
93 return std::clamp(lambda, 0.0, 0.5 / std::max(y0, 1e-9));
94}
95
96// Return the log-wealth increment from one observation; blocked rays pass `y = 0`.
97[[nodiscard]] inline double logwealth_step(double lambda, double y, double y0)
98{
99 return std::log1p(lambda * (y - y0));
100}
101
102} // namespace betting
103
104template <typename Scalar, typename Index>
105double scene_aabb_surface_area(const scene::SimpleScene<Scalar, Index, 3>& scene)
106{
107 const auto bbox = scene::simple_scene_bbox(scene);
108 if (bbox.isEmpty()) return 0.0;
109 const Eigen::Vector3<Scalar> d = bbox.sizes().cwiseMax(Scalar(0));
110 return 2.0 * (static_cast<double>(d.x()) * d.y() + static_cast<double>(d.y()) * d.z() +
111 static_cast<double>(d.x()) * d.z());
112}
113
114// See https://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/
115template <typename Scalar>
116Eigen::Array4<Scalar> generate_vec4(const size_t i)
117{
118 constexpr double phi_1 = 1.1673039782614186842560459;
119 constexpr double phi_2 = phi_1 * phi_1;
120 constexpr double phi_3 = phi_2 * phi_1;
121 constexpr double phi_4 = phi_2 * phi_2;
122 const Eigen::Array4d phi(phi_1, phi_2, phi_3, phi_4);
123 // +0.5 avoids the degenerate (0,0,0,0) sample at i=0.
124 const Eigen::Array4d shifted = static_cast<double>(i) / phi + 0.5;
125 return (shifted - shifted.floor()).template cast<Scalar>();
126}
127
128template <typename Scalar>
129struct RaySampler
130{
131 struct Sample
132 {
133 Eigen::RowVector2<Scalar> bary;
134 Eigen::RowVector3<Scalar> direction;
135 };
136
137 explicit RaySampler(const Eigen::RowVector3<Scalar>& normal)
138 : m_normal(normal)
139 {
140 Eigen::Vector3<Scalar> x_col, y_col;
141 lagrange::orthogonal_frame(Eigen::Vector3<Scalar>(normal.transpose()), x_col, y_col);
142 m_x_axis = x_col.transpose();
143 m_y_axis = y_col.transpose();
144 }
145
146 // Atomic member blocks the implicit move ctor; load explicitly so RaySampler can live in
147 // a std::vector.
148 RaySampler(RaySampler&& other) noexcept
149 : m_normal(other.m_normal)
150 , m_x_axis(other.m_x_axis)
151 , m_y_axis(other.m_y_axis)
152 , m_sample_index(other.m_sample_index.load(std::memory_order_relaxed))
153 {}
154 RaySampler(const RaySampler&) = delete;
155 RaySampler& operator=(const RaySampler&) = delete;
156 RaySampler& operator=(RaySampler&&) = delete;
157
158 const Eigen::RowVector3<Scalar>& get_normal() const { return m_normal; }
159
163 {
164 const auto vec4 =
165 generate_vec4<Scalar>(m_sample_index.fetch_add(1, std::memory_order_relaxed));
166 const Scalar phi = 2 * static_cast<Scalar>(lagrange::internal::pi) * vec4[0];
167 const Scalar r2 = vec4[1];
168 const Scalar r = std::sqrt(r2);
169 const Scalar x = r * std::cos(phi);
170 const Scalar y = r * std::sin(phi);
171 const Scalar z = std::sqrt(Scalar(1) - r2);
172 Sample result;
173 result.direction = x * m_x_axis + y * m_y_axis + z * m_normal;
174 result.bary = vec4.template tail<2>();
175 if (result.bary[0] + result.bary[1] > 1) {
176 // Intentional: direction flip pairs with the bary fold for bi-hemisphere coverage.
177 result.direction = -result.direction;
178 result.bary = Eigen::RowVector2<Scalar>::Ones() - result.bary;
179 }
180 return result;
181 }
182
185 Sample sample_vmf(const Eigen::RowVector3<Scalar>& axis, Scalar kappa)
186 {
187 const auto vec4 =
188 generate_vec4<Scalar>(m_sample_index.fetch_add(1, std::memory_order_relaxed));
189 const double kappa_d = static_cast<double>(kappa);
190 const double u = static_cast<double>(vec4[0]);
191 const double arg = u + (1.0 - u) * std::exp(-2.0 * kappa_d);
192 const Scalar w = static_cast<Scalar>(1.0 + std::log(arg) / kappa_d);
193 const Scalar s = std::sqrt(std::max(Scalar(0), Scalar(1) - w * w));
194 const Scalar phi = 2 * static_cast<Scalar>(lagrange::internal::pi) * vec4[1];
195 Eigen::Vector3<Scalar> e1, e2;
196 lagrange::orthogonal_frame(Eigen::Vector3<Scalar>(axis.transpose()), e1, e2);
197 Sample result;
198 result.direction =
199 w * axis + s * (std::cos(phi) * e1.transpose() + std::sin(phi) * e2.transpose());
200 result.bary = vec4.template tail<2>();
201 if (result.bary[0] + result.bary[1] > 1) {
202 result.bary = Eigen::RowVector2<Scalar>::Ones() - result.bary;
203 }
204 la_debug_assert(result.direction.allFinite(), "sample_vmf: non-finite direction");
205 return result;
206 }
207
208private:
209 const Eigen::RowVector3<Scalar> m_normal;
210 Eigen::RowVector3<Scalar> m_x_axis;
211 Eigen::RowVector3<Scalar> m_y_axis;
212 std::atomic<size_t> m_sample_index{0};
213};
214
217template <typename Scalar>
219{
220 Eigen::Vector3<Scalar> base;
221 Eigen::Vector3<Scalar> edge0;
222 Eigen::Vector3<Scalar> edge1;
223};
224
226template <typename Scalar>
227Eigen::RowVector3<Scalar> triangle_position(
228 const FacetTriangle<Scalar>& t,
229 const Eigen::RowVector2<Scalar>& bary)
230{
231 return (t.base + bary(0) * t.edge0 + bary(1) * t.edge1).transpose();
232}
233
236{
237 static constexpr size_t capacity = 16;
238
239 RayCaster::Point16f origins;
240 RayCaster::Direction16f directions;
241 RayCaster::Float16 tmins;
242 size_t count = 0;
243
244 template <typename Origin, typename Direction>
245 void push(const Origin& origin, const Direction& direction, float tmin = 1e-6f)
246 {
247 origins.row(count) = origin.template cast<float>();
248 directions.row(count) = direction.template cast<float>();
249 tmins[count] = tmin;
250 ++count;
251 }
252
253 bool full() const { return count == capacity; }
254 bool empty() const { return count == 0; }
255 void clear() { count = 0; }
256
257 uint32_t cast(const RayCaster& caster) const
258 {
259 return caster.occluded16(origins, directions, count, tmins);
260 }
261
263 uint32_t occupied_mask() const { return (uint32_t{1} << count) - 1; }
264};
265
267template <typename Scalar>
269{
270 std::vector<Scalar> facet_areas; // world-space
271 std::vector<RaySampler<Scalar>> ray_samplers; // world-space normals
272 std::vector<FacetTriangle<Scalar>> facet_triangles; // world-space, for ray origins
273};
274
277template <typename Scalar, typename Index>
278double initialize_instance_geometry(
279 InstanceData<Scalar>& instance,
280 const Eigen::Transform<Scalar, 3, Eigen::Affine>& transform,
281 const SurfaceMesh<Scalar, Index>& mesh,
282 std::vector<Eigen::Vector3<Scalar>>& world_vertices)
283{
284 const Index num_facets = mesh.get_num_facets();
285 instance.facet_areas.resize(num_facets);
286 instance.facet_triangles.resize(num_facets);
287 instance.ray_samplers.clear();
288 instance.ray_samplers.reserve(num_facets);
289
290 const auto vertices = vertex_view(mesh);
291 const auto facets = facet_view(mesh);
292 world_vertices.resize(mesh.get_num_vertices());
293 for (auto v : lagrange::range(mesh.get_num_vertices())) {
294 world_vertices[v] = transform * Eigen::Vector3<Scalar>(vertices.row(v).transpose());
295 }
296
297 double total_area = 0.0;
298 for (auto f : lagrange::range(num_facets)) {
299 const auto& v0 = world_vertices[facets(f, 0)];
300 const auto& v1 = world_vertices[facets(f, 1)];
301 const auto& v2 = world_vertices[facets(f, 2)];
302 const Eigen::Vector3<Scalar> edge0 = v0 - v2;
303 const Eigen::Vector3<Scalar> edge1 = v1 - v2;
304 instance.facet_triangles[f] = {v2, edge0, edge1};
305
306 const Eigen::Vector3<Scalar> area_vector = Scalar(0.5) * edge0.cross(edge1);
307 const Scalar area = area_vector.norm();
308 instance.facet_areas[f] = area;
309 total_area += static_cast<double>(area);
310 // A placeholder normal keeps all per-facet arrays aligned for degenerate geometry.
311 instance.ray_samplers.emplace_back(
312 area > 0 ? Eigen::RowVector3<Scalar>(area_vector.transpose() / area)
313 : Eigen::RowVector3<Scalar>::UnitZ());
314 }
315 return total_area;
316}
317
322template <typename Scalar>
324{
325 static constexpr int capacity = 4;
326 std::array<Eigen::Vector3<Scalar>, capacity> dir{};
327 std::array<Scalar, capacity> weight{}; // 0 => empty slot
328 int size = 0;
329
330 void add(const Eigen::Vector3<Scalar>& d, Scalar merge_cos)
331 {
332 int best = -1;
333 Scalar best_cos = merge_cos;
334 for (int i = 0; i < size; ++i) {
335 const Scalar c = dir[i].dot(d);
336 if (c >= best_cos) {
337 best_cos = c;
338 best = i;
339 }
340 }
341 if (best >= 0) {
342 weight[best] += 1;
343 dir[best] = (dir[best] + (d - dir[best]) / weight[best]).normalized(); // running mean
344 } else if (size < capacity) {
345 dir[size] = d;
346 weight[size] = 1;
347 ++size;
348 } else {
349 int lo = 0;
350 for (int i = 1; i < capacity; ++i)
351 if (weight[i] < weight[lo]) lo = i;
352 dir[lo] = d;
353 weight[lo] = 1;
354 }
355 }
356};
357
359template <typename Scalar, typename Index>
361{
364 std::vector<Scalar> facet_weights;
365 std::vector<Index> active_local_facets;
366
367 std::optional<AdjacencyList<Index>> facet_neighbors;
368
370 std::vector<SeedReservoir<Scalar>> facet_seeds;
371 std::vector<SeedReservoir<Scalar>> facet_seeds_snapshot;
372};
373
374template <typename Derived, typename Scalar>
376{
377 RayCaster m_ray_caster;
378
379 Derived& derived() { return static_cast<Derived&>(*this); }
380 const Derived& derived() const { return static_cast<const Derived&>(*this); }
381
382 size_t num_instances() const { return derived().m_instances.size(); }
383 Scalar compute_total_active_weight() const
384 {
385 const auto r = lagrange::range(num_instances());
386 return std::accumulate(r.begin(), r.end(), Scalar(0), [&](Scalar s, size_t i) {
387 return s + derived().instance_active_weight(i);
388 });
389 }
390
391 void run_batch(uint64_t num_rays)
392 {
393 const Scalar total = compute_total_active_weight();
394 if (total <= 0) return;
395
396 const auto t_start = std::chrono::steady_clock::now();
397
398 for (auto i : lagrange::range(num_instances())) {
399 const Scalar inst_weight = derived().instance_active_weight(i);
400 if (inst_weight <= 0) continue;
401
402 const uint64_t inst_rays = static_cast<uint64_t>(
403 std::round(static_cast<double>(num_rays) * inst_weight / total));
404 if (inst_rays == 0) continue;
405
406 derived().process_instance(i, inst_rays, inst_weight);
407 }
408
409 derived().end_batch();
410
411 const auto t_end = std::chrono::steady_clock::now();
412 const auto batch_ms =
413 std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start).count();
414 lagrange::logger().info("Batch: {} ms", batch_ms);
415 }
416};
417
419template <typename Sampler, typename Index>
420std::pair<uint64_t, uint64_t> sum_progress(const Sampler& sampler, Index count)
421{
422 uint64_t num_visible = 0;
423 uint64_t total_rays = 0;
424 for (Index i = 0; i < count; ++i) {
425 if (sampler.is_visible(i)) ++num_visible;
426 total_rays += sampler.num_rays_cast(i);
427 }
428 return {num_visible, total_rays};
429}
430
431} // namespace lagrange::raycasting::detail
A general purpose polygonal mesh class.
Definition SurfaceMesh.h:73
A ray caster built on top of Embree that operates directly on SurfaceMesh and SimpleScene objects.
Definition RayCaster.h:196
uint32_t occluded16(const Point16f &origins, const Direction16f &directions, const std::variant< Mask16, size_t > &active=size_t(16), const Float16 &tmin=Float16::Zero(), const Float16 &tmax=Float16::Constant(std::numeric_limits< float >::infinity())) const
Test a packet of up to 16 rays for occlusion.
Definition RayCaster.cpp:1640
Simple scene container for instanced meshes.
Definition SimpleScene.h:62
spdlog::logger & logger()
Retrieves the current logger.
Definition Logger.cpp:40
@ Scalar
Mesh attribute must have exactly 1 channel.
Definition AttributeFwd.h:56
SurfaceMesh< ToScalar, ToIndex > cast(const SurfaceMesh< FromScalar, FromIndex > &source_mesh, const AttributeFilter &convertible_attributes={}, std::vector< std::string > *converted_attributes_names=nullptr)
Cast a mesh to a mesh of different scalar and/or index type.
ConstRowMatrixView< Scalar > vertex_view(const SurfaceMesh< Scalar, Index > &mesh)
Returns a read-only view of the mesh vertices in the form of an Eigen matrix.
Definition views.cpp:156
ConstRowMatrixView< Index > facet_view(const SurfaceMesh< Scalar, Index > &mesh)
Returns a read-only view of a mesh facets in the form of an Eigen matrix.
Definition views.cpp:170
#define la_debug_assert(...)
Debug assertion check.
Definition assert.h:197
Anytime-valid betting test helpers for a bounded mean, following Waudby-Smith & Ramdas (2024),...
Definition occluded_sampler_common.h:87
void orthogonal_frame(const Eigen::Matrix< Scalar, 3, 1 > &x, Eigen::Matrix< Scalar, 3, 1 > &y, Eigen::Matrix< Scalar, 3, 1 > &z)
Build an orthogonal frame given a single vector.
Definition geometry3d.h:125
internal::Range< Index > range(Index end)
Returns an iterable object representing the range [0, end).
Definition range.h:176
Per-instance data for OccludedFacetSampler; gates each facet individually.
Definition occluded_sampler_common.h:361
std::vector< SeedReservoir< Scalar > > facet_seeds
Per-facet escape-direction seeds, only updated in flush() from snapshot (to avoid race condition).
Definition occluded_sampler_common.h:370
std::vector< Scalar > facet_weights
Per-facet ray-allocation weight ∝ 1/tau_f = (area / mean_face_area)^size_influence.
Definition occluded_sampler_common.h:364
Precomputed world-space facet triangle for O(1) ray origins: base = V2, edge0 = V0 - V2,...
Definition occluded_sampler_common.h:219
Definition occluded_sampler_common.h:376
Per-instance precomputation shared by both samplers.
Definition occluded_sampler_common.h:269
16-ray SIMD packet for RayCaster::occluded16. push widens to float on entry.
Definition occluded_sampler_common.h:236
uint32_t occupied_mask() const
Low count bits set — masks off undefined slots in a partial packet's cast mask.
Definition occluded_sampler_common.h:263
Definition occluded_sampler_common.h:132
Definition occluded_sampler_common.h:130
Sample sample_vmf(const Eigen::RowVector3< Scalar > &axis, Scalar kappa)
Sample a direction from a von Mises-Fisher lobe (mean axis, concentration kappa) on the full sphere,...
Definition occluded_sampler_common.h:185
Sample sample_cosine()
Bi-hemisphere sample via Malley's method: when bary reflection fires (u+v > 1), the direction is also...
Definition occluded_sampler_common.h:162
Bounded set of escape-direction "seeds" for a facet, feeding the adaptive vMF-mixture proposal.
Definition occluded_sampler_common.h:324