Last active
May 19, 2023 16:40
-
-
Save sortofsleepy/375941ae02f151f7523693f7633e2770 to your computer and use it in GitHub Desktop.
example of how to build an instanced sphere while adding additional attributes to the mesh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Builds instanced data for the packing | |
const objdata = useMemo(() => { | |
let sphere = new SphereGeometry(1, widthSegments, heightSegments); | |
// build colors | |
let palette = colors({ | |
numberOfValues: 20 | |
}) | |
const settings = { | |
dimensions, | |
packAttempts, | |
maxCount: numInstances, | |
minRadius, | |
maxRadius, | |
padding | |
} | |
const circles = pack(settings) | |
let positions = new Float32Array(numInstances * 3) | |
let scales = new Float32Array(numInstances) | |
let colorsData = new Float32Array(numInstances * 3) | |
let count = 0 | |
circles.forEach((circle, i) => { | |
positions[count] = circle.position[0] | |
positions[count + 1] = circle.position[1] | |
positions[count + 2] = circle.position[2] | |
scales[i] = circle.radius | |
let index = Math.floor(Math.random() * palette.length) | |
let color = palette[index] | |
colorsData[count] = color[0] | |
colorsData[count + 1] = color[1] | |
colorsData[count + 2] = color[2] | |
count += 3 | |
}) | |
let ipositions = new InstancedBufferAttribute(positions, 3) | |
let iscales = new InstancedBufferAttribute(scales, 1) | |
let icolor = new InstancedBufferAttribute(colorsData,3) | |
return { | |
index: sphere.index, | |
attribs: { | |
iPosition: ipositions, | |
iScale: iscales, | |
iColor:icolor, | |
...sphere.attributes | |
} | |
} | |
}, []) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<mesh}> | |
<instancedBufferGeometry | |
instanceCount={numInstances} | |
index={objdata.index} | |
attributes={objdata.attribs}/> | |
<rawShaderMaterial | |
...<whatever your shader options are> | |
/> | |
</mesh> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uses npm module pack-spheres to determine positions and radius of spheres.