2026-11-29 21:57:28 -06:00
|
|
|
import { invalidate } from "@react-three/fiber";
|
|
|
|
|
import { useEffect, useMemo, type ComponentProps } from "react";
|
|
|
|
|
import { BatchedMesh, Color, type Matrix4, type Mesh } from "three";
|
2026-11-30 22:42:12 -06:00
|
|
|
import { sceneChangeEvent } from "../../core/three/sceneChange";
|
2026-11-29 21:57:28 -06:00
|
|
|
|
|
|
|
|
export interface BatchItem {
|
|
|
|
|
mesh: Mesh;
|
|
|
|
|
matrix: Matrix4;
|
|
|
|
|
// red channel of the instance color, read in shaders with getBatchingColor
|
|
|
|
|
thickness?: number;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type BatchProps = Omit<ComponentProps<"primitive">, "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();
|
|
|
|
|
|
2026-11-30 22:42:12 -06:00
|
|
|
// otherwise the draw list is re-culled, re-sorted and re-uploaded every draw
|
|
|
|
|
batch.perObjectFrustumCulled = false;
|
|
|
|
|
batch.sortObjects = false;
|
|
|
|
|
|
2026-11-29 21:57:28 -06:00
|
|
|
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();
|
2026-11-30 22:42:12 -06:00
|
|
|
sceneChangeEvent.dispatch();
|
2026-11-29 21:57:28 -06:00
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
|
batch.dispose();
|
2026-11-30 22:42:12 -06:00
|
|
|
sceneChangeEvent.dispatch();
|
2026-11-29 21:57:28 -06:00
|
|
|
};
|
|
|
|
|
}, [batch]);
|
|
|
|
|
|
|
|
|
|
if (!batch) return null;
|
|
|
|
|
|
|
|
|
|
return <primitive object={batch} {...props} />;
|
|
|
|
|
}
|