Created
May 19, 2020 22:53
-
-
Save pailhead/adf2dbeb009ab3227ee0241fd1737809 to your computer and use it in GitHub Desktop.
sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Vector3, Camera } from 'three' | |
class IndexedVector3 extends Vector3 { | |
constructor(public readonly index: number, public bufferIndex: number = -1) { | |
super() | |
} | |
} | |
export class ParticleSorter { | |
private _currentBuffer: number[] = [] | |
private _pool: IndexedVector3[] = [] | |
private _deadVectors: number[] = [] | |
private _liveVectors: Map<IndexedVector3, boolean> = new Map() | |
private _list: IndexedVector3[] = [] | |
private _liveParticles = 0 | |
receive(positionBuffer: Float32Array, liveParticleCount: number) { | |
for (let i = 0; i < liveParticleCount; i++) { | |
const i3 = i * 3 | |
const i4 = i * 4 | |
for (let j = 0; j < 3; j++) { | |
this._currentBuffer[i3 + j] = positionBuffer[i4 + j] | |
} | |
} | |
this._liveParticles = liveParticleCount | |
} | |
sortBuffer(camera: Camera) { | |
this._releaseAll() | |
this._list = [] | |
for (let i = 0; i < this._liveParticles; i++) { | |
const v = this._getVector() | |
v.bufferIndex = i | |
let i3 = i * 3 | |
v.set( | |
this._currentBuffer[i3++], | |
this._currentBuffer[i3++], | |
this._currentBuffer[i3++] | |
) | |
v.applyMatrix4(camera.matrixWorldInverse) | |
this._list.push(v) | |
} | |
this._list.sort((a, b) => a.z - b.z) | |
// console.log(this._list) | |
const indecis: number[] = this._list.map(v => v.bufferIndex) | |
return indecis | |
} | |
private _getVector() { | |
let v | |
if (this._deadVectors.length) { | |
v = this._pool[this._deadVectors.pop()!].set(0, 0, 0) | |
} else { | |
v = new IndexedVector3(this._pool.length) | |
this._pool.push(v) | |
} | |
this._liveVectors.set(v, true) | |
return v | |
} | |
private _releaseVector(v: IndexedVector3) { | |
this._deadVectors.push(v.index) | |
this._liveVectors.delete(v) | |
} | |
private _releaseAll() { | |
this._liveVectors.forEach((_, v) => { | |
this._releaseVector(v) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment