Grass.js 2.06 KB
import {BaseMaterial} from "../core/BaseMaterial";

function Grass(args) {
    BaseMaterial.call(this);

    this.args = args;

    this.uniforms = {
        uTime: {value: 0},
        uElevation: {value: 0.3},
        uFrequency: {value: new THREE.Vector2(1, 3)},
        uSpeed: {value: 0.7},
        uHeight: {value: 0.6},
        uMap: {value: args.mesh.material.map},
    };

    this.material = null;
    this.prepare();
}

Grass.prototype = Object.create(BaseMaterial.prototype);
Grass.prototype.constructor = Grass;

Grass.prototype.prepare = function () {

    if (this.args.mesh.name.toLowerCase().includes("grass")) {

        this.material = this.copy(this.args.mesh.material);

        this.material.transparent = true;
        this.material.alphaTest = 0.5;
        this.material.depthWrite = true;
        this.material.side = THREE.DoubleSide;

        this.material.userData.effect = 'Grass';
        this.material.userData.args = this.args;
        this.material.userData.uniforms = this.uniforms;

        this.material.onBeforeCompile = function (shader) {

            shader.uniforms.uTime = this.userData.uniforms.uTime;
            shader.uniforms.uElevation = this.userData.uniforms.uElevation;
            shader.uniforms.uFrequency = this.userData.uniforms.uFrequency;
            shader.uniforms.uSpeed = this.userData.uniforms.uSpeed;
            shader.uniforms.uHeight = this.userData.uniforms.uHeight;

            this.userData.shader = shader;
            shader.fragmentShader = require('../glsl/fs/grass_pars.fs.glsl') + shader.fragmentShader;

            shader.fragmentShader = shader.fragmentShader.replace('#include <map_fragment>',
                require('../glsl/fs/grass.fs.glsl'));

            shader.vertexShader = require('../glsl/vs/grass_pars.vs.glsl') + shader.vertexShader;

            shader.vertexShader = shader.vertexShader.replace('#include <project_vertex>',
                require('../glsl/vs/grass.vs.glsl'));

        };
    }
    return this;

};
Grass.prototype.update = function (dt) {
    this.uniforms.uTime.value += dt;
};

export {Grass}