Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <canvas class="webgl"></canvas>
<div class="instructions">- Press to add thickness -</div>
<div id="credits">
  <p><a href="https://codepen.io/Yakudoo/" target="blank">my other codepens</a> | <a href="http://epic.net" target="blank">epic.net</a></p>
</div>

<script type="x-shader/x-vertex" id="floorVertexShader">
  varying vec2 vUv; 

  #include <common>
  #include <shadowmap_pars_vertex>
  #include <logdepthbuf_pars_vertex>

	void main() {
		#include <beginnormal_vertex>
		#include <defaultnormal_vertex>
		#include <begin_vertex>

		vUv = uv;
		gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		#include <logdepthbuf_vertex>
		#include <worldpos_vertex>
		#include <shadowmap_vertex>

	}
</script>
  
<script type="x-shader/x-fragment" id="floorFragmentShader">
  uniform vec3 color;
  uniform sampler2D tScratches;
	varying vec2 vUv;
  
  #include <common>
  #include <packing>
  #include <lights_pars_begin>
  #include <shadowmap_pars_fragment>
  #include <shadowmask_pars_fragment>
	#include <logdepthbuf_pars_fragment>

	void main() {
			#include <logdepthbuf_fragment>
      vec3 col = color;
      vec4 scratchesCol = texture2D( tScratches, vUv);
      float inkValue = max( max(scratchesCol.r, scratchesCol.g), scratchesCol.b);
      col = mix(col, scratchesCol.rgb, inkValue);
      col.r = min(col.r, 1.0);
      col.g = min(col.g, 1.0);
      col.b = min(col.b, 1.0);
      
      col.gb -= (1.0 - getShadowMask() ) * .1;
      gl_FragColor = vec4(col, 1.0);
		 	#include <tonemapping_fragment>
			#include <colorspace_fragment>
		}
</script>  
<script type="x-shader/x-vertex" id="simulationVertexShader">
  precision highp float;

  uniform float time;
  varying vec2 vUv;

  void main() {
    vUv = uv;
    vec4 modelViewPosition = modelViewMatrix * vec4(position, 1.0);
    gl_Position = projectionMatrix * modelViewPosition; 
  }
</script>

<script type="x-shader/x-fragment" id="simulationFragmentShader">
  // fragment shader
  uniform sampler2D inputTexture;
  uniform sampler2D noiseTexture;
  uniform vec2 tipPosOld;
  uniform vec2 tipPosNew;
  uniform float speed;
  uniform float persistence;
  uniform float thickness;
  uniform float time;
  uniform float waterQuantity;
  uniform float waterDiffusion;
  uniform float gravity;
  uniform vec3 inkColor;
  varying vec2 vUv;

  float lineSegment(vec2 p, vec2 a, vec2 b, float thickness) {
    vec2 pa = p - a;
    vec2 ba = b - a;
    float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
    float idk = length(pa - ba*h);
    idk = smoothstep(thickness, thickness * .5, idk);
    return idk;
  }
  
  vec4 blur(sampler2D image, vec2 uv, vec2 resolution, vec2 direction){
    vec4 color = vec4(0.0);
    vec2 off1 = vec2(.013846153846) * direction;
    vec2 off2 = vec2(.032307692308) * direction;
    color += texture2D(image, uv) * 0.2270270270;
    color += texture2D(image, uv + vec2(off1 * resolution)) * 0.3162162162;
    color += texture2D(image, uv - vec2(off1 * resolution)) * 0.3162162162;
    color += texture2D(image, uv + vec2(off2 * resolution)) * 0.0702702703;
    color += texture2D(image, uv - vec2(off2 * resolution)) * 0.0702702703;
    return color;
  }

  void main() {
    
    vec4 noise1 = texture2D(noiseTexture, vUv * 4.0 + vec2(time * .1, .0));
    vec4 noise2 = texture2D(noiseTexture, vUv * 8.0 + vec2(.0, time * .1) + noise1.rg * .5);
    vec4 noise3 = texture2D(noiseTexture, vUv * 16.0 + vec2(-time*.05, 0.) + noise2.rg * .5);
    vec4 noise = (noise1 + noise2 * .5 + noise3 * .25 ) / 1.75;
    float dirX = (-.5 + noise.g) * noise.r * 10.;
    float dirY = (-.5 + noise.b) * noise.r * 10.;
    
    
    vec4 oldTexture = texture2D(inputTexture, vUv);
    float br = 1. - + (oldTexture.r + oldTexture.g + oldTexture.b)/3.0;
    vec4 col = oldTexture * (1.0 - waterDiffusion);
    float p2 = (waterDiffusion)/4.0;
    vec2 stretchUv = vUv * vec2(1.0, 1.0 + gravity);
    col += blur(inputTexture, stretchUv, vec2(waterQuantity * br), vec2(dirX, dirY) ) * p2;
    col += blur(inputTexture, stretchUv, vec2(waterQuantity * br), vec2(dirY, dirX) ) * p2;
    col += blur(inputTexture, stretchUv, vec2(waterQuantity * br), vec2(-dirX, -dirY) ) * p2;
    col += blur(inputTexture, stretchUv, vec2(waterQuantity * br), vec2(-dirY, -dirX) ) * p2;
    col.rgb *= persistence;
    
    if (speed>0.0){
      float lineValue = 0.;
      float th = clamp( thickness + speed * .3, .0001, .1) ;
      lineValue = lineSegment(vUv , tipPosOld, tipPosNew, th);
      col.rgb = mix(col.rgb, inkColor, lineValue);
      col.rgb = clamp( col.rgb, vec3(0.), vec3(1.));
    }
   
    gl_FragColor = vec4(col);
}
</script>
              
            
!

CSS

              
                @import url(https://fonts.googleapis.com/css?family=Open+Sans:600);

body {
	margin: 0px;
}

.webgl {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  outline: none;
  background-color: #000000;
  cursor: move;
  /* fallback if grab cursor is unsupported */
  cursor: grabbing;
  cursor: -moz-grabbing;
  cursor: -webkit-grabbing;
}

#credits {
  position: absolute;
  width: 100%;
  margin: auto;
  bottom: 0;
  margin-bottom: 20px;
  font-family: "Open Sans", sans-serif;
  color: #544027;
  font-size: 0.7em;
  text-transform: uppercase;
  text-align: center;
}
#credits a {
  color: #7beeff;
}

#credits a:hover {
  color: #ff3434;
}
.instructions{
  position:absolute;
  width:100%;
  bottom:60px;
  margin: auto;
  margin-top:120px;
  font-family:'Open Sans', sans-serif;
  color:#7beeff;
  font-size:.9em;
  text-transform: uppercase;
  text-align : center;
  line-height : 1.5;
  user-select: none;
}

              
            
!

JS

              
                import * as THREE from "https://esm.sh/three@0.156.1";
import GUI from "https://esm.sh/lil-gui"; 

document.addEventListener("DOMContentLoaded", () => new App());

class App {
  constructor() {
    this.winWidth = window.innerWidth;
    this.winHeight = window.innerHeight;
    this.loadTextures();
  }
  
  loadTextures(){
    const tl = new THREE.TextureLoader()
    tl.load('https://assets.codepen.io/264161/noise_1.jpg', (texture)=>{
      this.noiseTexture = texture;
      this.noiseTexture.wrapS = THREE.RepeatWrapping;
      this.noiseTexture.wrapT = THREE.RepeatWrapping;
      this.setUpScene();
    });   
  }

  setUpScene() {
    // Scene
    this.scene = new THREE.Scene();
    this.bgrColor = 0x332e2e;
    this.inkColor = 0x7beeff;
    this.fog = new THREE.Fog(this.bgrColor, 13, 20);
    this.scene.fog = this.fog;
    this.camera = new THREE.PerspectiveCamera(
      60,
      this.winWidth / this.winHeight,
      1,
      100
    );
    this.camera.position.set(0, 7, 8);
    this.camera.lookAt(new THREE.Vector3());
    this.scene.add(this.camera);

    // Hero param
    this.targetHeroUVPos = new THREE.Vector2(0.5, 0.5);
    this.targetHeroAbsMousePos = new THREE.Vector2();
    this.targetHeroRotation = new THREE.Vector2();
    this.heroOldUVPos = new THREE.Vector2(0.5, 0.5);
    this.heroNewUVPos = new THREE.Vector2(0.5, 0.5);
    this.raycaster = new THREE.Raycaster();
    this.mouse = new THREE.Vector2();
    this.mouseDown = false;
    this.thickness = .004;
    this.pressure = 0;
    this.persistence = .98;
    this.gravity = 0.5;

    // Clock
    this.clock = new THREE.Clock();
    this.time = 0;
    this.deltaTime = 0;
    
    // Core
    this.createRenderer();
    this.createSim();
    this.createListeners();

    // Environment
    this.floorSize = 30;
    this.createHero();
    this.createFloor();
    this.createLight();
    this.createGUI()

    // Render loop
    this.draw();
  }

  createHero() {
    const geom = new THREE.CylinderGeometry(.05, .2, 1, 16, 1)
    geom.applyMatrix4(new THREE.Matrix4().makeRotationX(Math.PI))
    geom.applyMatrix4(new THREE.Matrix4().makeTranslation(0,.5,0))
    const mat = new THREE.MeshStandardMaterial({ 
      color: this.inkColor,
      roughness: 1,
    });
    this.hero = new THREE.Mesh(geom, mat)
    this.hero.position.y = .2
    this.hero.castShadow = true;
    this.scene.add(this.hero);
  }

  createFloor() {
    
    const fragmentShader = document.getElementById('floorFragmentShader').textContent;
    const vertexShader = document.getElementById('floorVertexShader').textContent;
    
    const uniforms = THREE.UniformsUtils.merge([
		  THREE.UniformsLib['common'],
      THREE.UniformsLib['shadowmap'],
		  THREE.UniformsLib['lights'],
      {
        color:{ value : new THREE.Color( this.bgrColor ) },
        tScratches : { value: this.bufferSim.output.texture },
	    }
	  ])
    const geom = new THREE.PlaneGeometry(this.floorSize, this.floorSize)
    const mat = new THREE.ShaderMaterial({
      uniforms,
      fragmentShader,
      vertexShader,
      lights:true,     
    })
    this.floor = new THREE.Mesh(geom, mat);
    this.floor.rotation.x = -Math.PI / 2;
    this.floor.receiveShadow = true;
    this.scene.add(this.floor);
   }

  createLight() {
    this.ambientLight = new THREE.AmbientLight(0xffffff);
    this.scene.add(this.ambientLight);

    this.light = new THREE.DirectionalLight(0xffffff, 1);
    this.light.position.set(2, 3, 1);
    this.light.castShadow = true;
    this.light.shadow.mapSize.width = 512;
    this.light.shadow.mapSize.height = 512;
    this.light.shadow.camera.near = 0.5;
    this.light.shadow.camera.far = 12;
    this.light.shadow.camera.left = -12;
    this.light.shadow.camera.right = 12;
    this.light.shadow.camera.bottom = -12;
    this.light.shadow.camera.top = 12;
    this.scene.add(this.light);
  }

  createRenderer() {
    const canvas = document.querySelector("canvas.webgl");
    this.renderer = new THREE.WebGLRenderer({
      canvas,
      antialias: true,
      preserveDrawingBuffer: true
    });
    this.renderer.setClearColor(new THREE.Color(this.bgrColor))

    this.renderer.setPixelRatio((this.pixelRatio = window.devicePixelRatio));
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    this.renderer.toneMapping = THREE.LinearToneMapping;
    this.renderer.toneMappingExposure = 1;
    this.renderer.shadowMap.enabled = true;
    this.renderer.shadowMap.type = THREE.VSMShadowMap;
    this.renderer.localClippingEnabled = true;
  }
  
  createSim(){
    const fragmentShader = document.getElementById('simulationFragmentShader').textContent;
    const vertexShader = document.getElementById('simulationVertexShader').textContent;
    
    this.floorSimMat = new THREE.ShaderMaterial({
      uniforms: {
        inputTexture: {type: "t", value: null},
        noiseTexture: {type: "t", value: this.noiseTexture },
        persistence: { value: this.persistence },
        thickness: { value: this.thickness },
        waterDiffusion: { value: .1 },
        waterQuantity: { value: .3 },
        gravity: { value: this.gravity },
        time: { value: 0 },
        tipPosOld: {value: new THREE.Vector2(.5,.5)},
        tipPosNew: {value: new THREE.Vector2(.5,.5)},
        speed: {value: 0.0},
        inkColor:{ value : new THREE.Color( this.inkColor ) },
      },
      vertexShader,
      fragmentShader,
    })
		this.bufferSim = new BufferSim(this.renderer, 1024, 1024, this.floorSimMat)
  }

  createListeners() {
    window.addEventListener("resize", this.onWindowResize.bind(this));
    document.addEventListener("mousemove", this.onMouseMove.bind(this), false);
    document.addEventListener("mousedown", this.onMouseDown.bind(this), false);
    document.addEventListener("mouseup", this.onMouseUp.bind(this), false);
    document.addEventListener("touchmove", this.onTouchMove.bind(this), false);
  }

  draw() {
    this.updateGame();
    this.renderer.render(this.scene, this.camera);
    if (this.controls) this.controls.update();
    window.requestAnimationFrame(this.draw.bind(this));
  }

  updateGame() {
    this.dt = this.clock.getDelta();
    this.time += this.dt;
    
		this.heroNewUVPos.lerp(this.targetHeroUVPos, this.dt * 5);
		this.hero.position.x = ( this.heroNewUVPos.x - 0.5 ) * this.floorSize;
		this.hero.position.z = ( 0.5 - this.heroNewUVPos.y ) * this.floorSize;

		this.heroSpeed = new THREE.Vector2().subVectors(this.heroNewUVPos, this.heroOldUVPos);
		this.targetHeroRotation.lerp(this.heroSpeed.clone().multiplyScalar(90), this.dt * 30);

		this.hero.rotation.z = this.targetHeroRotation.x;
		this.hero.rotation.x = this.targetHeroRotation.y;

		this.floorSimMat.time += this.dt;
		this.floorSimMat.uniforms.tipPosNew.value = this.heroNewUVPos;
		this.floorSimMat.uniforms.tipPosOld.value = this.heroOldUVPos;
		this.floorSimMat.uniforms.speed.value = this.heroSpeed.length();
		const r = Math.abs(Math.sin(this.time * .61 + .0 ));
		const g = Math.abs(Math.sin(this.time * .43 + 2.09 ));
		const b = Math.abs(Math.sin(this.time * .36 + 4.18 ));
		const newCol = new THREE.Color(r,g,b);
		this.floorSimMat.uniforms.inkColor.value = newCol;
		this.floorSimMat.uniforms.time.value = this.time;
		this.floorSimMat.uniforms.persistence.value = Math.pow(this.persistence, this.dt*10);
		this.floorSimMat.uniforms.gravity.value = this.gravity * this.dt;

		if ( this.mouseDown && this.pressure < .02 ) {
			this.pressure += this.dt * .02;
		} else if (!this.mouseDown) {
			this.pressure *= Math.pow(.9, this.dt*30)
		}
		this.floorSimMat.uniforms.thickness.value = this.thickness + this.pressure

		this.hero.scale.y = 1. - this.pressure * 10
		this.hero.scale.x = 1. + this.pressure * 40
		this.hero.scale.z = 1. + this.pressure * 40
		this.bufferSim.render();
		this.renderer.setRenderTarget(null);

		this.floor.material.uniforms.tScratches.value = this.bufferSim.output.texture;
		this.hero.material.color = newCol;
		this.heroOldUVPos = this.heroNewUVPos.clone();
  }

  onWindowResize() {
    this.winWidth = window.innerWidth;
    this.winHeight = window.innerHeight;
    this.camera.aspect = this.winWidth / this.winHeight;
    this.camera.updateProjectionMatrix();
    this.renderer.setSize(this.winWidth, this.winHeight);
  }
  
  onMouseDown(event) { 
    this.mouseDown = true;
  }
  
  onMouseUp(event) { 
    this.mouseDown = false;
  }

  onMouseMove(event) { 
    const x = event.clientX / this.winWidth * 2 - 1;
    const y = -(event.clientY / this.winHeight * 2 - 1);
    this.mouse.x = x;
    this.mouse.y = y;
    if (this.floor) this.raycast(); 
  }
  
  onTouchMove(event) { 
    if (event.touches.length == 1) {
      event.preventDefault();
      const x = event.touches[0].pageX / this.winWidth * 2 - 1;
      const y = -(event.touches[0].pageY / this.winHeight * 2 - 1);
      this.mouse.x = x;
      this.mouse.y = y;
      if (this.floor) this.raycast(); 
    }
  }
  
  raycast() {
    this.raycaster.setFromCamera( this.mouse, this.camera );
    var intersects = this.raycaster.intersectObjects( [this.floor] );

    if (intersects.length>0){
      this.targetHeroUVPos.x = intersects[0].uv.x;
      this.targetHeroUVPos.y = intersects[0].uv.y;
    }
  }
  
  createGUI(){
    
    const fsu = this.floorSimMat.uniforms
    this.gui = new GUI();
    this.gui.add( this, 'persistence', 0.8, .999 ).name('Persistence');
    this.gui.add( this, 'thickness', 0.0003, .02 ).name('Thickness');
    this.gui.add( fsu.waterQuantity, 'value', .0, 1. ).name('water quantity');
    this.gui.add( fsu.waterDiffusion, 'value', .01, 1. ).name('water diffusion');
    this.gui.add( this,'gravity', 0, 1 ).name('gravity');
    //this.gui.close();
  }

}
class BufferSim{
    constructor ( renderer, width, height, shader ) {

        this.renderer = renderer;
        this.shader = shader;
        this.orthoScene = new THREE.Scene();
        var fbo = new THREE.WebGLRenderTarget( width, height, {
            wrapS: THREE.ClampToEdgeWrapping,
            wrapT: THREE.ClampToEdgeWrapping,
            minFilter: THREE.LinearFilter,
            magFilter: THREE.LinearFilter,
            format: THREE.RGBAFormat,
            type: THREE.FloatType,
            stencilBuffer: false,
            depthBuffer: false
        });

        fbo.texture.generateMipmaps = false;
        
        this.fbos = [ fbo, fbo.clone() ];
        this.current = 0;
        this.output = this.fbos[ 0 ];
        this.orthoCamera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, .00001, 1000 );
        this.orthoQuad = new THREE.Mesh( new THREE.PlaneGeometry( width, height ), this.shader );
        this.orthoScene.add( this.orthoQuad );
    }

    render(){
        this.shader.uniforms.inputTexture.value = this.fbos[ this.current ].texture;
        this.input = this.fbos[ this.current ];
        this.current = 1 - this.current;
        this.output = this.fbos[ this.current ];
        this.renderer.setRenderTarget(this.output);
        this.renderer.render( this.orthoScene, this.orthoCamera );
        this.renderer.setRenderTarget(null);
    }
}

              
            
!
999px

Console