着色器材质内置变量
three.js着色器的内置变量,分别是
- gl_PointSize:在点渲染模式中,控制方形点区域渲染像素大小(注意这里是像素大小,而不是three.js单位,因此在移动相机是,所看到该点在屏幕中的大小不变)
- gl_Position:控制顶点选完的位置
- gl_FragColor:片元的RGB颜色值
- gl_FragCoord:片元的坐标,同样是以像素为单位
- gl_PointCoord:在点渲染模式中,对应方形像素坐标
他们或者单个出现在着色器中,或者组团出现在着色器中,是着色器的灵魂。下面来分别说一说他们的意义和用法。
- gl_PointSize
gl_PointSize内置变量是一个float类型,在点渲染模式中,顶点由于是一个点,理论上我们并无法看到,所以他是以一个正对着相机的正方形面表现的。使用内置变量gl_PointSize主要是用来设置顶点渲染出来的正方形面的相素大小(默认值是0)。
void main() { gl_PointSize = 10.0; }
- gl_Position
gl_Position内置变量是一个vec4类型,它表示最终传入片元着色器片元化要使用的顶点位置坐标。vec4(x,y,z,1.0),前三个参数表示顶点的xyz坐标值,第四个参数是浮点数1.0。
void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }
- gl_FragColor
gl_FragColor内置变量是vec4类型,主要用来设置片元像素的颜色,它的前三个参数表示片元像素颜色值RGB,第四个参数
是片元像素透明度A,1.0表示不透明,0.0表示完全透明。
void main() { gl_FragColor = vec4(1.0,0.0,0.0,1.0); }
- gl_FragCoord
gl_FragCoord内置变量是vec2类型,它表示WebGL在canvas画布上渲染的所有片元或者说像素的坐标,坐标原点是canvas画布的左上角,x轴水平向右,y竖直向下,gl_FragCoord坐标的单位是像素,gl_FragCoord的值是vec2(x,y),通过gl_FragCoord.x、gl_FragCoord.y方式可以分别访问片元坐标的纵横坐标。这里借了一张图
下面我们举个例子
fragmentShader: `void main() {if(gl_FragCoord.x < 600.0) {gl_FragColor = vec4(1.0,0.0,0.0,1.0);} else {gl_FragColor = vec4(1.0,1.0,0.0,1.0);}}
`
这里以600像素为分界,x值小于600像素的部分,材质被渲染成红色,大于的部分为黄色。
- gl_PointCoord
gl_PointCoord内置变量也是vec2类型,同样表示像素的坐标,但是与gl_FragCoord不同的是,gl_FragCoord是按照整个canvas算的x值从[0,宽度],y值是从[0,高度]。而gl_PointCoord是在点渲染模式中生效的,而它的范围是对应小正方形面,同样是左上角[0,0]到右下角[1,1]。
- 内置变量练习
五个内置变量我们都大致的说了一遍,下面用一个小案例来试用一下除了gl_FragCoord的其他四个。先上图,
var planeGeom = new THREE.PlaneGeometry(1000, 1000, 100, 100);
uniforms = {time: {value: 0}
}
var planeMate = new THREE.ShaderMaterial({transparent: true,side: THREE.DoubleSide,uniforms: uniforms,vertexShader: `uniform float time;void main() {float y = sin(position.x / 50.0 + time) * 10.0 + sin(position.y / 50.0 + time) * 10.0;vec3 newPosition = vec3(position.x, position.y, y * 2.0 );gl_PointSize = (y + 20.0) / 4.0;gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );}`,fragmentShader: `void main() {float r = distance(gl_PointCoord, vec2(0.5, 0.5));if(r < 0.5) {gl_FragColor = vec4(0.0,1.0,1.0,1.0);}}`
})
var planeMesh = new THREE.Points(planeGeom, planeMate);
planeMesh.rotation.x = - Math.PI / 2;
scene.add(planeMesh);
案例-星云
src/main/main.js
import * as THREE from "three";import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import fragmentShader from "../shader/basic/fragmentShader.glsl";
import vertexShader from "../shader/basic/vertexShader.glsl";
// 目标:打造一个旋转的银河系
// 初始化场景
const scene = new THREE.Scene();// 创建透视相机
const camera = new THREE.PerspectiveCamera(75,window.innerHeight / window.innerHeight,0.1,1000
);
// 设置相机位置
// object3d具有position,属性是1个3维的向量
camera.aspect = window.innerWidth / window.innerHeight;
// 更新摄像机的投影矩阵
camera.updateProjectionMatrix();
camera.position.set(0, 0, 5);
scene.add(camera);// 加入辅助轴,帮助我们查看3维坐标轴
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);// 导入纹理
const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load('textures/particles/10.png');
const texture1 = textureLoader.load('textures/particles/9.png');
const texture2 = textureLoader.load('textures/particles/11.png');let geometry=null;
let points=null;// 设置星系的参数
const params = {count: 1000,size: 0.1,radius: 5,branches: 4,spin: 0.5,color: "#ff6030",outColor: "#1b3984",
};// GalaxyColor
let galaxyColor = new THREE.Color(params.color);
let outGalaxyColor = new THREE.Color(params.outColor);
let material;
const generateGalaxy = () => {// 如果已经存在这些顶点,那么先释放内存,在删除顶点数据if (points !== null) {geometry.dispose();material.dispose();scene.remove(points);}// 生成顶点几何geometry = new THREE.BufferGeometry();// 随机生成位置const positions = new Float32Array(params.count * 3);const colors = new Float32Array(params.count * 3);const scales = new Float32Array(params.count);//图案属性const imgIndex = new Float32Array(params.count)// 循环生成点for (let i = 0; i < params.count; i++) {const current = i * 3;// 计算分支的角度 = (计算当前的点在第几个分支)*(2*Math.PI/多少个分支)const branchAngel =(i % params.branches) * ((2 * Math.PI) / params.branches);const radius = Math.random() * params.radius;// 距离圆心越远,旋转的度数就越大// const spinAngle = radius * params.spin;// 随机设置x/y/z偏移值const randomX =Math.pow(Math.random() * 2 - 1, 3) * 0.5 * (params.radius - radius) * 0.3;const randomY =Math.pow(Math.random() * 2 - 1, 3) * 0.5 * (params.radius - radius) * 0.3;const randomZ =Math.pow(Math.random() * 2 - 1, 3) * 0.5 * (params.radius - radius) * 0.3;// 设置当前点x值坐标positions[current] = Math.cos(branchAngel) * radius + randomX;// 设置当前点y值坐标positions[current + 1] = randomY;// 设置当前点z值坐标positions[current + 2] = Math.sin(branchAngel) * radius + randomZ;const mixColor = galaxyColor.clone();mixColor.lerp(outGalaxyColor, radius / params.radius);// 设置颜色colors[current] = mixColor.r;colors[current + 1] = mixColor.g;colors[current + 2] = mixColor.b;// 顶点的大小scales[current] = Math.random();// 根据索引值设置不同的图案;imgIndex[current] = i%3 ;}geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));geometry.setAttribute("aScale", new THREE.BufferAttribute(scales, 1));geometry.setAttribute("imgIndex", new THREE.BufferAttribute(imgIndex, 1));// 设置点的着色器材质material = new THREE.ShaderMaterial({vertexShader: vertexShader,fragmentShader: fragmentShader,transparent: true,vertexColors: true,blending: THREE.AdditiveBlending,depthWrite: false,uniforms: {uTime: {value: 0,},uTexture:{value:texture},uTexture1:{value:texture1},uTexture2:{value:texture2},uTime:{value:0},uColor:{value:galaxyColor}},});// 生成点points = new THREE.Points(geometry, material);scene.add(points);console.log(points);// console.log(123);
};generateGalaxy()// 初始化渲染器
const renderer = new THREE.WebGLRenderer();
renderer.shadowMap.enabled = true;// 设置渲染尺寸大小
renderer.setSize(window.innerWidth, window.innerHeight);// 监听屏幕大小改变的变化,设置渲染的尺寸
window.addEventListener("resize", () => {// console.log("resize");// 更新摄像头camera.aspect = window.innerWidth / window.innerHeight;// 更新摄像机的投影矩阵camera.updateProjectionMatrix();// 更新渲染器renderer.setSize(window.innerWidth, window.innerHeight);// 设置渲染器的像素比例renderer.setPixelRatio(window.devicePixelRatio);
});// 将渲染器添加到body
document.body.appendChild(renderer.domElement);// 初始化控制器
const controls = new OrbitControls(camera, renderer.domElement);
// 设置控制器阻尼
controls.enableDamping = true;
// // 设置自动旋转
// controls.autoRotate = true;const clock = new THREE.Clock();function animate(t) {// controls.update();const elapsedTime = clock.getElapsedTime();material.uniforms.uTime.value = elapsedTime;requestAnimationFrame(animate);// 使用渲染器渲染相机看这个场景的内容渲染出来renderer.render(scene, camera);
}animate();
src/shader/basic/fragmentShader.glsl
varying vec2 vUv;uniform sampler2D uTexture;
uniform sampler2D uTexture1;
uniform sampler2D uTexture2;
varying float vImgIndex;
varying vec3 vColor;
void main(){// gl_FragColor = vec4(gl_PointCoord,0.0,1.0);// 设置渐变圆// float strength = distance(gl_PointCoord,vec2(0.5)); // 点到中心距离// strength*=2.0;// strength = 1.0-strength;// gl_FragColor = vec4(strength);// 圆形点// float strength = 1.0-distance(gl_PointCoord,vec2(0.5));// strength = step(0.5,strength);// gl_FragColor = vec4(strength);// 根据纹理设置图案// vec4 textureColor = texture2D(uTexture,gl_PointCoord);// gl_FragColor = vec4(textureColor.rgb,textureColor.r) ;vec4 textureColor;if(vImgIndex==0.0){textureColor = texture2D(uTexture,gl_PointCoord);}else if(vImgIndex==1.0){textureColor = texture2D(uTexture1,gl_PointCoord);}else{textureColor = texture2D(uTexture2,gl_PointCoord);}gl_FragColor = vec4(vColor,textureColor.r) ;}
src/shader/basic/vertexShader.glsl
varying vec2 vUv;attribute float imgIndex;
attribute float aScale;
varying float vImgIndex;uniform float uTime;varying vec3 vColor;
void main(){vec4 modelPosition = modelMatrix * vec4( position, 1.0 );// 获取定点的角度float angle = atan(modelPosition.x,modelPosition.z);// 获取顶点到中心的距离float distanceToCenter = length(modelPosition.xz);// 根据顶点到中心的距离,设置旋转偏移度数float angleOffset = 1.0/distanceToCenter*uTime;// 目前旋转的度数angle+=angleOffset;modelPosition.x = cos(angle)*distanceToCenter;modelPosition.z = sin(angle)*distanceToCenter;vec4 viewPosition = viewMatrix*modelPosition;gl_Position = projectionMatrix * viewPosition;// 设置点的大小// gl_PointSize = 100.0; // 点的大小// 根据viewPosition的z坐标决定是否原理摄像机gl_PointSize =200.0/-viewPosition.z*aScale; // 点的大小vUv = uv;vImgIndex=imgIndex;vColor = color;
}