Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve linear culling performance #21

Merged
merged 4 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 4 additions & 9 deletions examples/sorting.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,22 @@
import { Asset, Main, PerspectiveCameraAuto } from '@three.ez/main';
import { BufferGeometry, BufferGeometryLoader, MeshNormalMaterial, Scene, Vector3 } from 'three';
import { Main, PerspectiveCameraAuto } from '@three.ez/main';
import { BoxGeometry, MeshNormalMaterial, Scene, Vector3 } from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js';
import { InstancedMesh2 } from '../src/index.js';
import { createRadixSort } from '../src/utils/createRadixSort.js';

const config = {
count: 10000,
count: 100000,
animatedCount: 0,
customSort: true
}

const modelPath = 'https://threejs.org/examples/models/json/suzanne_buffergeometry.json';
const geometry = await Asset.load<BufferGeometry>(BufferGeometryLoader, modelPath);
geometry.computeVertexNormals();

const main = new Main();
const camera = new PerspectiveCameraAuto().translateZ(100);
const scene = new Scene();

const material = new MeshNormalMaterial();
const instancedMesh = new InstancedMesh2(main.renderer, config.count, geometry, material, undefined, true);
const instancedMesh = new InstancedMesh2(main.renderer, config.count, new BoxGeometry(), material);

instancedMesh.createInstances((object) => {
object.position.random().multiplyScalar(100).subScalar(50);
Expand All @@ -43,7 +39,6 @@ scene.on('animate', e => {
for (let i = 0; i < config.animatedCount; i++) {
const mesh = instancedMesh.instances[i];
mesh.rotateOnAxis(axis, e.delta);
// mesh.rotation.x += e.delta;
mesh.updateMatrix();
}
});
Expand Down
23 changes: 13 additions & 10 deletions src/objects/InstancedMesh2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { InstancedEntity, UniformValue, UniformValueNoNumber } from "./Instanced
import { InstancedMeshBVH } from "./InstancedMeshBVH.js";
import { InstancedMeshLOD } from "./InstancedMeshLOD.js";
import { InstancedRenderItem, InstancedRenderList } from "./InstancedRenderList.js";
import { getMaxScaleOnAxisAt, getPositionAt } from "../utils/matrixUtils.js";

// TODO: Add expand and count/maxCount when create?
// TODO: partial texture update
Expand Down Expand Up @@ -453,7 +454,7 @@ export class InstancedMesh2<

if (this.bvh) this.BVHCulling();
else this.linearCulling();

}

if (sortObjects) {
Expand All @@ -480,12 +481,11 @@ export class InstancedMesh2<
if (!this._visibilityChanged) return;

const array = this._indexArray;
const visibilityArray = this.visibilityArray;
const instancesCount = this.instancesCount;
let count = 0;

for (let i = 0; i < instancesCount; i++) {
if (visibilityArray[i]) {
if (this.getVisibilityAt(i)) {
array[count++] = i;
}
}
Expand All @@ -496,10 +496,9 @@ export class InstancedMesh2<

protected updateRenderList(): void {
const instancesCount = this.instancesCount;
const visibilityArray = this.visibilityArray;

for (let i = 0; i < instancesCount; i++) {
if (visibilityArray[i]) {
if (this.getVisibilityAt(i)) {
const matrix = this.getMatrixAt(i); // TODO improve avoiding copy
const depth = _position.setFromMatrixPosition(matrix).sub(_cameraPos).dot(_forward);
_renderList.push(depth, i);
Expand Down Expand Up @@ -532,6 +531,7 @@ export class InstancedMesh2<

protected linearCulling(): void {
const array = this._indexArray;
const matrixArray = this._matrixArray;
const bSphere = this.geometry.boundingSphere;
const radius = bSphere.radius;
const center = bSphere.center;
Expand All @@ -545,10 +545,14 @@ export class InstancedMesh2<
for (let i = 0; i < instancesCount; i++) {
if (!this.getVisibilityAt(i)) continue;

const matrix = this.getMatrixAt(i); // we can optimize this a little avoiding copy? what about using instances if available?
if (geometryCentered) _sphere.center.copy(_position.setFromMatrixPosition(matrix));
else _sphere.center.copy(center).applyMatrix4(matrix);
_sphere.radius = radius * matrix.getMaxScaleOnAxis();
if (geometryCentered) {
getPositionAt(i, matrixArray, _sphere.center);
_sphere.radius = radius * getMaxScaleOnAxisAt(i, matrixArray);
} else {
const matrix = this.getMatrixAt(i); // TODO: can be a little improved
_sphere.center.copy(center).applyMatrix4(matrix);
_sphere.radius = radius * matrix.getMaxScaleOnAxis();
}

if (_frustum.intersectsSphere(_sphere)) {
if (sortObjects) {
Expand Down Expand Up @@ -643,7 +647,6 @@ export class InstancedMesh2<

return this;
}

}

const _box3 = new Box3();
Expand Down
4 changes: 2 additions & 2 deletions src/objects/InstancedMeshBVH.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { box3ToArray, BVH, BVHNode, FloatArray, HybridBuilder, onFrustumIntersec
import { Box3, Matrix4, Raycaster, Sphere, Vector3 } from 'three';
import { InstancedMesh2 } from './InstancedMesh2.js';
import { InstancedMeshLOD, LODLevel } from './InstancedMeshLOD.js';
import { getSphereFromMatrix, SphereTarget } from '../utils/matrixUtils.js';
import { getSphereFromMatrix_centeredGeometry, SphereTarget } from '../utils/matrixUtils.js';

export class InstancedMeshBVH {
public target: InstancedMesh2 | InstancedMeshLOD;
Expand Down Expand Up @@ -166,7 +166,7 @@ export class InstancedMeshBVH {
protected getBox(id: number, array: FloatArray): FloatArray {
// TODO add check if geometry is centered. adjust ref using this._matrixArray insteaad of this.target._matrixArray
if (this._getBoxFromSphere) {
const { centerX, centerY, centerZ, maxScale } = getSphereFromMatrix(id, this.target._matrixArray, this._sphereTarget);
const { centerX, centerY, centerZ, maxScale } = getSphereFromMatrix_centeredGeometry(id, this.target._matrixArray, this._sphereTarget);
const radius = this._geoBoundingSphere.radius * maxScale;
array[0] = centerX - radius;
array[1] = centerX + radius;
Expand Down
46 changes: 8 additions & 38 deletions src/objects/InstancedMeshLOD.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { createTexture_mat4, createTexture_vec4 } from "../utils/createTexture.j
import { BVHParams, Entity, InstancedMesh2, UpdateEntityCallback } from "./InstancedMesh2.js";
import { InstancedMeshBVH } from "./InstancedMeshBVH.js";
import { InstancedRenderItem, InstancedRenderList } from "./InstancedRenderList.js";
import { getMaxScaleOnAxisAt, getPositionAt } from "../utils/matrixUtils.js";

export interface LODLevel<TCustomData = {}> {
distance: number;
Expand Down Expand Up @@ -202,6 +203,7 @@ export class InstancedMeshLOD<TCustomData = {}> extends Object3D {
}

protected BVHCulling(): void {
const matrixArray = this._matrixArray;
const instancesCount = this.instancesCount;
const count = this._countIndexes; // reuse the same? also uintarray?
const indexes = this._indexes;
Expand All @@ -212,7 +214,7 @@ export class InstancedMeshLOD<TCustomData = {}> extends Object3D {
this.bvh.frustumCulling(_projScreenMatrix, (node: BVHNode<{}, number>) => {
const index = node.object;
if (index < instancesCount && visibilityArray[index]) {
const distance = this.getPositionAt(index).distanceToSquared(_cameraPos);
const distance = getPositionAt(index, matrixArray, _position).distanceToSquared(_cameraPos);
_renderList.push(distance, index);
}
});
Expand All @@ -224,7 +226,7 @@ export class InstancedMeshLOD<TCustomData = {}> extends Object3D {
if (index < instancesCount && visibilityArray[index]) {

if (level === null) {
const distance = this.getPositionAt(index).distanceToSquared(_cameraPos); // distance can be get by BVH
const distance = getPositionAt(index, matrixArray, _position).distanceToSquared(_cameraPos); // distance can be get by BVH
level = this.getObjectIndexForDistance(distance);
}

Expand All @@ -237,6 +239,7 @@ export class InstancedMeshLOD<TCustomData = {}> extends Object3D {

protected linearCulling(): void {
const sortObjects = this.sortObjects;
const matrixArray = this._matrixArray;
const bSphere = this.levels[this.levels.length - 1].object.geometry.boundingSphere; // TODO check se esiste?
const radius = bSphere.radius;
const center = bSphere.center;
Expand All @@ -251,9 +254,9 @@ export class InstancedMeshLOD<TCustomData = {}> extends Object3D {
for (let i = 0; i < instancesCount; i++) {
if (!this.visibilityArray[i]) continue; // opt anche nell'altra classe

if (geometryCentered) { //TODO try to use custom sphere implementation
_sphere.center.copy(this.getPositionAt(i));
_sphere.radius = radius * this.getMaxScaleOnAxisAt(i);
if (geometryCentered) {
getPositionAt(i, matrixArray, _sphere.center);
_sphere.radius = radius * getMaxScaleOnAxisAt(i, matrixArray);
} else {
const matrix = this.getMatrixAt(i); // opt this getting only pos and scale
_sphere.center.copy(center).applyMatrix4(matrix);
Expand All @@ -273,40 +276,7 @@ export class InstancedMeshLOD<TCustomData = {}> extends Object3D {
}
}

protected getPositionAt(index: number): Vector3 {
const array = this._matrixArray;
const offset = index * 16;
_position.x = array[offset + 12];
_position.y = array[offset + 13];
_position.z = array[offset + 14];
return _position;
}

protected getMaxScaleOnAxisAt(index: number): number {
const te = this._matrixArray;
const offset = index * 16;

const te0 = te[offset + 0];
const te1 = te[offset + 1];
const te2 = te[offset + 2];

const scaleXSq = te0 * te0 + te1 * te1 + te2 * te2;
const te4 = te[offset + 4];
const te5 = te[offset + 5];
const te6 = te[offset + 6];

const scaleYSq = te4 * te4 + te5 * te5 + te6 * te6;
const te8 = te[offset + 8];
const te9 = te[offset + 9];
const te10 = te[offset + 10];
const scaleZSq = te8 * te8 + te9 * te9 + te10 * te10;

return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq)); // can be improved?

}

// TODO edit raycast

}

// const _box3 = new Box3();
Expand Down
35 changes: 31 additions & 4 deletions src/utils/matrixUtils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { FloatArray } from "bvh.js";
import { Vector3 } from "three";

export interface SphereTarget {
centerX: number;
Expand All @@ -7,11 +8,9 @@ export interface SphereTarget {
maxScale: number;
}

// this method works if geometry is centered
export function getSphereFromMatrix(id: number, array: FloatArray, target: SphereTarget): SphereTarget {
export function getSphereFromMatrix_centeredGeometry(id: number, array: FloatArray, target: SphereTarget): SphereTarget {
const offset = id * 16;

// get max scale from matrix
const m0 = array[offset + 0];
const m1 = array[offset + 1];
const m2 = array[offset + 2];
Expand All @@ -28,10 +27,38 @@ export function getSphereFromMatrix(id: number, array: FloatArray, target: Spher

target.maxScale = Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));

// get position from matrix
target.centerX = array[offset + 12];
target.centerY = array[offset + 13];
target.centerZ = array[offset + 14];

return target;
}

export function getPositionAt(index: number, array: FloatArray, target: Vector3): Vector3 {
const offset = index * 16;
target.x = array[offset + 12];
target.y = array[offset + 13];
target.z = array[offset + 14];
return target;
}

export function getMaxScaleOnAxisAt(index: number, array: FloatArray): number {
const offset = index * 16;

const te0 = array[offset + 0];
const te1 = array[offset + 1];
const te2 = array[offset + 2];
const scaleXSq = te0 * te0 + te1 * te1 + te2 * te2;

const te4 = array[offset + 4];
const te5 = array[offset + 5];
const te6 = array[offset + 6];
const scaleYSq = te4 * te4 + te5 * te5 + te6 * te6;

const te8 = array[offset + 8];
const te9 = array[offset + 9];
const te10 = array[offset + 10];
const scaleZSq = te8 * te8 + te9 * te9 + te10 * te10;

return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
}