(Attempt 2) ThreeJS Fragment shader fade in and out at a specified z position

An attempt 2 at getting ThreeJS Fragment shader to fade in and out at a specified z position...

by AllForTheCode

HTML

<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
    
<script type="importmap">
	{
		"imports": {
			"three": "https://unpkg.com/three/build/three.module.js"
		}
	}
</script>
<div id="debug">
  <div id="debug1">x</div>
</div>

SCSS

html,
body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

#debug {
  position: absolute;
  left: 5px;
  top: 5px;
  z-index: 50;

  div {
    display: table;
    background: none;
    color: RGBA(255, 255, 255, 0.9);
  }
}

JavaScript

import * as THREE from 'three';

const db1 = document.getElementById("debug1");

const camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 50);
camera.position.set(-2, 2, 2);
/* camera.position.z = 1; */

const scene = new THREE.Scene();

const geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
const material = new THREE.MeshBasicMaterial({
  transparent: true
});
material.onBeforeCompile = function(m) {
  m.fragmentShader = `
  
  uniform mat4 inverse_view_proj;
	uniform float screen_width;
	uniform float screen_height;
  float a;
  
  void main() {
		// Convert screen coordinates to normalized device coordinates (NDC)
    vec4 ndc = vec4(
        (gl_FragCoord.x / screen_width - 0.5) * 2.0,
        (gl_FragCoord.y / screen_height - 0.5) * 2.0,
        (gl_FragCoord.z - 0.5) * 2.0,
        1.0);

    // Convert NDC throuch inverse clip coordinates to view coordinates
    vec4 clip = inverse_view_proj * ndc;
    vec3 vertex = (clip / clip.w).xyz;
    
    // From attempt 1
  	float z = gl_FragCoord.z / gl_FragCoord.w;
    vec3 test = vec3(0.0,0.0,(gl_FragCoord.z / gl_FragCoord.w));
    
    // change alpha at a certain z value
    if( ndc.z >= 0.0) {
      a = 1.0;
    } else {
      a = 0.5;
    }
    
    // Results using >= 0.0:
      // ndc.z: a = 1.0 at all times
    	// clip.z: a = 1.0 at all times
    	// vertex.z: a = 0.5 at all times
      // test.z: a = 1.0 at all times (test.z appears to be around 5.0)
            
		// Results using >= 1.0:
      // ndc.z: a = 0.5 at all times
    	// clip.z: a = 0.5 at all times
    	// vertex.z: a = 0.5 at all times
      // test.z: a = 1.0 at all times
    
    // Which leads me to think that the z for all of the above
    // clip, vertex and ndc are not being re-evaluated each render
    // and is wrong code to get the correct z
    
    // Set FragColor
  	gl_FragColor = vec4( vec3( 1.0 ), a );
  }`;
};

const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

const...