webgl+canvas实现三维布料棉被随风摆动褶皱动画效果代码

代码语言:html

所属分类:三维

代码描述:webgl+canvas实现三维布料棉被随风摆动褶皱动画效果代码

代码标签: webgl canvas 三维 布料 棉被 随风 摆动 褶皱 动画

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  



  
  
</head>

<body translate="no">
  
  
      <script >
const dpr = Math.max(1, .5 * window.devicePixelRatio);
const canvas = document.createElement("canvas");

document.body.innerHTML = "";
document.body.appendChild(canvas);
document.body.style = "margin:0;overflow:hidden;";
canvas.style.width = "100%";
canvas.style.height = "auto";
canvas.style.objectFit = "contain";

const vertexSource = `#version 300 es
#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp float;
#else
precision mediump float;
#endif

in vec4 position;

void main(void) {
    gl_Position = position;
}
`;
const fragmentSource = `#version 300 es
/*********
 * made by Matthias Hurrle (@atzedent) 
 */
#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp float;
#else
precision mediump float;
#endif

out vec4 fragColor;

uniform vec2 resolution;
uniform float time;

#define T mod(2.*time, 180.)
#define S smoothstep

float rnd(float a) {
	return fract(sin(a*12.233)*78.599);
}

float rnd(vec2 p) {
	return fract(sin(dot(p,p.yx+vec2(234,543)))*345678.);
}

float curve(float a, float b) {
	a /= b;

	return mix(
		rnd(floor(a)),
		rnd(floor(a)+1.),
		pow(S(.0,1.,fract(a)),10.)
	);
}

mat2 rot(float a) {
	float s=sin(a), c=cos(a);
	return mat2(c,-s,s,c);
}

float map(vec3 p) {
	float d=p.y+(1.-cos(sin(T+6.3*p.x)))*.1;
	d += 1.-pow(cos(.75*sin(T+curve(T*.5,8.)+2.*(1.+curve(T*2.5,14.4))*(p.xz*rot(.125)).x)),2.);
	d += 1.-cos(curve(T*.2,8.)+sin(T+.8*(p.xz*rot(.38)).x))*.1;
	d += 1.2*sin(p.z*.4+sin(p.x*.6+1.2));
	
	d = max(d, -p.z);
	
	return d*.5;
}

vec3 norm(vec3 p) {
	float h=1e-3;
	vec2 k=vec2(-1,1);
	return normalize(
		k.xyy*map(p+k.xyy*h)+
		k.yxy*map(p+k.yxy*h)+
		k.yyx*map(p+k.yyx*h)+
		k.xxx*map(p+k.xxx*h)
	);
}

void cam(inout vec3 p) {
	p.xz*=rot(sin(T*.2)*.2);
}

void main(void) {
	vec2 uv = (
		gl_FragCoord.xy-.5*resolution
	)/min(resolution.x, resolution.y);

	vec3 col = vec3(0),
	p = vec3(0,0,-3),
	rd = normalize(vec3(uv,1));

	cam(p);
	cam(rd);

	const float steps=400., maxd=40.;
	float dd=.0, diffuse=mix(.75,1.,rnd(p.xz));

	for (float i=.0; i<steps; i++) {
		float d=map(p)*diffuse;

		if (d<1e-3) break;
		if (d>maxd) {
			dd=maxd;
			break;
		}

		p += rd*d;
		dd += d;
	}

	vec3 n=norm(p),
	l = normalize(vec3(0,10,-.1));

	float
	dif=max(.0,dot(n,l)),
	fre=1.+max(.0,dot(-rd,n));

	col += vec3(.3,.2,.1);
	col += .2*pow(fre,3..........完整代码请登录后点击上方下载按钮下载查看

网友评论0