我正在尝试从framebuffer / WebGLRenderTarget读取深度值到数组中。我可以找到将深度渲染为深度纹理的信息,但是无法读取缓冲区的深度。使用readpixels我只能得到rbga值。理想情况下,我正在尝试从深度和射线获得世界地位。
我尝试读取像素,但是不知道如何在threejs中读取深度。
答案 0 :(得分:0)
无法直接读取深度值。
您可以将DepthTexture
的{{1}}属性设置为WebGLRenderTarget
。然后,您可以将该深度纹理的全部或部分渲染到另一个渲染目标并读取结果。
depthTexture
'use strict';
/* global THREE */
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const fov = 75;
const aspect = 2; // the canvas default
const near = 0.01;
const far = 5;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 0.7;
const scene = new THREE.Scene();
const geometry = new THREE.BoxBufferGeometry();
const material = new THREE.MeshBasicMaterial({color: 'red'});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
cube.position.x = 0.25;
cube.rotation.y = Math.PI * 0.25;
const depthTexture = new THREE.DepthTexture(canvas.width, canvas.height);
const rt = new THREE.WebGLRenderTarget(canvas.width, canvas.height, {
depthTexture,
});
renderer.setRenderTarget(rt);
renderer.render(scene, camera);
const planeScene = new THREE.Scene();
const planeGeo = new THREE.PlaneBufferGeometry(2, 2);
const planeMat = new THREE.MeshBasicMaterial({map: depthTexture});
const plane = new THREE.Mesh(planeGeo, planeMat);
planeScene.add(plane);
const ortho = new THREE.OrthographicCamera(-1, 1, 1, -1, -1, 1)
const planeRT = new THREE.WebGLRenderTarget(canvas.width, canvas.height, {type: THREE.FloatType});
renderer.setRenderTarget(planeRT);
renderer.render(planeScene, ortho);
const depths = new Float32Array(canvas.width * canvas.height * 4);
renderer.readRenderTargetPixels(planeRT, 0, 0, canvas.width, canvas.height, depths);
console.log(depths);