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

3
由于关于WebGL的信息惊人地缺乏(或者我不知道如何搜索),我有一个问题,如何将鼠标坐标转换为三维坐标,以便看到我点击屏幕的确切位置。
我的情况是我有一个非常简单的天空盒,相机位于[0,0,0],我可以通过点击和拖动来查看它。我想做的是能够在那个天空盒上某个地方点击,并知道我点击了哪里,因为我需要在那个位置上放置注释(一些文字或HTML元素)。而且,那个html元素必须随着我转向另一侧而移动并消失。因此,我需要一种方法来获取鼠标单击事件并找出我点击了立方体的哪一面以及坐标在哪里,以便我可以正确地放置注释。
我正在使用纯WebGL,没有使用THREE.js或类似的东西。由于只有一个立方体,我只能假设找到交点不会很难,也不需要额外的库。

这不是一个WebGL问题,而是一个数学问题。请查看光线与平面相交测试 - LJᛃ
我需要将我的二维鼠标坐标转换为三维坐标,以便我能够完成这个任务。所以你没有读懂我的问题。 - Poyr23
我觉得你可能没有意识到一个二维点在三维空间中代表了一条无限射线,但也许我没有仔细阅读你的问题,祝你好运! - LJᛃ
好的,我们有所进展了,无限光线的坐标是什么 :) - Poyr23
1个回答

6

您说得没错,确实很难找到一个例子。

常见的WebGL着色器使用以下代码在3D中进行投影:

gl_Position = matrix * position;

或者

gl_Position = projection * modelView * position;

或者

gl_Position = projection * view * world * position;

这些基本上是同一件事情。它们使用position并将其乘以矩阵以转换为剪辑空间。要执行相反的操作,需要将剪辑空间中的位置转换回position空间。
inverse (projection * view * world) * clipSpacePosition

所以,取出你的3D库,并计算传递给WebGL的矩阵的逆。例如,这里有一些使用twgl数学库计算矩阵以绘制某些内容的代码。
  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));

然后我们需要一个剪辑空间光线。由于我们从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中的射线到三角形代码来遍历所有三角形,并查看从起点到终点的射线是否与一个或多个三角形相交。

请注意,如果您只想要世界空间中的射线而不是位置空间,则可以使用

  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信息,这里有一些链接

感谢您提供详细的答案。由于我没有太多时间来完成这个项目,所以我决定采用一种不太准确但更加简单易实现的方法。我将立方体分成了许多小三角形,并为它们设置了不同的颜色(但并未绘制)。当鼠标点击发生时,我可以读取像素的颜色并确定点击的位置。由于我只有这一个立方体,所以它表现得还不错,但肯定不是最佳解决方案。如果在截止日期之前还有时间,我可以尝试做出更好的解决方案,我相信它会大幅提升效果。 - Poyr23
那是一个不同的问题。你的问题是“在WebGL中获取鼠标点击的3D坐标”,而不是“我该如何在WebGL中选择物体”。对于后者,这里有一个解决方案 - gman
我从未提出不同的问题,我只是在陈述我决定采用不同的方法,问题仍然是一样的。而且我感谢你的回答。 - Poyr23

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接