This is a method to set a decal on a mesh in R3F and utilize the vertices with another mesh.
Here are some samples of code from the main file:
1import { useState, useMemo } from 'react';2import { Canvas } from '@react-three/fiber';3import { OrbitControls, Box, Decal as D, Sphere } from '@react-three/drei';4import { Vector3 } from 'three';5import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';678const Spheres = ({ reTriangulatedPositions }) => {9 if (!reTriangulatedPositions || reTriangulatedPositions.length === 0) {10 return null;11 }1213 const randomColor = Math.random() * 0xffffff; // Random color in hex1415 return (16 <group>17 {reTriangulatedPositions.map((s, i) => (18 <Sphere key={i} position={s} args={[0.1, 10, 10]}>19 <meshStandardMaterial color={randomColor} />20 </Sphere>21 ))}22 </group>23 );24};
1const Decal = () => {2 const [decalRef, setDecalRef] = useState([]);3 const [originalRef, setOriginalRef] = useState([]);456 const data = useMemo(() => {7 if (decalRef.geometry && originalRef.geometry) {8 const decalGeom = decalRef.geometry;9 let originalGeom = originalRef.geometry.clone();1011 originalGeom.index = null;1213 const combinedGeom = new BufferGeometryUtils.mergeGeometries([decalGeom, originalGeom], false)14 const vectors = [];1516 if (combinedGeom?.attributes?.position) {17 for (let i = 0; i < combinedGeom.attributes.position.count; i++) {18 vectors.push(new Vector3().fromBufferAttribute(combinedGeom.attributes.position, i))19 }20 }21 return vectors;2223 }24 }, [decalRef, originalRef])2526 return (27 <Canvas>28 <OrbitControls />29 <ambientLight />30 <gridHelper />31 <Box ref={setOriginalRef} args={[1,1,1]}>32 <meshStandardMaterial attach="material" color="orange" wireframe/>33 <D34 ref={setDecalRef}35 position={[0, 0.51, 0]}36 rotation={[0, 0, 0]}37 scale={0.5}38 >39 <planeGeometry args={[1,1,1]} />40 <meshBasicMaterial41 color={'black'}42 polygonOffset43 polygonOffsetFactor={-1}44 wireframe45 />46 </D>47 </Box>48 <Spheres reTriangulatedPositions={data} />49 </Canvas>50 );51};5253export default Decal;
When creating a new geometry using the decal and original vertices, I must account for the fact that the decal does not have an index while the original box buffer geometry does. Consequently, I need to set the cloned original geometry index to null to ensure compatibility between the two buffer geometries.
If there are any inconsistencies or incompatibilities with the attributes, it could lead to a failure of the merge, resulting in a null or an empty object.
Next, I will be creating a combined geometry using a standard mesh and a transparent decal. More details will be provided in the coming days.