mirror of
https://github.com/blitzkit/blitzkit.git
synced 2026-12-04 23:32:54 +01:00
apply batched mesh to all things
This commit is contained in:
21 files changed
+844
-892
No files matched your search
@@ -0,0 +1,61 @@
|
||||
import { invalidate } from "@react-three/fiber";
|
||||
import { useEffect, useMemo, type ComponentProps } from "react";
|
||||
import { BatchedMesh, Color, type Matrix4, type Mesh } from "three";
|
||||
|
||||
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();
|
||||
|
||||
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();
|
||||
|
||||
return () => {
|
||||
batch.dispose();
|
||||
};
|
||||
}, [batch]);
|
||||
|
||||
if (!batch) return null;
|
||||
|
||||
return <primitive object={batch} {...props} />;
|
||||
}
|
||||
Reference in new issue
Block a user