在 WebGL 中获取鼠标单击的 3D 坐标

Get 3D coordinates of a mouse click in WebGL

由于令人惊讶的是几乎没有关于 webGL 的信息(或者我只是不知道如何搜索它),所以我有一个关于如何将鼠标坐标转换为 3D 坐标的问题,所以要查看确切的位置我正在点击的屏幕。

所以我的情况是我有一个非常简单的天空盒,相机位于 [0, 0, 0],我可以通过单击和拖动来环顾四周。我想要做的是能够单击该天空盒上的某个位置并知道我单击的位置,因为我需要在该位置放置注释(一些文本或 html 元素)。那个 html 元素必须随着我转向另一边而移动并离开视野。所以我需要的是一种让鼠标点击并找出我正在点击立方体的哪一侧以及在什么坐标处点击的方法,这样我就可以正确放置注释。

我使用的是普通 WebGL,我不使用 THREE.js 或类似的东西。由于它只有一个立方体,我只能假设找到交点不会那么难,也不需要额外的库。

嗯,你说得对,很难找到一个例子

一个常见的 3D webgl 着色器项目,使用类似

的代码
gl_Position = matrix * position;

gl_Position = projection * modelView * position;

gl_Position = projection * view * world * position;

基本上都是一样的。他们取 position 并将其乘以矩阵以转换为剪辑 space。您需要做相反的事情才能走另一条路,在剪辑 space 中占据一席之地并隐蔽回到 position space 即

inverse (projection * view * world) * clipSpacePosition

因此,获取您的 3D 库并计算您传递给 WebGL 的矩阵的逆矩阵。例如,这里有一些代码正在计算矩阵以使用 twgl's 数学库

绘制一些东西
  const fov = 30 * Math.PI / 180;
  const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
  const zNear = 0.5;
  const zFar = 10;
  const projection = m4.perspective(fov, aspect, zNear, zFar);

  const eye = [1, 4, -6];
  const target = [0, 0, 0];
  const up = [0, 1, 0];
  const camera = m4.lookAt(eye, target, up);

  const view = m4.inverse(camera);
  const viewProjection = m4.multiply(projection, view);
  const world = m4.rotationY(time);

对于有效执行此操作的着色器

  gl_Position = viewProjection * world * position

所以我们需要逆

  const invMat = m4.inverse(m4.multiply(viewProjection, world));

然后我们需要剪辑space射线。我们要从 2D 转到 3D,所以我们将使用 -1 和 +1 作为我们的 Z 值

,制作一条从 zNear 开始到 zFar 结束的截锥体的射线
  canvas.addEventListener('mousemove', (e) => {
     const rect = canvas.getBoundingClientRect();
     const x = e.clientX - rect.left;
     const y = e.clientY - rect.top;

     const clipX = x / rect.width  *  2 - 1;
     const clipY = y / rect.height * -2 + 1;

     const start = m4.transformPoint(invMat, [clipX, clipY, -1]);
     const end   = m4.transformPoint(invMat, [clipX, clipY,  1]);

     ... do something with start/end
  });

startend 现在是相对于 position (几何中的数据)所以你现在必须在 JavaScript 中使用一些光线到三角形的代码来遍历你所有的三角形,看看从头到尾的光线是否与你的一个或多个三角形相交。

请注意,如果您想要的只是世界 space 中的一条射线,而不是位置 space,那么您将使用

  const invMat = m4.inverse(viewProjection);

"use strict";

const vs = `
uniform mat4 u_world;
uniform mat4 u_viewProjection;

attribute vec4 position;
attribute vec2 texcoord;
attribute vec4 color;

varying vec4 v_position;
varying vec2 v_texcoord;
varying vec4 v_color;

void main() {
  v_texcoord = texcoord;
  v_color = color;
  gl_Position = u_viewProjection * u_world * position;
}
`;

const fs = `
precision mediump float;

varying vec2 v_texcoord;
varying vec4 v_color;

uniform sampler2D tex;

void main() {
  gl_FragColor = texture2D(tex, v_texcoord) * v_color;
}
`;

const m4 = twgl.m4;
const gl = document.querySelector("#c").getContext("webgl");

// compiles shaders, links, looks up locations
const programInfo = twgl.createProgramInfo(gl, [vs, fs]);

const cubeArrays = twgl.primitives.createCubeVertices(1);
cubeArrays.color = {value: [0.2, 0.3, 1, 1]};
// calls gl.createBuffer, gl.bindBuffer, gl.bufferData
// for each array
const cubeBufferInfo = twgl.createBufferInfoFromArrays(gl, cubeArrays);

const numLines = 50;
const positions = new Float32Array(numLines * 3 * 2);
const colors = new Float32Array(numLines * 4 * 2);
// calls gl.createBuffer, gl.bindBuffer, gl.bufferData
// for each array
const linesBufferInfo = twgl.createBufferInfoFromArrays(gl, {
  position: positions,
  color: colors,
  texcoord: { value: [0, 0], },
});

const tex = twgl.createTexture(gl, {
  minMag: gl.NEAREST,
  format: gl.LUMINANCE,
  src: [
    255, 192,
    192, 255,
  ],
});

let clipX = 0;
let clipY = 0;
let lineNdx = 0;

function render(time) {
  time *= 0.001;
  twgl.resizeCanvasToDisplaySize(gl.canvas);
  gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

  gl.enable(gl.DEPTH_TEST);
  gl.enable(gl.CULL_FACE);
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

  const fov = 30 * Math.PI / 180;
  const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
  const zNear = 1;
  const zFar = 10;
  const projection = m4.perspective(fov, aspect, zNear, zFar);

  const eye = [Math.cos(time), Math.sin(time), 6];
  const target = [0, 0, 0];
  const up = [0, 1, 0];
  const camera = m4.lookAt(eye, target, up);
  
  const view = m4.inverse(camera);
  const viewProjection = m4.multiply(projection, view);
  const world = m4.rotateX(m4.rotationY(1), 1);

  gl.useProgram(programInfo.program);
  // calls gl.bindBuffer, gl.enableVertexAttribArray, gl.vertexAttribPointer
  twgl.setBuffersAndAttributes(gl, programInfo, cubeBufferInfo);
  twgl.setUniformsAndBindTextures(programInfo, {
    tex,
    u_world: world,
    u_viewProjection: viewProjection,
    color: [0.2, 0.3, 1, 1],
  });
  // calls gl.drawArrays or gl.drawElements
  twgl.drawBufferInfo(gl, cubeBufferInfo);

  // add a line in world space
  const invMat = m4.inverse(viewProjection);
  const start = m4.transformPoint(invMat, [clipX, clipY, -1]);
  const end   = m4.transformPoint(invMat, [clipX, clipY,  1]);
  const poffset = lineNdx * 3 * 2;
  const coffset = lineNdx * 4 * 2;
  const color = [Math.random(), Math.random(), Math.random(), 1];
  positions.set(start, poffset);
  positions.set(end, poffset + 3);
  colors.set(color, coffset);
  colors.set(color, coffset + 4);

  gl.bindBuffer(gl.ARRAY_BUFFER, linesBufferInfo.attribs.position.buffer);
  gl.bufferSubData(gl.ARRAY_BUFFER, 0, positions);
  gl.bindBuffer(gl.ARRAY_BUFFER, linesBufferInfo.attribs.color.buffer);
  gl.bufferSubData(gl.ARRAY_BUFFER, 0, colors);

  lineNdx = (lineNdx + 1) % numLines;  

  // calls gl.bindBuffer, gl.enableVertexAttribArray, gl.vertexAttribPointer
  twgl.setBuffersAndAttributes(gl, programInfo, linesBufferInfo);
  twgl.setUniformsAndBindTextures(programInfo, {
    tex,
    u_world: m4.identity(),
    u_viewProjection: viewProjection,
    color: [1, 0, 0, 1],
  });
  // calls gl.drawArrays or gl.drawElements
  twgl.drawBufferInfo(gl, linesBufferInfo, gl.LINES);

  requestAnimationFrame(render);
}
requestAnimationFrame(render);


gl.canvas.addEventListener('mousemove', (e) => {
   const canvas = gl.canvas;
   const rect = canvas.getBoundingClientRect();
   const x = e.clientX - rect.left;
   const y = e.clientY - rect.top;

   clipX = x / rect.width  *  2 - 1;
   clipY = y / rect.height * -2 + 1;
});
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
<canvas id="c"></canvas>
<script src="https://twgljs.org/dist/4.x/twgl-full.min.js"></script>

至于 WebGL 信息,有一些 here