use std::cell::{Cell, Ref, RefCell, RefMut};
use std::collections::HashMap;
use std::rc::Rc;
use crate::extras::{from_half_float, to_half_float};
use crate::math::{Matrix3, Matrix4, Vector3};
use crate::nodes::node::BufferId;
use crate::nodes::Type;
#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct AttributeId(usize);
impl AttributeId {
pub(crate) fn next() -> Self {
thread_local! {
static ATTRIBUTE_ID: Cell<usize> = const { Cell::new(0) };
}
ATTRIBUTE_ID.with(|id| {
let next = id.get();
id.set(next + 1);
AttributeId(next)
})
}
pub fn get(&self) -> usize {
self.0
}
}
impl Clone for AttributeId {
fn clone(&self) -> Self {
Self::next()
}
}
impl Default for AttributeId {
fn default() -> Self {
Self::next()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ArrayKind {
F32,
F16,
I8,
U8,
U8Clamped,
I16,
U16,
I32,
U32,
}
impl ArrayKind {
pub fn bytes_per_element(self) -> usize {
match self {
ArrayKind::I8 | ArrayKind::U8 | ArrayKind::U8Clamped => 1,
ArrayKind::F16 | ArrayKind::I16 | ArrayKind::U16 => 2,
ArrayKind::F32 | ArrayKind::I32 | ArrayKind::U32 => 4,
}
}
pub(crate) fn upload_kind(self, normalized: bool, interleaved: bool) -> ArrayKind {
if normalized || interleaved {
return self;
}
match self {
ArrayKind::I8 | ArrayKind::I16 => ArrayKind::I32,
ArrayKind::U8 | ArrayKind::U16 => ArrayKind::U32,
kind => kind,
}
}
pub fn vertex_format(
self,
item_size: usize,
normalized: bool,
interleaved: bool,
) -> (wgpu::VertexFormat, usize) {
use wgpu::VertexFormat as F;
let unsupported = || -> ! {
panic!(
"THREE.WebGPUAttributeUtils: Vertex format not supported yet. \
({self:?}, itemSize {item_size}, normalized {normalized}, interleaved {interleaved})"
)
};
assert!(
(1..=4).contains(&item_size),
"three-rs: a vertex attribute has 1 to 4 components, not {item_size}"
);
let kind = self.upload_kind(normalized, interleaved);
if item_size == 1 {
let format = match kind {
ArrayKind::I32 => F::Sint32,
ArrayKind::U32 => F::Uint32,
ArrayKind::F32 => F::Float32,
_ => unsupported(),
};
return (format, 1);
}
let bpe = kind.bytes_per_element();
let padded = (bpe * item_size).div_ceil(4) * 4 / bpe;
let format = match (kind, normalized, padded) {
(ArrayKind::F32, false, 2) => F::Float32x2,
(ArrayKind::F32, false, 3) => F::Float32x3,
(ArrayKind::F32, false, 4) => F::Float32x4,
(ArrayKind::I32, false, 2) => F::Sint32x2,
(ArrayKind::I32, false, 3) => F::Sint32x3,
(ArrayKind::I32, false, 4) => F::Sint32x4,
(ArrayKind::U32, false, 2) => F::Uint32x2,
(ArrayKind::U32, false, 3) => F::Uint32x3,
(ArrayKind::U32, false, 4) => F::Uint32x4,
(ArrayKind::F16, false, 2) => F::Float16x2,
(ArrayKind::F16, false, 4) => F::Float16x4,
(ArrayKind::I16, false, 2) => F::Sint16x2,
(ArrayKind::I16, false, 4) => F::Sint16x4,
(ArrayKind::I16, true, 2) => F::Snorm16x2,
(ArrayKind::I16, true, 4) => F::Snorm16x4,
(ArrayKind::U16, false, 2) => F::Uint16x2,
(ArrayKind::U16, false, 4) => F::Uint16x4,
(ArrayKind::U16, true, 2) => F::Unorm16x2,
(ArrayKind::U16, true, 4) => F::Unorm16x4,
(ArrayKind::I8, false, 4) => F::Sint8x4,
(ArrayKind::I8, true, 4) => F::Snorm8x4,
(ArrayKind::U8, false, 4) => F::Uint8x4,
(ArrayKind::U8, true, 4) => F::Unorm8x4,
_ => unsupported(),
};
(format, padded)
}
pub fn shader_type(self, item_size: usize, normalized: bool) -> Type {
let component = if normalized {
Type::F32
} else {
match self {
ArrayKind::I8 | ArrayKind::I16 | ArrayKind::I32 => Type::I32,
ArrayKind::U8 | ArrayKind::U16 | ArrayKind::U32 => Type::U32,
ArrayKind::F32 | ArrayKind::F16 | ArrayKind::U8Clamped => Type::F32,
}
};
if item_size == 1 {
component
} else {
Type::vector_of(component, item_size)
}
}
fn denormalize(self, value: f64) -> f64 {
match self {
ArrayKind::F32 => value,
ArrayKind::U32 => value / 4294967295.0,
ArrayKind::U16 | ArrayKind::F16 => value / 65535.0,
ArrayKind::U8 | ArrayKind::U8Clamped => value / 255.0,
ArrayKind::I32 => (value / 2147483647.0).max(-1.0),
ArrayKind::I16 => (value / 32767.0).max(-1.0),
ArrayKind::I8 => (value / 127.0).max(-1.0),
}
}
fn normalize(self, value: f64) -> f64 {
let scale = match self {
ArrayKind::F32 => return value,
ArrayKind::U32 => 4294967295.0,
ArrayKind::U16 | ArrayKind::F16 => 65535.0,
ArrayKind::U8 | ArrayKind::U8Clamped => 255.0,
ArrayKind::I32 => 2147483647.0,
ArrayKind::I16 => 32767.0,
ArrayKind::I8 => 127.0,
};
js_round(value * scale)
}
}
fn padded_item_size(kind: ArrayKind, item_size: usize, storage: bool) -> usize {
if storage && item_size == 3 {
return 4;
}
let bpe = kind.bytes_per_element();
if item_size > 1 && !(item_size * bpe).is_multiple_of(4) {
(item_size * bpe).div_ceil(4) * 4 / bpe
} else {
item_size
}
}
fn js_round(x: f64) -> f64 {
(x + 0.5).floor()
}
fn js_wrap(value: f64, bits: i32) -> u64 {
if !value.is_finite() {
return 0;
}
value.trunc().rem_euclid(2f64.powi(bits)) as u64
}
#[derive(Clone, Debug, PartialEq)]
pub enum TypedArray {
F32(Vec<f32>),
F16(Vec<u16>),
I8(Vec<i8>),
U8(Vec<u8>),
U8Clamped(Vec<u8>),
I16(Vec<i16>),
U16(Vec<u16>),
I32(Vec<i32>),
U32(Vec<u32>),
}
macro_rules! each_array {
($array:expr, $v:ident => $body:expr) => {
match $array {
TypedArray::F32($v) => $body,
TypedArray::F16($v) => $body,
TypedArray::I8($v) => $body,
TypedArray::U8($v) => $body,
TypedArray::U8Clamped($v) => $body,
TypedArray::I16($v) => $body,
TypedArray::U16($v) => $body,
TypedArray::I32($v) => $body,
TypedArray::U32($v) => $body,
}
};
}
impl TypedArray {
pub(crate) fn zeros(kind: ArrayKind, len: usize) -> Self {
match kind {
ArrayKind::F32 => TypedArray::F32(vec![0.0; len]),
ArrayKind::F16 => TypedArray::F16(vec![0; len]),
ArrayKind::I8 => TypedArray::I8(vec![0; len]),
ArrayKind::U8 => TypedArray::U8(vec![0; len]),
ArrayKind::U8Clamped => TypedArray::U8Clamped(vec![0; len]),
ArrayKind::I16 => TypedArray::I16(vec![0; len]),
ArrayKind::U16 => TypedArray::U16(vec![0; len]),
ArrayKind::I32 => TypedArray::I32(vec![0; len]),
ArrayKind::U32 => TypedArray::U32(vec![0; len]),
}
}
pub(crate) fn from_f64(kind: ArrayKind, values: &[f64]) -> Self {
let mut array = Self::zeros(kind, values.len());
for (i, v) in values.iter().enumerate() {
array.set(i, *v);
}
array
}
pub(crate) fn from_le_bytes(kind: ArrayKind, bytes: &[u8]) -> Self {
let bpe = kind.bytes_per_element();
assert!(
bytes.len().is_multiple_of(bpe),
"three-rs: byte length of {kind:?} should be a multiple of {bpe}, got {}",
bytes.len()
);
fn words<const N: usize, T>(bytes: &[u8], f: impl Fn([u8; N]) -> T) -> Vec<T> {
bytes.as_chunks::<N>().0.iter().map(|w| f(*w)).collect()
}
match kind {
ArrayKind::F32 => TypedArray::F32(words(bytes, f32::from_le_bytes)),
ArrayKind::F16 => TypedArray::F16(words(bytes, u16::from_le_bytes)),
ArrayKind::I8 => TypedArray::I8(bytes.iter().map(|&b| b as i8).collect()),
ArrayKind::U8 => TypedArray::U8(bytes.to_vec()),
ArrayKind::U8Clamped => TypedArray::U8Clamped(bytes.to_vec()),
ArrayKind::I16 => TypedArray::I16(words(bytes, i16::from_le_bytes)),
ArrayKind::U16 => TypedArray::U16(words(bytes, u16::from_le_bytes)),
ArrayKind::I32 => TypedArray::I32(words(bytes, i32::from_le_bytes)),
ArrayKind::U32 => TypedArray::U32(words(bytes, u32::from_le_bytes)),
}
}
pub fn kind(&self) -> ArrayKind {
match self {
TypedArray::F32(_) => ArrayKind::F32,
TypedArray::F16(_) => ArrayKind::F16,
TypedArray::I8(_) => ArrayKind::I8,
TypedArray::U8(_) => ArrayKind::U8,
TypedArray::U8Clamped(_) => ArrayKind::U8Clamped,
TypedArray::I16(_) => ArrayKind::I16,
TypedArray::U16(_) => ArrayKind::U16,
TypedArray::I32(_) => ArrayKind::I32,
TypedArray::U32(_) => ArrayKind::U32,
}
}
pub fn len(&self) -> usize {
each_array!(self, v => v.len())
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, index: usize) -> f64 {
match self {
TypedArray::F32(v) => v[index] as f64,
TypedArray::F16(v) => v[index] as f64,
TypedArray::I8(v) => v[index] as f64,
TypedArray::U8(v) => v[index] as f64,
TypedArray::U8Clamped(v) => v[index] as f64,
TypedArray::I16(v) => v[index] as f64,
TypedArray::U16(v) => v[index] as f64,
TypedArray::I32(v) => v[index] as f64,
TypedArray::U32(v) => v[index] as f64,
}
}
pub fn set(&mut self, index: usize, value: f64) {
match self {
TypedArray::F32(v) => v[index] = value as f32,
TypedArray::F16(v) | TypedArray::U16(v) => v[index] = js_wrap(value, 16) as u16,
TypedArray::I8(v) => v[index] = js_wrap(value, 8) as u8 as i8,
TypedArray::U8(v) => v[index] = js_wrap(value, 8) as u8,
TypedArray::U8Clamped(v) => {
v[index] = if value.is_nan() {
0
} else {
value.clamp(0.0, 255.0).round_ties_even() as u8
}
}
TypedArray::I16(v) => v[index] = js_wrap(value, 16) as u16 as i16,
TypedArray::I32(v) => v[index] = js_wrap(value, 32) as u32 as i32,
TypedArray::U32(v) => v[index] = js_wrap(value, 32) as u32,
}
}
fn copy_element(&mut self, to: usize, other: &TypedArray, from: usize) {
self.set(to, other.get(from));
}
pub fn vertex_format(
&self,
item_size: usize,
normalized: bool,
interleaved: bool,
) -> (wgpu::VertexFormat, usize) {
self.kind()
.vertex_format(item_size, normalized, interleaved)
}
pub fn as_f32(&self) -> Option<&Vec<f32>> {
match self {
TypedArray::F32(v) => Some(v),
_ => None,
}
}
pub fn as_f32_mut(&mut self) -> Option<&mut Vec<f32>> {
match self {
TypedArray::F32(v) => Some(v),
_ => None,
}
}
fn push_bytes(&self, index: usize, kind: ArrayKind, out: &mut Vec<u8>) {
match (self, kind) {
(TypedArray::F32(v), _) => out.extend_from_slice(&v[index].to_le_bytes()),
(TypedArray::I8(v), ArrayKind::I32) => {
out.extend_from_slice(&(v[index] as i32).to_le_bytes())
}
(TypedArray::I16(v), ArrayKind::I32) => {
out.extend_from_slice(&(v[index] as i32).to_le_bytes())
}
(TypedArray::U8(v), ArrayKind::U32) => {
out.extend_from_slice(&(v[index] as u32).to_le_bytes())
}
(TypedArray::U16(v), ArrayKind::U32) => {
out.extend_from_slice(&(v[index] as u32).to_le_bytes())
}
(TypedArray::F16(v) | TypedArray::U16(v), _) => {
out.extend_from_slice(&v[index].to_le_bytes())
}
(TypedArray::I8(v), _) => out.push(v[index] as u8),
(TypedArray::U8(v) | TypedArray::U8Clamped(v), _) => out.push(v[index]),
(TypedArray::I16(v), _) => out.extend_from_slice(&v[index].to_le_bytes()),
(TypedArray::I32(v), _) => out.extend_from_slice(&v[index].to_le_bytes()),
(TypedArray::U32(v), _) => out.extend_from_slice(&v[index].to_le_bytes()),
}
}
pub(crate) fn to_bytes(
&self,
kind: ArrayKind,
item_size: usize,
padded_item_size: usize,
) -> Vec<u8> {
let bpe = kind.bytes_per_element();
let count = self.len() / item_size.max(1);
let mut out = Vec::with_capacity(count * padded_item_size * bpe + 4);
if padded_item_size == item_size {
for i in 0..self.len() {
self.push_bytes(i, kind, &mut out);
}
} else {
for item in 0..count {
for c in 0..item_size {
self.push_bytes(item * item_size + c, kind, &mut out);
}
out.resize(out.len() + (padded_item_size - item_size) * bpe, 0);
}
}
out.resize(out.len().div_ceil(4) * 4, 0);
out
}
}
impl From<Vec<f32>> for TypedArray {
fn from(v: Vec<f32>) -> Self {
TypedArray::F32(v)
}
}
impl From<Vec<i8>> for TypedArray {
fn from(v: Vec<i8>) -> Self {
TypedArray::I8(v)
}
}
impl From<Vec<u8>> for TypedArray {
fn from(v: Vec<u8>) -> Self {
TypedArray::U8(v)
}
}
impl From<Vec<i16>> for TypedArray {
fn from(v: Vec<i16>) -> Self {
TypedArray::I16(v)
}
}
impl From<Vec<u16>> for TypedArray {
fn from(v: Vec<u16>) -> Self {
TypedArray::U16(v)
}
}
impl From<Vec<i32>> for TypedArray {
fn from(v: Vec<i32>) -> Self {
TypedArray::I32(v)
}
}
impl From<Vec<u32>> for TypedArray {
fn from(v: Vec<u32>) -> Self {
TypedArray::U32(v)
}
}
fn f32_ref(array: Ref<'_, TypedArray>) -> Ref<'_, Vec<f32>> {
Ref::map(array, |a| match a {
TypedArray::F32(v) => v,
other => panic_not_f32(other.kind()),
})
}
fn f32_ref_mut(array: RefMut<'_, TypedArray>) -> RefMut<'_, Vec<f32>> {
RefMut::map(array, |a| match a {
TypedArray::F32(v) => v,
other => panic_not_f32(other.kind()),
})
}
fn panic_not_f32(kind: ArrayKind) -> ! {
panic!(
"three-rs: array() is the Float32Array view, and this attribute's array is {kind:?}; \
read it with data()"
)
}
#[derive(Debug)]
pub struct InterleavedBuffer {
id: AttributeId,
array: RefCell<TypedArray>,
stride: usize,
version: Cell<u32>,
instanced: bool,
mesh_per_attribute: usize,
}
impl InterleavedBuffer {
pub fn new(array: impl Into<TypedArray>, stride: usize) -> Self {
Self {
id: AttributeId::next(),
array: RefCell::new(array.into()),
stride,
version: Cell::new(0),
instanced: false,
mesh_per_attribute: 1,
}
}
pub fn new_instanced(
array: impl Into<TypedArray>,
stride: usize,
mesh_per_attribute: usize,
) -> Self {
Self {
instanced: true,
mesh_per_attribute,
..Self::new(array, stride)
}
}
pub fn id(&self) -> usize {
self.id.get()
}
pub fn array(&self) -> Ref<'_, Vec<f32>> {
f32_ref(self.array.borrow())
}
pub fn array_mut(&self) -> RefMut<'_, Vec<f32>> {
f32_ref_mut(self.array.borrow_mut())
}
pub fn data(&self) -> Ref<'_, TypedArray> {
self.array.borrow()
}
pub fn data_mut(&self) -> RefMut<'_, TypedArray> {
self.array.borrow_mut()
}
pub fn stride(&self) -> usize {
self.stride
}
pub fn count(&self) -> usize {
self.array.borrow().len() / self.stride
}
pub fn version(&self) -> u32 {
self.version.get()
}
pub fn set_needs_update(&self) {
self.version.set(self.version.get() + 1);
}
pub fn is_instanced(&self) -> bool {
self.instanced
}
pub fn mesh_per_attribute(&self) -> usize {
self.mesh_per_attribute
}
pub fn copy_at(&self, index1: usize, other: &InterleavedBuffer, index2: usize) -> &Self {
let index1 = index1 * self.stride;
let index2 = index2 * other.stride;
if std::ptr::eq(self, other) {
let mut array = self.array.borrow_mut();
for i in 0..self.stride {
let v = array.get(index2 + i);
array.set(index1 + i, v);
}
} else {
let source = other.array.borrow();
let mut array = self.array.borrow_mut();
for i in 0..self.stride {
array.copy_element(index1 + i, &source, index2 + i);
}
}
self
}
pub fn set(&self, value: &[f32], offset: usize) -> &Self {
let mut array = self.array.borrow_mut();
for (i, v) in value.iter().enumerate() {
array.set(offset + i, *v as f64);
}
self
}
pub fn copy(&mut self, source: &InterleavedBuffer) -> &mut Self {
*self.array.get_mut() = source.array.borrow().clone();
self.stride = source.stride;
if self.instanced {
self.mesh_per_attribute = source.mesh_per_attribute;
}
self
}
}
impl Clone for InterleavedBuffer {
fn clone(&self) -> Self {
Self {
id: AttributeId::next(),
array: RefCell::new(self.array.borrow().clone()),
stride: self.stride,
version: Cell::new(0),
instanced: self.instanced,
mesh_per_attribute: self.mesh_per_attribute,
}
}
}
#[derive(Clone, Debug)]
pub enum StorageContents {
Count(usize),
Array(TypedArray),
}
impl From<usize> for StorageContents {
fn from(count: usize) -> Self {
StorageContents::Count(count)
}
}
impl From<TypedArray> for StorageContents {
fn from(array: TypedArray) -> Self {
StorageContents::Array(array)
}
}
impl From<Vec<f32>> for StorageContents {
fn from(array: Vec<f32>) -> Self {
StorageContents::Array(TypedArray::F32(array))
}
}
#[derive(Clone, Debug)]
pub struct StorageBufferAttribute {
id: BufferId,
array: Rc<RefCell<TypedArray>>,
pub item_size: usize,
instanced: bool,
}
impl StorageBufferAttribute {
pub fn new(contents: impl Into<StorageContents>, item_size: usize, kind: ArrayKind) -> Self {
let array = match contents.into() {
StorageContents::Count(count) => TypedArray::zeros(kind, count * item_size),
StorageContents::Array(array) => array,
};
Self {
id: BufferId::next(),
array: Rc::new(RefCell::new(array)),
item_size,
instanced: false,
}
}
pub fn new_instanced(
contents: impl Into<StorageContents>,
item_size: usize,
kind: ArrayKind,
) -> Self {
Self {
instanced: true,
..Self::new(contents, item_size, kind)
}
}
pub fn id(&self) -> BufferId {
self.id
}
pub fn count(&self) -> usize {
self.array.borrow().len() / self.item_size
}
pub fn data(&self) -> Ref<'_, TypedArray> {
self.array.borrow()
}
pub fn is_instanced(&self) -> bool {
self.instanced
}
pub(crate) fn upload_kind(&self, normalized: bool) -> ArrayKind {
self.array.borrow().kind().upload_kind(normalized, false)
}
pub(crate) fn padded_item_size(&self, normalized: bool) -> usize {
padded_item_size(self.upload_kind(normalized), self.item_size, true)
}
pub(crate) fn init_words(&self, normalized: bool) -> Vec<u32> {
let kind = self.upload_kind(normalized);
let padded = self.padded_item_size(normalized);
let array = self.array.borrow();
let bytes = array.to_bytes(kind, self.item_size, padded);
bytes
.as_chunks::<4>()
.0
.iter()
.map(|w| u32::from_le_bytes(*w))
.collect()
}
}
impl From<StorageBufferAttribute> for BufferAttribute {
fn from(storage: StorageBufferAttribute) -> Self {
let instanced = storage.instanced;
let item_size = storage.item_size;
Self {
id: AttributeId::next(),
storage: Backing::Storage(storage),
item_size,
normalized: false,
version: Cell::new(0),
instanced,
}
}
}
#[derive(Debug)]
enum Backing {
Own(RefCell<TypedArray>),
Interleaved {
data: Rc<InterleavedBuffer>,
offset: usize,
},
Storage(StorageBufferAttribute),
}
#[derive(Debug)]
pub struct BufferAttribute {
pub id: AttributeId,
storage: Backing,
pub item_size: usize,
pub normalized: bool,
version: Cell<u32>,
instanced: bool,
}
macro_rules! typed_constructors {
($($(#[$doc:meta])* $name:ident($elem:ty) => $variant:ident;)*) => {
$(
$(#[$doc])*
pub fn $name(array: Vec<$elem>, item_size: usize, normalized: bool) -> Self {
Self::from_typed(TypedArray::$variant(array), item_size, normalized)
}
)*
};
}
impl BufferAttribute {
pub fn new(array: Vec<f32>, item_size: usize) -> Self {
Self::from_typed(TypedArray::F32(array), item_size, false)
}
pub fn from_typed(array: TypedArray, item_size: usize, normalized: bool) -> Self {
Self {
id: AttributeId::next(),
storage: Backing::Own(RefCell::new(array)),
item_size,
normalized,
version: Cell::new(0),
instanced: false,
}
}
typed_constructors! {
int8(i8) => I8;
uint8(u8) => U8;
uint8_clamped(u8) => U8Clamped;
int16(i16) => I16;
uint16(u16) => U16;
int32(i32) => I32;
uint32(u32) => U32;
}
pub fn float16(array: Vec<u16>, item_size: usize, normalized: bool) -> Self {
Self::from_typed(TypedArray::F16(array), item_size, normalized)
}
pub fn new_instanced(array: Vec<f32>, item_size: usize) -> Self {
Self::from_typed_instanced(TypedArray::F32(array), item_size, false)
}
pub fn from_typed_instanced(array: TypedArray, item_size: usize, normalized: bool) -> Self {
Self {
instanced: true,
..Self::from_typed(array, item_size, normalized)
}
}
pub fn interleaved(
data: Rc<InterleavedBuffer>,
item_size: usize,
offset: usize,
normalized: bool,
) -> Self {
Self {
id: AttributeId::next(),
storage: Backing::Interleaved { data, offset },
item_size,
normalized,
version: Cell::new(0),
instanced: false,
}
}
pub fn is_instanced(&self) -> bool {
match &self.storage {
Backing::Interleaved { data, .. } => data.is_instanced(),
_ => self.instanced,
}
}
pub fn is_interleaved(&self) -> bool {
matches!(self.storage, Backing::Interleaved { .. })
}
pub fn data_buffer(&self) -> Option<&Rc<InterleavedBuffer>> {
match &self.storage {
Backing::Interleaved { data, .. } => Some(data),
_ => None,
}
}
pub fn offset(&self) -> usize {
match &self.storage {
Backing::Interleaved { offset, .. } => *offset,
_ => 0,
}
}
pub(crate) fn storage_buffer(&self) -> Option<&StorageBufferAttribute> {
match &self.storage {
Backing::Storage(storage) => Some(storage),
_ => None,
}
}
fn cell(&self) -> &RefCell<TypedArray> {
match &self.storage {
Backing::Own(array) => array,
Backing::Interleaved { data, .. } => &data.array,
Backing::Storage(storage) => &storage.array,
}
}
fn layout(&self) -> (usize, usize) {
match &self.storage {
Backing::Interleaved { data, offset } => (data.stride, *offset),
_ => (self.item_size, 0),
}
}
pub fn kind(&self) -> ArrayKind {
self.cell().borrow().kind()
}
pub fn array(&self) -> Ref<'_, Vec<f32>> {
f32_ref(self.cell().borrow())
}
pub fn array_mut(&self) -> RefMut<'_, Vec<f32>> {
f32_ref_mut(self.cell().borrow_mut())
}
pub fn data(&self) -> Ref<'_, TypedArray> {
self.cell().borrow()
}
pub fn data_mut(&self) -> RefMut<'_, TypedArray> {
self.cell().borrow_mut()
}
pub fn version(&self) -> u32 {
match &self.storage {
Backing::Interleaved { data, .. } => data.version(),
_ => self.version.get(),
}
}
pub fn set_needs_update(&self) {
match &self.storage {
Backing::Interleaved { data, .. } => data.set_needs_update(),
_ => self.version.set(self.version.get() + 1),
}
}
pub fn count(&self) -> usize {
match &self.storage {
Backing::Interleaved { data, .. } => data.count(),
_ => self.cell().borrow().len() / self.item_size,
}
}
pub fn get_component(&self, index: usize, component: usize) -> f64 {
let (stride, offset) = self.layout();
let array = self.cell().borrow();
let kind = array.kind();
let mut value = array.get(offset + index * stride + component);
if kind == ArrayKind::F16 {
value = from_half_float(value as u16) as f64;
}
if self.normalized {
value = kind.denormalize(value);
}
value
}
pub fn set_component(&mut self, index: usize, component: usize, value: f64) -> &mut Self {
self.store(index, component, value);
self
}
pub(crate) fn store(&self, index: usize, component: usize, value: f64) {
let (stride, offset) = self.layout();
let mut array = self.cell().borrow_mut();
let kind = array.kind();
let mut value = value;
if self.normalized {
value = kind.normalize(value);
}
if kind == ArrayKind::F16 {
value = to_half_float(value) as f64;
}
array.set(offset + index * stride + component, value);
}
pub fn get_x(&self, index: usize) -> f64 {
self.get_component(index, 0)
}
pub fn get_y(&self, index: usize) -> f64 {
self.get_component(index, 1)
}
pub fn get_z(&self, index: usize) -> f64 {
self.get_component(index, 2)
}
pub fn get_w(&self, index: usize) -> f64 {
self.get_component(index, 3)
}
pub fn set_x(&mut self, index: usize, x: f64) -> &mut Self {
self.set_component(index, 0, x)
}
pub fn set_y(&mut self, index: usize, y: f64) -> &mut Self {
self.set_component(index, 1, y)
}
pub fn set_z(&mut self, index: usize, z: f64) -> &mut Self {
self.set_component(index, 2, z)
}
pub fn set_w(&mut self, index: usize, w: f64) -> &mut Self {
self.set_component(index, 3, w)
}
pub fn set_xy(&mut self, index: usize, x: f64, y: f64) -> &mut Self {
self.store(index, 0, x);
self.store(index, 1, y);
self
}
pub fn set_xyz(&mut self, index: usize, x: f64, y: f64, z: f64) {
self.store(index, 0, x);
self.store(index, 1, y);
self.store(index, 2, z);
}
pub fn set_xyzw(&mut self, index: usize, x: f64, y: f64, z: f64, w: f64) -> &mut Self {
self.store(index, 0, x);
self.store(index, 1, y);
self.store(index, 2, z);
self.store(index, 3, w);
self
}
pub fn copy_at(&mut self, index1: usize, attribute: &Self, index2: usize) -> &mut Self {
let (stride1, offset1) = self.layout();
let (stride2, offset2) = attribute.layout();
let base1 = offset1 + index1 * stride1;
let base2 = offset2 + index2 * stride2;
if std::ptr::eq(self.cell(), attribute.cell()) {
let mut array = self.cell().borrow_mut();
for i in 0..self.item_size {
let v = array.get(base2 + i);
array.set(base1 + i, v);
}
} else {
let source = attribute.cell().borrow();
let mut array = self.cell().borrow_mut();
for i in 0..self.item_size {
array.copy_element(base1 + i, &source, base2 + i);
}
}
self
}
pub fn copy_array(&mut self, array: &[f32]) -> &mut Self {
let mut target = self.cell().borrow_mut();
assert!(
array.len() <= target.len(),
"three-rs: copy_array(): offset is out of bounds ({} elements into {})",
array.len(),
target.len()
);
if let Some(v) = target.as_f32_mut() {
v[..array.len()].copy_from_slice(array);
} else {
for (i, v) in array.iter().enumerate() {
target.set(i, *v as f64);
}
}
drop(target);
self
}
pub fn set(&mut self, value: &[f32], offset: usize) -> &mut Self {
let mut target = self.cell().borrow_mut();
if let Some(v) = target.as_f32_mut() {
v[offset..offset + value.len()].copy_from_slice(value);
} else {
for (i, v) in value.iter().enumerate() {
target.set(offset + i, *v as f64);
}
}
drop(target);
self
}
pub fn copy(&mut self, source: &BufferAttribute) -> &mut Self {
self.storage = match &source.storage {
Backing::Own(array) => Backing::Own(RefCell::new(array.borrow().clone())),
Backing::Interleaved { data, offset } => Backing::Interleaved {
data: data.clone(),
offset: *offset,
},
Backing::Storage(storage) => Backing::Own(RefCell::new(storage.array.borrow().clone())),
};
self.item_size = source.item_size;
self.normalized = source.normalized;
self.instanced = source.instanced;
self
}
pub(crate) fn to_f32_items(&self) -> Vec<f32> {
if let Backing::Own(array) = &self.storage {
if let Some(v) = array.borrow().as_f32() {
return v.clone();
}
}
(0..self.count())
.flat_map(|i| (0..self.item_size).map(move |c| self.get_component(i, c) as f32))
.collect()
}
pub fn get_vector3(&self, index: usize) -> Vector3 {
Vector3::new(self.get_x(index), self.get_y(index), self.get_z(index))
}
pub fn apply_matrix4(&mut self, m: &Matrix4) {
for i in 0..self.count() {
let mut v = self.get_vector3(i);
v.apply_matrix4(m);
self.set_xyz(i, v.x, v.y, v.z);
}
}
pub fn apply_normal_matrix(&mut self, m: &Matrix3) {
for i in 0..self.count() {
let mut v = self.get_vector3(i);
v.apply_normal_matrix(m);
self.set_xyz(i, v.x, v.y, v.z);
}
}
fn gather_array(&self, indices: Option<&[usize]>) -> TypedArray {
let (stride, offset) = self.layout();
let source = self.cell().borrow();
let n = self.item_size;
let count = indices.map_or(self.count(), <[usize]>::len);
let mut out = TypedArray::zeros(source.kind(), count * n);
for k in 0..count {
let item = indices.map_or(k, |indices| indices[k]);
for c in 0..n {
out.copy_element(k * n + c, &source, offset + item * stride + c);
}
}
out
}
pub(crate) fn gather(&self, indices: &[usize]) -> BufferAttribute {
BufferAttribute::from_typed(
self.gather_array(Some(indices)),
self.item_size,
self.normalized,
)
}
pub(crate) fn clone_with(
&self,
buffers: &mut HashMap<usize, Rc<InterleavedBuffer>>,
) -> BufferAttribute {
match &self.storage {
Backing::Interleaved { data, offset } => {
let data = buffers
.entry(data.id())
.or_insert_with(|| Rc::new((**data).clone()))
.clone();
BufferAttribute::interleaved(data, self.item_size, *offset, self.normalized)
}
_ => self.clone(),
}
}
pub(crate) fn buffer_key(&self) -> BufferKey {
match &self.storage {
Backing::Own(_) => BufferKey::Attribute(self.id.get()),
Backing::Interleaved { data, .. } => BufferKey::Interleaved(data.id()),
Backing::Storage(storage) => BufferKey::Storage(storage.id()),
}
}
pub(crate) fn upload_bytes(&self) -> Vec<u8> {
match &self.storage {
Backing::Interleaved { data, .. } => {
let array = data.array.borrow();
array.to_bytes(array.kind(), 1, 1)
}
Backing::Own(array) => {
let array = array.borrow();
let kind = array.kind().upload_kind(self.normalized, false);
let padded = padded_item_size(kind, self.item_size, false);
array.to_bytes(kind, self.item_size, padded)
}
Backing::Storage(storage) => storage
.init_words(self.normalized)
.iter()
.flat_map(|w| w.to_le_bytes())
.collect(),
}
}
pub(crate) fn desc(&self, name: &str, group: usize) -> AttributeDesc {
let layout = match &self.storage {
Backing::Own(_) => AttributeLayout::Own,
Backing::Interleaved { data, offset } => AttributeLayout::Interleaved {
buffer: group,
stride: data.stride,
offset: *offset,
},
Backing::Storage(storage) => AttributeLayout::Storage {
padded_item_size: storage.padded_item_size(self.normalized),
},
};
AttributeDesc {
name: name.to_string(),
kind: self.kind(),
item_size: self.item_size,
normalized: self.normalized,
instanced: self.is_instanced(),
layout,
}
}
}
impl Clone for BufferAttribute {
fn clone(&self) -> Self {
let storage = match &self.storage {
Backing::Own(array) => Backing::Own(RefCell::new(array.borrow().clone())),
Backing::Interleaved { .. } => Backing::Own(RefCell::new(self.gather_array(None))),
Backing::Storage(storage) => Backing::Storage(StorageBufferAttribute {
id: BufferId::next(),
array: Rc::new(RefCell::new(storage.array.borrow().clone())),
item_size: storage.item_size,
instanced: storage.instanced,
}),
};
Self {
id: AttributeId::next(),
storage,
item_size: self.item_size,
normalized: self.normalized,
version: Cell::new(0),
instanced: self.instanced,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum BufferKey {
Attribute(usize),
Interleaved(usize),
Storage(BufferId),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[doc(hidden)]
pub enum AttributeLayout {
Own,
Interleaved {
buffer: usize,
stride: usize,
offset: usize,
},
Storage {
padded_item_size: usize,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[doc(hidden)]
pub struct AttributeDesc {
pub name: String,
pub kind: ArrayKind,
pub item_size: usize,
pub normalized: bool,
pub instanced: bool,
pub layout: AttributeLayout,
}
impl AttributeDesc {
pub fn shader_type(&self) -> Type {
self.kind.shader_type(self.item_size, self.normalized)
}
pub fn vertex_format(&self) -> wgpu::VertexFormat {
let interleaved = matches!(self.layout, AttributeLayout::Interleaved { .. });
self.kind
.vertex_format(self.item_size, self.normalized, interleaved)
.0
}
pub fn array_stride(&self) -> u64 {
let stride = match self.layout {
AttributeLayout::Own => {
let kind = self.kind.upload_kind(self.normalized, false);
(self.item_size * kind.bytes_per_element()).div_ceil(4) * 4
}
AttributeLayout::Interleaved { stride, .. } => stride * self.kind.bytes_per_element(),
AttributeLayout::Storage { padded_item_size } => {
let kind = self.kind.upload_kind(self.normalized, false);
padded_item_size * kind.bytes_per_element()
}
};
stride as u64
}
pub fn offset(&self) -> u64 {
match self.layout {
AttributeLayout::Interleaved { offset, .. } => {
(offset * self.kind.bytes_per_element()) as u64
}
_ => 0,
}
}
}