|
| 1 | +import { AppBase, Entity, Picker as PickerPC, Vec3, Vec4 } from 'playcanvas'; |
| 2 | + |
| 3 | +const float32 = new Float32Array(1); |
| 4 | +const uint8 = new Uint8Array(float32.buffer); |
| 5 | +const two = new Vec4(2, 2, 2, 1); |
| 6 | +const one = new Vec4(1, 1, 1, 0); |
| 7 | + |
| 8 | +class Picker { |
| 9 | + app: AppBase; |
| 10 | + |
| 11 | + camera: Entity; |
| 12 | + |
| 13 | + picker: PickerPC | null; |
| 14 | + |
| 15 | + constructor(app: AppBase, camera: Entity) { |
| 16 | + this.app = app; |
| 17 | + this.camera = camera; |
| 18 | + this.picker = null; |
| 19 | + } |
| 20 | + |
| 21 | + async pick(x: number, y: number) { |
| 22 | + const { app, camera } = this; |
| 23 | + const { graphicsDevice } = app; |
| 24 | + const { canvas } = graphicsDevice; |
| 25 | + const width = canvas.clientWidth; |
| 26 | + const height = canvas.clientHeight; |
| 27 | + |
| 28 | + y = height - y - 1; |
| 29 | + |
| 30 | + // construct picker on demand |
| 31 | + if (!this.picker) { |
| 32 | + this.picker = new PickerPC(this.app, width, height); |
| 33 | + } |
| 34 | + |
| 35 | + // render scene, read depth |
| 36 | + const { picker } = this; |
| 37 | + picker.resize(width, height); |
| 38 | + picker.prepare(camera.camera, app.scene, [app.scene.layers.getLayerByName('World')]); |
| 39 | + const pixels = await picker.renderTarget.colorBuffer.read(x, y, 1, 1, { |
| 40 | + renderTarget: picker.renderTarget |
| 41 | + }); |
| 42 | + |
| 43 | + for (let i = 0; i < 4; ++i) { |
| 44 | + uint8[i] = pixels[i]; |
| 45 | + } |
| 46 | + const depth = float32[0]; |
| 47 | + |
| 48 | + // 255, 255, 255, 255 === NaN |
| 49 | + if (!isFinite(depth)) { |
| 50 | + return null; |
| 51 | + } |
| 52 | + |
| 53 | + // clip space |
| 54 | + const pos = new Vec4(x / width, y / height, depth, 1).mul(two).sub(one); |
| 55 | + |
| 56 | + // homogeneous view space |
| 57 | + camera.camera.projectionMatrix.clone().invert().transformVec4(pos, pos); |
| 58 | + |
| 59 | + // perform perspective divide |
| 60 | + pos.mulScalar(1.0 / pos.w); |
| 61 | + |
| 62 | + // view to world space |
| 63 | + const pos3 = new Vec3(pos.x, pos.y, pos.z); |
| 64 | + camera.getWorldTransform().transformPoint(pos3, pos3); |
| 65 | + |
| 66 | + return pos3; |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +export { Picker }; |
0 commit comments