# 拾取

THREE.js 提供了 RayCaster 类来做这些事情。

*const fov = 60;
const aspect = 2;  // 画布默认纵横比为2
const near = 0.1;
*const far = 200;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
*camera.position.z = 30;

const scene = new THREE.Scene();
+scene.background = new THREE.Color('white');

+// 把摄像机放到自拍杆上 (把它添加为一个对象的子元素)
+// 如此，我们就能通过旋转自拍杆，来移动摄像机
+const cameraPole = new THREE.Object3D();

render 函数中旋转摄像机端点。

cameraPole.rotation.y = time * .1;

const boxWidth = 1;
const boxHeight = 1;
const boxDepth = 1;
const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);

function rand(min, max) {
if (max === undefined) {
max = min;
min = 0;
}
return min + (max - min) * Math.random();
}

function randomColor() {
return `hsl(\${rand(360) | 0}, \${rand(50, 100) | 0}%, 50%)`;
}

const numObjects = 100;
for (let i = 0; i < numObjects; ++i) {
const material = new THREE.MeshPhongMaterial({
color: randomColor(),
});

const cube = new THREE.Mesh(geometry, material);

cube.position.set(rand(-20, 20), rand(-20, 20), rand(-20, 20));
cube.rotation.set(rand(Math.PI), rand(Math.PI), 0);
cube.scale.set(rand(3, 6), rand(3, 6), rand(3, 6));
}

class PickHelper {
constructor() {
this.raycaster = new THREE.Raycaster();
this.pickedObject = null;
this.pickedObjectSavedColor = 0;
}
pick(normalizedPosition, scene, camera, time) {
// 恢复上一个被拾取对象的颜色
if (this.pickedObject) {
this.pickedObject.material.emissive.setHex(this.pickedObjectSavedColor);
this.pickedObject = undefined;
}

// 发出射线
this.raycaster.setFromCamera(normalizedPosition, camera);
// 获取与射线相交的对象
const intersectedObjects = this.raycaster.intersectObjects(scene.children);
if (intersectedObjects.length) {
// 找到第一个对象，它是离鼠标最近的对象
this.pickedObject = intersectedObjects[0].object;
// 保存它的颜色
this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
// 设置它的发光为 黄色/红色闪烁
this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000);
}
}
}

const pickPosition = {x: 0, y: 0};
clearPickPosition();

...

function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
x: (event.clientX - rect.left) * canvas.width  / rect.width,
y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}

function setPickPosition(event) {
const pos = getCanvasRelativePosition(event);
pickPosition.x = (pos.x / canvas.width ) *  2 - 1;
pickPosition.y = (pos.y / canvas.height) * -2 + 1;  // note we flip Y
}

function clearPickPosition() {
// 对于触屏，不像鼠标总是能有一个位置坐标，
// 如果用户不在触摸屏幕，我们希望停止拾取操作。
// 因此，我们选取一个特别的值，表明什么都没选中
pickPosition.x = -100000;
pickPosition.y = -100000;
}

// 阻止窗口滚动行为
event.preventDefault();
setPickPosition(event.touches[0]);
}, {passive: false});

setPickPosition(event.touches[0]);
});

+const pickHelper = new PickHelper();

function render(time) {
time *= 0.001;  //将毫秒单位转换为秒单位;

...

+  pickHelper.pick(pickPosition, scene, camera, time);

renderer.render(scene, camera);

...

1. 这是基于CPU运算的 Javascript遍历每一个对象，检查其包围盒或包围球是否与射线相交，如果相交，它必须遍历组成该对象的每一个三角，检查它们是否与射线相交。
好处是，JavaScript能够很容易计算出射线在哪里与三角相交，并为我们提供相关数据。举个例子，如果你想要在相交的位置放置一个标记。
缺点是，CPU要做大量的工作,当你的对象由大量的三角组成时，这个过程会有些慢。
2. 它无法处理一些奇怪的着色器或者位移 如果，你有一个变形或者拟态几何形状的着色器，Javascript无法理解这个变形，它会给出错误的答案。举例：据我所知，你不能对有皮肤的对象使用这种方式。
3. 无法处理透明的孔洞 举个例子，为立方体应用这个纹理

const numObjects = 100;
for (let i = 0; i < numObjects; ++i) {
const material = new THREE.MeshPhongMaterial({
color: randomColor(),
+map: texture,
+transparent: true,
+side: THREE.DoubleSide,
+alphaTest: 0.1,
});

const cube = new THREE.Mesh(geometry, material);

...

const scene = new THREE.Scene();
scene.background = new THREE.Color('white');
const pickingScene = new THREE.Scene();
pickingScene.background = new THREE.Color(0);

const idToObject = {};
+const numObjects = 100;
for (let i = 0; i < numObjects; ++i) {
+  const id = i + 1;
const material = new THREE.MeshPhongMaterial({
color: randomColor(),
map: texture,
transparent: true,
side: THREE.DoubleSide,
alphaTest: 0.1,
});

const cube = new THREE.Mesh(geometry, material);
+  idToObject[id] = cube;

cube.position.set(rand(-20, 20), rand(-20, 20), rand(-20, 20));
cube.rotation.set(rand(Math.PI), rand(Math.PI), 0);
cube.scale.set(rand(3, 6), rand(3, 6), rand(3, 6));

+  const pickingMaterial = new THREE.MeshPhongMaterial({
+    emissive: new THREE.Color(id),
+    color: new THREE.Color(0, 0, 0),
+    specular: new THREE.Color(0, 0, 0),
+    map: texture,
+    transparent: true,
+    side: THREE.DoubleSide,
+    alphaTest: 0.5,
+    blending: THREE.NoBlending,
+  });
+  const pickingCube = new THREE.Mesh(geometry, pickingMaterial);
+  pickingCube.position.copy(cube.position);
+  pickingCube.rotation.copy(cube.rotation);
+  pickingCube.scale.copy(cube.scale);
}

function setPickPosition(event) {
const pos = getCanvasRelativePosition(event);
-  pickPosition.x = (pos.x / canvas.clientWidth ) *  2 - 1;
-  pickPosition.y = (pos.y / canvas.clientHeight) * -2 + 1;  // 注意，翻转了y轴
+  pickPosition.x = pos.x;
+  pickPosition.y = pos.y;
}

-class PickHelper {
+class GPUPickHelper {
constructor() {
-    this.raycaster = new THREE.Raycaster();
+    // 创建一个1px的渲染目标
+    this.pickingTexture = new THREE.WebGLRenderTarget(1, 1);
+    this.pixelBuffer = new Uint8Array(4);
this.pickedObject = null;
this.pickedObjectSavedColor = 0;
}
pick(cssPosition, scene, camera, time) {
+    const {pickingTexture, pixelBuffer} = this;

// 如果已经存在拾取的对象，将其颜色恢复
if (this.pickedObject) {
this.pickedObject.material.emissive.setHex(this.pickedObjectSavedColor);
this.pickedObject = undefined;
}

+    // 设置视野偏移来表现鼠标下的1px
+    const pixelRatio = renderer.getPixelRatio();
+    camera.setViewOffset(
+        renderer.getContext().drawingBufferWidth,   // 全宽
+        renderer.getContext().drawingBufferHeight,  // 全高
+        cssPosition.x * pixelRatio | 0,             // rect x
+        cssPosition.y * pixelRatio | 0,             // rect y
+        1,                                          // rect width
+        1,                                          // rect height
+    );
+    // 渲染场景
+    renderer.setRenderTarget(pickingTexture)
+    renderer.render(scene, camera);
+    renderer.setRenderTarget(null);
+
+    // 清理视野偏移，回归正常
+    camera.clearViewOffset();
+    // 读取像素
+        pickingTexture,
+        0,   // x
+        0,   // y
+        1,   // width
+        1,   // height
+        pixelBuffer);
+
+    const id =
+        (pixelBuffer[0] << 16) |
+        (pixelBuffer[1] <<  8) |
+        (pixelBuffer[2]      );

-    // 射线穿越视锥体
-    this.raycaster.setFromCamera(normalizedPosition, camera);
-    // 获取与射线相交的对象
-    const intersectedObjects = this.raycaster.intersectObjects(scene.children);
-    if (intersectedObjects.length) {
-      // 获取第一个对象，他是离鼠标最近的一个
-      this.pickedObject = intersectedObjects[0].object;

+    const intersectedObject = idToObject[id];
+    if (intersectedObject) {
+      //获取第一个对象，他是离鼠标最近的一个
+      this.pickedObject = intersectedObject;
// 保存颜色
this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
// 设置对象在黄/红两色间闪烁
this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000);
}
}
}

-const pickHelper = new PickHelper();
+const pickHelper = new GPUPickHelper();

-  pickHelper.pick(pickPosition, scene, camera, time);
+  pickHelper.pick(pickPosition, pickScene, camera, time);