use super::patch_table::{PatchMap, PatchTable, PatchTableFactory};
use super::primvar_refiner::{Primvar, PrimvarRefiner};
use super::topology_refiner::TopologyRefiner;
use crate::vtr::TopologyError;
use crate::Index;
#[derive(Debug, Clone, Copy)]
pub struct Stencil<'a> {
pub indices: &'a [Index],
pub weights: &'a [f32],
}
impl Stencil<'_> {
pub fn size(&self) -> usize {
self.indices.len()
}
}
#[derive(Debug, Clone, Copy)]
pub struct StencilTableOptions {
pub generate_intermediate_levels: bool,
pub generate_control_verts: bool,
}
impl Default for StencilTableOptions {
fn default() -> Self {
Self {
generate_intermediate_levels: true,
generate_control_verts: false,
}
}
}
impl StencilTableOptions {
pub fn for_patch_controls() -> Self {
Self {
generate_intermediate_levels: true,
generate_control_verts: true,
}
}
}
#[derive(Debug, Clone)]
pub struct StencilTable {
num_control_vertices: usize,
offsets: Vec<u32>,
indices: Vec<Index>,
weights: Vec<f32>,
}
impl StencilTable {
pub fn num_stencils(&self) -> usize {
self.offsets.len().saturating_sub(1)
}
pub fn num_control_vertices(&self) -> usize {
self.num_control_vertices
}
pub fn stencil(&self, i: usize) -> Stencil<'_> {
let (s, e) = (self.offsets[i] as usize, self.offsets[i + 1] as usize);
Stencil {
indices: &self.indices[s..e],
weights: &self.weights[s..e],
}
}
pub fn offsets(&self) -> &[u32] {
&self.offsets
}
pub fn indices(&self) -> &[Index] {
&self.indices
}
pub fn weights(&self) -> &[f32] {
&self.weights
}
pub fn update_values<T: Primvar>(&self, control_values: &[T], dst: &mut [T]) {
assert!(
control_values.len() >= self.num_control_vertices,
"control buffer too small"
);
assert!(dst.len() >= self.num_stencils(), "dst buffer too small");
apply_weights(
&self.offsets,
&self.indices,
&self.weights,
control_values,
dst,
);
}
}
fn apply_weights<T: Primvar>(
offsets: &[u32],
indices: &[Index],
weights: &[f32],
control_values: &[T],
dst: &mut [T],
) {
for (i, out) in dst.iter_mut().enumerate().take(offsets.len() - 1) {
let (s, e) = (offsets[i] as usize, offsets[i + 1] as usize);
let mut acc = out.clone();
acc.clear();
for (&idx, &w) in indices[s..e].iter().zip(&weights[s..e]) {
acc.add_with_weight(&control_values[idx as usize], w);
}
*out = acc;
}
}
#[derive(Debug, Clone, Default)]
struct StencilAccumulator {
entries: Vec<(Index, f32)>,
}
impl Primvar for StencilAccumulator {
fn clear(&mut self) {
self.entries.clear();
}
fn add_with_weight(&mut self, src: &Self, weight: f32) {
for &(index, w) in &src.entries {
match self.entries.iter_mut().find(|(i, _)| *i == index) {
Some((_, acc)) => *acc += w * weight,
None => self.entries.push((index, w * weight)),
}
}
}
}
pub struct StencilTableFactory;
impl StencilTableFactory {
pub fn create(refiner: &TopologyRefiner, options: StencilTableOptions) -> StencilTable {
let num_control = refiner.level(0).num_vertices();
let primvar = PrimvarRefiner::new(refiner);
let mut collected: Vec<StencilAccumulator> = Vec::new();
if options.generate_control_verts {
collected.extend((0..num_control).map(identity_stencil));
}
let mut src: Vec<StencilAccumulator> = (0..num_control).map(identity_stencil).collect();
for level in 1..=refiner.max_level() {
let mut dst = vec![StencilAccumulator::default(); refiner.level(level).num_vertices()];
primvar.interpolate(level, &src, &mut dst);
if options.generate_intermediate_levels || level == refiner.max_level() {
collected.extend(dst.iter().cloned());
}
src = dst;
}
build_table(num_control, collected)
}
pub fn create_limit(refiner: &TopologyRefiner) -> StencilTable {
assert!(
!refiner.is_adaptive(),
"vertex limit stencils require uniform refinement; use LimitStencilTableFactory for adaptive refiners"
);
let num_control = refiner.level(0).num_vertices();
let primvar = PrimvarRefiner::new(refiner);
let mut src: Vec<StencilAccumulator> = (0..num_control).map(identity_stencil).collect();
for level in 1..=refiner.max_level() {
let mut dst = vec![StencilAccumulator::default(); refiner.level(level).num_vertices()];
primvar.interpolate(level, &src, &mut dst);
src = dst;
}
let mut limits = vec![StencilAccumulator::default(); src.len()];
primvar.limit(&src, &mut limits);
build_table(num_control, limits)
}
pub fn append_local_point_stencils(
cv_stencils: &StencilTable,
local_point_stencils: &StencilTable,
) -> StencilTable {
assert!(
cv_stencils.num_stencils() >= local_point_stencils.num_control_vertices(),
"control-vertex stencil table has {} stencils but the local points depend on {} control values; \
build it with StencilTableOptions::for_patch_controls()",
cv_stencils.num_stencils(),
local_point_stencils.num_control_vertices()
);
let mut stencils: Vec<StencilAccumulator> = (0..cv_stencils.num_stencils())
.map(|i| {
let stencil = cv_stencils.stencil(i);
StencilAccumulator {
entries: stencil
.indices
.iter()
.copied()
.zip(stencil.weights.iter().copied())
.collect(),
}
})
.collect();
for i in 0..local_point_stencils.num_stencils() {
let local = local_point_stencils.stencil(i);
let mut composed = StencilAccumulator::default();
for (&cv, &w) in local.indices.iter().zip(local.weights) {
composed.add_with_weight(&stencils[cv as usize], w);
}
stencils.push(composed);
}
build_table(cv_stencils.num_control_vertices(), stencils)
}
}
fn identity_stencil(v: usize) -> StencilAccumulator {
StencilAccumulator {
entries: vec![(v as Index, 1.0)],
}
}
impl StencilTable {
pub(crate) fn from_stencils(
num_control_vertices: usize,
stencils: Vec<Vec<(Index, f32)>>,
) -> StencilTable {
build_table(
num_control_vertices,
stencils
.into_iter()
.map(|entries| StencilAccumulator { entries })
.collect(),
)
}
}
fn build_table(num_control_vertices: usize, stencils: Vec<StencilAccumulator>) -> StencilTable {
let total: usize = stencils.iter().map(|s| s.entries.len()).sum();
let mut table = StencilTable {
num_control_vertices,
offsets: Vec::with_capacity(stencils.len() + 1),
indices: Vec::with_capacity(total),
weights: Vec::with_capacity(total),
};
table.offsets.push(0);
for mut stencil in stencils {
stencil.entries.sort_by_key(|&(i, _)| i);
for (index, weight) in stencil.entries {
table.indices.push(index);
table.weights.push(weight);
}
table.offsets.push(table.indices.len() as u32);
}
table
}
#[derive(Debug, Clone, Copy)]
pub struct LocationArray<'a> {
pub ptex_face: Index,
pub u: &'a [f32],
pub v: &'a [f32],
}
impl<'a> LocationArray<'a> {
pub fn new(ptex_face: Index, u: &'a [f32], v: &'a [f32]) -> Self {
assert_eq!(
u.len(),
v.len(),
"u and v coordinate arrays must be parallel"
);
Self { ptex_face, u, v }
}
pub fn len(&self) -> usize {
self.u.len()
}
pub fn is_empty(&self) -> bool {
self.u.is_empty()
}
}
#[derive(Debug, Clone, Copy)]
pub struct LimitStencil<'a> {
pub indices: &'a [Index],
pub weights: &'a [f32],
pub du_weights: &'a [f32],
pub dv_weights: &'a [f32],
}
impl LimitStencil<'_> {
pub fn size(&self) -> usize {
self.indices.len()
}
}
#[derive(Debug, Clone)]
pub struct LimitStencilTable {
points: StencilTable,
du_weights: Vec<f32>,
dv_weights: Vec<f32>,
}
impl LimitStencilTable {
pub fn num_stencils(&self) -> usize {
self.points.num_stencils()
}
pub fn num_control_vertices(&self) -> usize {
self.points.num_control_vertices()
}
pub fn stencil(&self, i: usize) -> LimitStencil<'_> {
let (s, e) = (
self.points.offsets[i] as usize,
self.points.offsets[i + 1] as usize,
);
LimitStencil {
indices: &self.points.indices[s..e],
weights: &self.points.weights[s..e],
du_weights: &self.du_weights[s..e],
dv_weights: &self.dv_weights[s..e],
}
}
pub fn du_weights(&self) -> &[f32] {
&self.du_weights
}
pub fn dv_weights(&self) -> &[f32] {
&self.dv_weights
}
pub fn point_stencils(&self) -> &StencilTable {
&self.points
}
pub fn update_values<T: Primvar>(&self, control_values: &[T], dst: &mut [T]) {
self.points.update_values(control_values, dst);
}
pub fn update_derivs<T: Primvar>(&self, control_values: &[T], du: &mut [T], dv: &mut [T]) {
assert!(
control_values.len() >= self.num_control_vertices(),
"control buffer too small"
);
assert!(
du.len() >= self.num_stencils() && dv.len() >= self.num_stencils(),
"derivative buffers too small"
);
apply_weights(
&self.points.offsets,
&self.points.indices,
&self.du_weights,
control_values,
du,
);
apply_weights(
&self.points.offsets,
&self.points.indices,
&self.dv_weights,
control_values,
dv,
);
}
}
pub struct LimitStencilTableFactory;
impl LimitStencilTableFactory {
pub fn create(
refiner: &TopologyRefiner,
locations: &[LocationArray<'_>],
cv_stencils: Option<&StencilTable>,
patch_table: Option<&PatchTable>,
) -> Result<LimitStencilTable, TopologyError> {
let mut num_locations = 0usize;
for array in locations {
assert_eq!(
array.u.len(),
array.v.len(),
"u and v coordinate arrays must be parallel"
);
num_locations += array.len();
}
let num_control_vertices = refiner.level(0).num_vertices();
if num_locations == 0 {
return Ok(LimitStencilTable {
points: StencilTable {
num_control_vertices,
offsets: vec![0],
indices: Vec::new(),
weights: Vec::new(),
},
du_weights: Vec::new(),
dv_weights: Vec::new(),
});
}
let owned_patches;
let patch_table = match patch_table {
Some(table) => table,
None => {
owned_patches = PatchTableFactory::create(refiner)?;
&owned_patches
}
};
let num_ptex_faces = patch_table.ptex_indices().num_faces();
for array in locations {
if !array.is_empty() && array.ptex_face as usize >= num_ptex_faces {
return Err(TopologyError::PtexFaceOutOfRange {
ptex_face: array.ptex_face,
num_faces: num_ptex_faces,
});
}
}
let owned_stencils;
let cv_stencils = match cv_stencils {
Some(table) => table,
None => {
owned_stencils =
StencilTableFactory::create(refiner, StencilTableOptions::for_patch_controls());
&owned_stencils
}
};
assert!(
cv_stencils.num_stencils() >= patch_table.num_control_values(),
"control-vertex stencil table has {} stencils but the patch table has {} control values; \
build it with StencilTableOptions::for_patch_controls()",
cv_stencils.num_stencils(),
patch_table.num_control_values()
);
let num_control_vertices = cv_stencils.num_control_vertices();
let map = PatchMap::new(patch_table);
let mut offsets = Vec::with_capacity(num_locations + 1);
let mut indices = Vec::new();
let mut weights = Vec::new();
let mut du_weights = Vec::new();
let mut dv_weights = Vec::new();
offsets.push(0u32);
let mut scratch = vec![[0.0f32; 3]; num_control_vertices];
let mut in_use = vec![false; num_control_vertices];
let mut touched: Vec<Index> = Vec::new();
for array in locations {
for (&u, &v) in array.u.iter().zip(array.v) {
let patch = map.find_patch(array.ptex_face as usize, u, v).ok_or(
TopologyError::LimitLocationInHole {
ptex_face: array.ptex_face,
location: offsets.len() - 1,
},
)?;
let basis = patch_table.evaluate_basis(patch, u, v);
for (k, &cv) in basis.indices.iter().enumerate() {
let stencil = cv_stencils.stencil(cv as usize);
let factors = [basis.weights[k], basis.du_weights[k], basis.dv_weights[k]];
for (&index, &w) in stencil.indices.iter().zip(stencil.weights) {
if !std::mem::replace(&mut in_use[index as usize], true) {
touched.push(index);
}
for (s, f) in scratch[index as usize].iter_mut().zip(factors) {
*s += f * w;
}
}
}
touched.sort_unstable();
for &index in &touched {
let [w, du, dv] = std::mem::take(&mut scratch[index as usize]);
in_use[index as usize] = false;
indices.push(index);
weights.push(w);
du_weights.push(du);
dv_weights.push(dv);
}
touched.clear();
offsets.push(indices.len() as u32);
}
}
Ok(LimitStencilTable {
points: StencilTable {
num_control_vertices,
offsets,
indices,
weights,
},
du_weights,
dv_weights,
})
}
}