import { invalidate } from "@react-three/fiber"; import { useEffect, useMemo, type ComponentProps } from "react"; import { BatchedMesh, Color, type Matrix4, type Mesh } from "three"; import { sceneChangeEvent } from "../../core/three/sceneChange"; export interface BatchItem { mesh: Mesh; matrix: Matrix4; // red channel of the instance color, read in shaders with getBatchingColor thickness?: number; } type BatchProps = Omit, "object"> & { items: BatchItem[]; }; /** * One draw call for all items. Only the geometry is memoized, on the identity * of items; material, renderOrder, shadows, events and so on are plain props. */ export function Batch({ items, ...props }: BatchProps) { const batch = useMemo(() => { if (items.length === 0) return null; let vertices = 0; let indices = 0; for (const { mesh } of items) { vertices += mesh.geometry.attributes.position.count; indices += mesh.geometry.index!.count; } const batch = new BatchedMesh(items.length, vertices, indices); const color = new Color(); // otherwise the draw list is re-culled, re-sorted and re-uploaded every draw batch.perObjectFrustumCulled = false; batch.sortObjects = false; for (const { mesh, matrix, thickness } of items) { const instanceId = batch.addInstance(batch.addGeometry(mesh.geometry)); batch.setMatrixAt(instanceId, matrix); if (thickness !== undefined) { batch.setColorAt(instanceId, color.setRGB(thickness, 0, 0)); } } return batch; }, [items]); useEffect(() => { if (!batch) return; invalidate(); sceneChangeEvent.dispatch(); return () => { batch.dispose(); sceneChangeEvent.dispatch(); }; }, [batch]); if (!batch) return null; return ; }