Three.js, custom shader and png texture with transparency
Asked Answered
G

1

7

I have an extremely simple PNG texture: a grey circle with a transparent background.

PNG image with transparency

I use it as a uniform map for a THREE.ShaderMaterial:

var uniforms = THREE.UniformsUtils.merge( [basicShader.uniforms] );
uniforms['map'].value = THREE.ImageUtils.loadTexture( "img/particle.png" );
uniforms['size'].value = 100;
uniforms['opacity'].value = 0.5;
uniforms['psColor'].value = new THREE.Color( 0xffffff );

Here is my fragment shader (just part of it):

gl_FragColor = vec4( psColor, vOpacity );
gl_FragColor = gl_FragColor * texture2D( map,vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );
gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );

I applied the material to some particles (THREE.PointCloud mesh) and it works quite well:

Particles texture with transparency: OK!

But if i turn the camera of more than 180 degrees I see this:

Particles texture without transparency

I understand that the fragment shader is not correctly taking into account the alpha value of the PNG texture.

What is the best approach in this case, to get the right color and opacity (from custom attributes) and still get the alpha right from the PNG?

And why is it behaving correctly on one side?

Gereron answered 24/6, 2015 at 21:15 Comment(0)
J
12

Transparent objects must be rendered from back to front -- from furthest to closest. This is because of the depth buffer.

But PointCloud particles are not sorted based on distance from the camera. That would be too inefficient. The particles are always rendered in the same order, regardless of the camera position.

You have several work-arounds.

The first is to discard fragments for which the alpha is low. You can use a pattern like so:

if ( textureColor.a < 0.5 ) discard;

Another option is to set material.depthTest = false or material.depthWrite = false. You might not like the side effects, however, if you have other objects in the scene.

three.js r.71

Jonijonie answered 24/6, 2015 at 22:12 Comment(2)
Great, I tried textureColor.a < 0.3 and looks perfect. Thanks also for the details, I understand better how the PointCloud works now.Gereron
Well... actually looks better with < 0.5Gereron

© 2022 - 2024 — McMap. All rights reserved.