Sungaila Sungaila - 10 days ago 7
Javascript Question

Three.js shader material doesn't display particles

I have a very basic scene which includes a grid of particles in the shape of a cube. You can find it here: https://codepen.io/sungaila/pen/qqVXKM

My problem is that if I use a ShaderMaterial, I can't get the particles to display. The following is my (very simple) shader code:

<script type = 'x-shader/x-vertex' id = 'vertexShader'>
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0);
}
</script>

<script type = 'x-shader-x-fragment' id = 'fragmentShader'>
void main() {
gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 );
}
</script>


And the following is the relevant JS code:

geometry = new THREE.BoxBufferGeometry(10,10,10, 5, 5, 5);

material = new THREE.ShaderMaterial({
vertexShader: document.getElementById( 'vertexShader' ).textContent,
fragmentShader: document.getElementById( 'fragmentShader' ).textContent
});

particles = new THREE.Points(geometry, material);


Something I noticed is that if I comment out the 'material' lines, the material will default to 'PointsMaterial' and the particles will display. Also, the color of the particles will somehow be affected by the shader code even though I feel like I haven't linked them together yet.

How do I get the particles to display using a ShaderMaterial?

Answer

You need to set gl_PointSize in your vertex shader.

<script type = 'x-shader/x-vertex' id = 'vertexShader'>
void main() {
    vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); 
    gl_PointSize = 1.0 * ( 300.0 / -mvPosition.z ); 
    gl_Position = projectionMatrix * mvPosition;
}
</script>