在WebGL中,可以使用矩阵在屏幕空间中绘制对象偏移吗?

如何解决在WebGL中,可以使用矩阵在屏幕空间中绘制对象偏移吗?

我有一个简单的对象,它在0、0、0处绘制3d小控件。如果相机位于0、0、0的中心,则它将小控件绘制在屏幕中心。

enter image description here

我想“提起”这个Gizmo,并在屏幕坐标的屏幕右下角渲染它,而不旋转它。基本上,我希望Gizmo显示屏幕中心的旋转而不会阻塞视图,而不必专注于特定点。所以我想消除模型矩阵之类的东西。

通过转换投影矩阵,我可以进行以下工作:

enter image description here

this.gl.uniformMatrix4fv(this.modelMatrixUniform,false,modelMatrix);
this.gl.uniformMatrix4fv(this.viewMatrixUniform,viewMatrix);

const bottomRightMat = mat4.create();
mat4.translate(bottomRightMat,projectionMatrix,[5,-3,0]);
this.gl.uniformMatrix4fv(this.projectionMatrixUniform,bottomRightMat);
this.gl.drawElements(this.gl.LINES,this.indexBuffer.getLength(),this.gl.UNSIGNED_SHORT,0);

但是小控件已被旋转到新位置。红线仍应指向下方和左侧,因为那是屏幕中心的X轴正方向。另外,数字5和3是任意的,我认为它们不能在不同的变焦或相机位置使用。

有没有一种方法可以指定一个以屏幕中心为中心并在屏幕空间中进行转换的矩阵变换?

解决方法

一种方法是在渲染对象时更改视口。

// size of area in bottom right
const miniWidth = 150;
const miniHeight = 100;
gl.viewport(gl.canvas.width - miniWidth,gl.canvas.height - miniHeight,miniWidth,miniHeight);

// now draw. you'll need to zoom in,like set the camera closer
// or move the object closer or add a scale matrix after the projection
// matrix as in projection * scale * view * ...

您将需要一个与新视口的宽高比匹配的投影矩阵,并且您需要缩放对象,将相机靠近或在投影和视图矩阵之间添加2D比例。 请记住,将视口放回完整的画布以渲染场景的其余部分。

const vs = `
attribute vec4 position;
uniform mat4 u_worldViewProjection;
void main() {
  gl_Position = u_worldViewProjection * position;
}
`;

const fs = `
precision mediump float;
void main() {
  gl_FragColor = vec4(vec3(0),1);
}
`

const gl = document.querySelector("canvas").getContext("webgl");
const programInfo = twgl.createProgramInfo(gl,[vs,fs]);

const bufferInfo = twgl.createBufferInfoFromArrays(gl,{
  position: [
    -1,-1,1,],indices: {
    numComponents: 2,data: [
      0,2,3,4,5,6,7,},});

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

  const fov = 90 * Math.PI / 180;
  const zNear = 0.5;
  const zFar = 100;
  const projection = mat4.perspective(mat4.create(),fov,gl.canvas.clientWidth / gl.canvas.clientHeight,zNear,zFar);
  const eye = [0,10];
  const target = [0,0];
  const up = [0,0];
  const view = mat4.lookAt(mat4.create(),eye,target,up);

  drawCube([-8,0],projection,view);
  drawCube([-4,view);
  drawCube([ 0,view);
  drawCube([ 4,view);
  drawCube([ 8,view);

  const iconAreaWidth  = 100;
  const iconAreaHeight = 75;
  gl.viewport(
      gl.canvas.width - iconAreaWidth,iconAreaWidth,iconAreaHeight);     
  const iconProjection = mat4.perspective(mat4.create(),iconAreaWidth / iconAreaHeight,zFar);
  // compute the zoom size need to make things the sngs
  const scale = gl.canvas.clientHeight / iconAreaHeight;
  mat4.scale(iconProjection,iconProjection,[scale,scale,1]);
  drawCube([ 0,view);

  function drawCube(translation,view) {
    const viewProjection = mat4.multiply(mat4.create(),view);
    const world = mat4.multiply(
       mat4.create(),mat4.fromTranslation(mat4.create(),translation),mat4.fromRotation(mat4.create(),time,[0.42,0.56,0.70]));
    const worldViewProjection = mat4.multiply(mat4.create(),viewProjection,world);

    gl.useProgram(programInfo.program);
    twgl.setBuffersAndAttributes(gl,programInfo,bufferInfo);
    twgl.setUniforms(programInfo,{
      u_worldViewProjection: worldViewProjection,});
    twgl.drawBufferInfo(gl,bufferInfo,gl.LINES);
  }
  
  requestAnimationFrame(render);
}
requestAnimationFrame(render);
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; background: #CDE; }
<canvas></canvas>
<script src="https://twgljs.org/dist/4.x/twgl-full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix.js"></script>

另一种方法是计算偏心的视锥投影矩阵。代替mat4.perspective使用mat4.frustum

function perspectiveWithCenter(
    fieldOfView,width,height,near,far,centerX = 0,centerY = 0) {
  const aspect = width / height;

  // compute the top and bottom of the near plane of the view frustum
  const top = Math.tan(fieldOfView * 0.5) * near;
  const bottom = -top;

  // compute the left and right of the near plane of the view frustum
  const left = aspect * bottom;
  const right = aspect * top;

  // compute width and height of the near plane of the view frustum
  const nearWidth = right - left;
  const nearHeight = top - bottom;

  // convert the offset from canvas units to near plane units
  const offX = centerX * nearWidth / width;
  const offY = centerY * nearHeight / height;

  const m = mat4.create();
  mat4.frustum(
        m,left + offX,right + offX,bottom + offY,top + offY,far);
  return m;
}

因此要绘制小控件集,请调用类似

  const gizmoCenterX = -gl.canvas.clientWidth  / 2 + 50;
  const gizmoCenterY =  gl.canvas.clientHeight / 2 - 50;
  const offsetProjection = perspectiveWithCenter(
      fov,gl.canvas.clientWidth,gl.canvas.clientHeight,zFar,gizmoCenterX,gizmoCenterY);

const vs = `
attribute vec4 position;
uniform mat4 u_worldViewProjection;
void main() {
  gl_Position = u_worldViewProjection * position;
}
`;

const fs = `
precision mediump float;
void main() {
  gl_FragColor = vec4(vec3(0),});

function perspectiveWithCenter(
    fieldOfView,far);
  return m;
}

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

  const fov = 90 * Math.PI / 180;
  const zNear = 0.5;
  const zFar = 100;
  const projection = perspectiveWithCenter(
      fov,view);

  const gizmoCenterX = -gl.canvas.clientWidth  / 2 + 50;
  const gizmoCenterY =  gl.canvas.clientHeight / 2 - 50;
  const offsetProjection = perspectiveWithCenter(
      fov,gizmoCenterY);
  drawCube([ 0,offsetProjection,gl.LINES);
  }
  
  requestAnimationFrame(render);
}
requestAnimationFrame(render);
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; background: #CDE; }
<canvas></canvas>
<script src="https://twgljs.org/dist/4.x/twgl-full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix.js"></script>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-