threejs/shader/将mesh的世界空间变换传入shader以得到正确光照

今天刚开始写shader material,要实现的是在一个已经有波形变化的平面上做基本Phong光照。本来PlaneGeometry是在XOY平面中的,转了九十度到XOZ平面上,结果发现出来的渲染效果不太对:
这里写图片描述

后来想了想,是因为我在创建mesh之后又旋转了mesh:

    sea.rotation.x = -Math.PI/2;

但是这并不会改变mesh.vertices中存储的position值,因为它们是model space的,而变换是在world space中进行的。

要改正很简单,mesh.matrixWorld保存了世界空间变换的矩阵,将其作为uniform传入vertex shader,乘modelMatrix即可。
代码:

varying vec2 vUv;
varying vec3 worldPos;
varying vec3 vNormal;
uniform mat4 transform;
void main() { 
    vUv = uv; 
    vNormal = normal;
    gl_Position = projectionMatrix * modelViewMatrix  * vec4( position, 1.0 ); 
    // 配合片段着色器的光照计算,在世界空间中进行
    worldPos = transform * modelMatrix * vec4(position.xyz, 1.0);

}

修正后:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Three.js is a JavaScript library used for creating 3D graphics in the browser. It provides a set of built-in shaders that can be used to create various visual effects like reflections, refractions, shadows, and more. Three.js shaders are written in GLSL (OpenGL Shading Language), a C-like language used for programming graphics processing units (GPUs). To create a custom shader in Three.js, you need to define a new shader material and pass in the GLSL code as a string. Here is an example of a simple custom shader that applies a color gradient based on the object's Y position: ``` var customShader = new THREE.ShaderMaterial({ uniforms: { color1: { value: new THREE.Color(0xff0000) }, color2: { value: new THREE.Color(0x0000ff) } }, vertexShader: ` varying vec3 vPosition; void main() { vPosition = position; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } `, fragmentShader: ` uniform vec3 color1; uniform vec3 color2; varying vec3 vPosition; void main() { float t = (vPosition.y + 1.0) / 2.0; gl_FragColor = vec4(mix(color1, color2, t), 1.0); } ` }); var cube = new THREE.Mesh( new THREE.BoxGeometry(1, 1, 1), customShader ); scene.add(cube); ``` This shader defines two uniforms (color1 and color2) that represent the two colors of the gradient. In the vertex shader, we pass the vertex position to the fragment shader via a varying variable. In the fragment shader, we calculate the gradient value (t) based on the Y position of the vertex and use the mix() function to interpolate between the two colors. Finally, we set the output color using gl_FragColor.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值