Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added extra types for instanced Attribute arrays. #2182

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions src/core/Instances.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export type InstancedAttributeProps = JSX.IntrinsicElements['instancedBufferAttr
defaultValue: any
normalized?: boolean
usage?: number
type?: 'float' | 'int' | 'uint' | 'short' | 'ushort' | 'byte'
}

type InstancedMesh = Omit<THREE.InstancedMesh, 'instanceMatrix' | 'instanceColor'> & {
Expand Down Expand Up @@ -282,15 +283,37 @@ export function createInstances<T = InstanceProps>() {
}

export const InstancedAttribute = React.forwardRef(
({ name, defaultValue, normalized, usage = THREE.DynamicDrawUsage }: InstancedAttributeProps, fref) => {
(
{ name, defaultValue, normalized, usage = THREE.DynamicDrawUsage, type = 'float' }: InstancedAttributeProps,
fref
) => {
const ref = React.useRef<THREE.InstancedBufferAttribute>(null!)
React.useImperativeHandle(fref, () => ref.current, [])
React.useLayoutEffect(() => {
const parent = (ref.current as any).__r3f.parent
parent.geometry.attributes[name] = ref.current
const value = Array.isArray(defaultValue) ? defaultValue : [defaultValue]
const array = Array.from({ length: parent.userData.limit }, () => value).flat()
ref.current.array = new Float32Array(array)
switch (type) {
case 'float':
ref.current.array = new Float32Array(array)
break
case 'int':
ref.current.array = new Int32Array(array)
break
case 'uint':
ref.current.array = new Uint32Array(array)
break
case 'short':
ref.current.array = new Int16Array(array)
break
case 'ushort':
ref.current.array = new Uint16Array(array)
break
case 'byte':
ref.current.array = new Uint8Array(array)
break
}
ref.current.itemSize = value.length
ref.current.count = array.length / ref.current.itemSize
return () => {
Expand Down
Loading