threejs为ShaderMaterial添加照明

时间:2014-03-25 06:41:17

标签: three.js glsl

我正在创建一个充满球体的立方体。所以我正在使用粒子系统。在我尝试将着色器材质应用于每个粒子之前,它们都运行良好。我几乎用http://threejs.org/examples/#webgl_custom_attributes_particles3的例子。

它正在工作,但我现在要做的是使用定向照明为场景添加光照。这就是我无处可去的地方。我没有GLSL的经验,现在只是复制和粘贴,测试水域。任何帮助都会很棒。

这是我到目前为止所拥有的。

<script type="x-shader/x-vertex" id="vertexshader">

    attribute float size;
    attribute vec4 ca;

    varying vec4 vColor;

    void main() {

    vColor = ca;

    vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );

    gl_PointSize = size * ( 150.0 / length( mvPosition.xyz ) );

    gl_Position = projectionMatrix * mvPosition;

    }

</script>

<script type="x-shader/x-fragment" id="fragmentshader">

    uniform vec3 color;
    uniform sampler2D texture;

    varying vec4 vColor;

    void main() {

    vec4 outColor = texture2D( texture, gl_PointCoord );

    if ( outColor.a < 0.5 ) discard;

    gl_FragColor = outColor * vec4( color * vColor.xyz, 1.0 );

    float depth = gl_FragCoord.z / gl_FragCoord.w;
    const vec3 fogColor = vec3( 0.0 );

    float fogFactor = smoothstep( 200.0, 700.0, depth );
    gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );

    }

</script>

和我的js:

(function addSpheres() {
var cube = new THREE.Object3D();
scene.add(cube);

var totalSpheres = 3840; //15*16*16
var particles = new THREE.Geometry();

var attributes = {
    size: { type: 'f', value: [] },
    ca: { type: 'c', value: [] }
};
var uniforms = {
    amplitude: { type: "f", value: 1.0 },
    color: { type: "c", value: new THREE.Color(0xffffff) },
    texture: { type: "t", value: THREE.ImageUtils.loadTexture("textures/sprites/ball.png") }
};
uniforms.texture.value.wrapS = uniforms.texture.value.wrapT = THREE.RepeatWrapping;

var shaderMaterial = new THREE.ShaderMaterial({
    uniforms: uniforms,
    attributes: attributes,
    vertexShader: document.getElementById('vertexshader').textContent,
    fragmentShader: document.getElementById('fragmentshader').textContent,
});
shaderMaterial.lights = true;

var n = 20, n2 = n / 2;
var particle;
for (var i = -7; i < 9; i++) {
    for (var j = -7; j < 9; j++) {
        for (var k = -7; k < 8; k++) {
            var pX = i * n - n2;
            var pY = j * n - n2;
            var pZ = k * n - n2;

            particle = new THREE.Vector3(pX, pY, pZ);
            particles.vertices.push(particle);
        }
    }
}

particleSystem = new THREE.ParticleSystem(particles, shaderMaterial);
particleSystem.dynamic = true;

// custom attributes

var vertices = particleSystem.geometry.vertices;
var values_size = attributes.size.value;
var values_color = attributes.ca.value;

for (var v = 0; v < vertices.length; v++) {
    attributes.size.value[v] = 55;
    attributes.ca.value[v] = new THREE.Color(0xffffff);

    attributes.size.needsUpdate = true;
    attributes.ca.needsUpdate = true;
}

cube.add(particleSystem);

scene.matrixAutoUpdate = false;
})();

提前致谢。 约翰。

0 个答案:

没有答案