2024-06-26 08-57-16火焰
shader
来源
//shadertory:https://www.shadertoy.com/view/ctVGD1
//shadertory:https://www.shadertoy.com/view/ml3GWs
代码
import { DoubleSide, ShaderChunk, ShaderMaterial } from "three";
export default function getFireMaterial() {
//https://www.shadertoy.com/view/ctVGD1
/**
一个从玻璃花纹修改来的火焰特效
shadertory:https://www.shadertoy.com/view/ctVGD1
shadertory:https://www.shadertoy.com/view/ml3GWs
*/
const vertex = `
${ShaderChunk.logdepthbuf_pars_vertex}
bool isPerspectiveMatrix(mat4) {
return true;
}
varying vec4 m_pos;
varying vec2 vUv;
varying vec3 _flame;
uniform float uTime;
vec2 hash( vec2 p ){
p = vec2( dot(p,vec2(127.1,311.7)), dot(p,vec2(269.5,183.3)) );
return -1.0 + 2.0*fract(sin(p)*43758.5453123);
}
float noise1( in vec2 p ){
// noise function from IQ himself
const float K1 = 0.366025404; // (sqrt(3)-1)/2;
const float K2 = 0.211324865; // (3-sqrt(3))/6;
vec2 i = floor( p + (p.x+p.y)*K1 );
vec2 a = p - i + (i.x+i.y)*K2;
float m = step(a.y,a.x);
vec2 o = vec2(m,1.0-m);
vec2 b = a - o + K2;
vec2 c = a - 1.0 + 2.0*K2;
vec3 h = max( 0.5-vec3(dot(a,a), dot(b,b), dot(c,c) ), 0.0 );
vec3 n = h*h*h*h*vec3( dot(a,hash(i+0.0)), dot(b,hash(i+o)), dot(c,hash(i+1.0)));
return dot( n, vec3(70.0) );
}
float noise2(in vec2 p){
return
0.500*noise1(p*1.0)
+0.250*noise1(p*2.0)
+0.125*noise1(p*4.0)
+0.063*noise1(p*8.0)
;
}
vec2 noise3(in vec2 p){
return vec2(noise2(p), noise2(p + 20.0));
}
vec2 noise4(in vec2 p){
return noise3(p + noise3(p));
}
vec2 transform(in vec2 p){
return p + 0.2 * noise4(1.4 * p - vec2(0.0, uTime * 0.8));
}
vec3 ud(vec2 p) {
p.x = abs(p.x);
float q = p.x * (p.y * 11.0 + 1.7);
p.x = max(p.x, q);
return vec3(1.0, 0.1, 0.0) / pow(length(p), 5.0) * 0.000008;
}
void main () {
vUv = uv;
vec2 st = uv-.5;
_flame = ud(transform(st * vec2(1.0, 0.5)));
vec3 newPosition = normal*vec3(0,0,0)+position;
gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0);
${ShaderChunk.logdepthbuf_vertex}
}
`;
// 片元着色器代码
const fragment = `
${ShaderChunk.logdepthbuf_pars_fragment}
precision mediump float;
varying vec2 vUv;
varying vec3 _flame;
void main() {
vec2 uv = vUv;
vec3 color = vec3(0.,0.,1.);
gl_FragColor = vec4(_flame,length(_flame));
${ShaderChunk.logdepthbuf_fragment}
}
`;
const uniforms = {
uTime: { value: 1.0 },
};
const material = new ShaderMaterial({
uniforms: {
uTime: { value: 1.0 },
},
vertexShader: vertex,
fragmentShader: fragment,
side: DoubleSide,
transparent: true,
depthWrite:true,
depthTest:true,
alphaTest: 0.5
});
return material;
}
Mesh
let geometry = new PlaneGeometry(1, 1, 50, 50);
let material = getFireMaterial();
this.geometry = geometry;
this.material = material;
let mesh = new Mesh(geometry, material);
this.mesh = mesh;
let mesh2 = mesh.clone();
mesh2.rotation.y = Math.PI / 2;
this.add(mesh, mesh2);
动画
let loop = () => {
requestAnimationFrame(loop);
if ( this.material) {
this.material.uniforms.uTime.value += 0.01;
}
};
loop();