all files / src/ Material.js

82.46% Statements 174/211
65.38% Branches 85/130
88.46% Functions 23/26
82.46% Lines 174/211
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620        1×   1×     70× 70× 70×   70× 134× 134× 134× 6×     128×     70×       35× 35× 35× 11× 11×   35×       35× 25×     10× 10× 10×             1× 54×                                                                                                                       54× 52×     54×   54×               84×             84×   84× 1121× 1121× 1121×   96×   1025× 251× 150× 12×           84× 1121× 1121× 1121×                     1121×       238× 238× 238× 238×         238×   883× 96× 96× 96× 96×     96× 96×             787× 251× 184×     67×   67× 12×       12× 12× 12×   12× 12× 12× 12× 12×             12×     55×       536×       84×                     118×     118× 118×   107×         107×   107× 9× 9×                                                                                                               40×             40×                 83× 83× 83×                 54×     54× 54×   54× 54×   54×   54× 54×   54× 54×   54× 54×           54× 54×     54× 54× 467×             54×   54×               1×       1× 45×   1× 1× 1× 1×   1×                   64× 64× 64×               64× 64×             64× 64× 45× 45× 45×                       64×             64×             64× 64× 1× 1× 1×                         89×       89×                 2×       2×                 11×             11× 11× 11× 11× 9× 9×               14× 14× 14×     14×             1×             1× 1× 1× 1× 1× 1×               1× 1× 1×     1×               1× 1×                 60× 60× 60× 554× 22×     60×                     1× 1×   641×           108×       1×   119× 35×       119×            
import Base from './core/Base';
import Texture from './Texture';
import util from './core/util';
import colorUtil from './core/color';
var parseColor = colorUtil.parseToFloat;
 
var programKeyCache = {};
 
function getDefineCode(defines, lightsNumbers, enabledTextures) {
    var defineKeys = Object.keys(defines);
    defineKeys.sort();
    var defineStr = [];
    // Custom Defines
    for (var i = 0; i < defineKeys.length; i++) {
        var key = defineKeys[i];
        var value = defines[key];
        if (value === null) {
            defineStr.push(key);
        }
        else{
            defineStr.push(key + ' ' + value.toString());
        }
    }
    return defineStr.join('\n');
}
 
function getProgramKey(vertexDefines, fragmentDefines, enabledTextures) {
    enabledTextures.sort();
    var defineStr = [];
    for (var i = 0; i < enabledTextures.length; i++) {
        var symbol = enabledTextures[i];
        defineStr.push(symbol);
    }
    var key = getDefineCode(vertexDefines) + '\n'
        + getDefineCode(fragmentDefines) + '\n'
        + defineStr.join('\n');
 
    if (programKeyCache[key]) {
        return programKeyCache[key];
    }
 
    var id = util.genGUID();
    programKeyCache[key] = id;
    return id;
}
 
/**
 * @constructor clay.Material
 * @extends clay.core.Base
 */
var Material = Base.extend(function () {
    return /** @lends clay.Material# */ {
        /**
         * @type {string}
         */
        name: '',
 
        /**
         * @type {Object}
         */
        // uniforms: null,
 
        /**
         * @type {clay.Shader}
         */
        // shader: null,
 
        /**
         * @type {boolean}
         */
        depthTest: true,
 
        /**
         * @type {boolean}
         */
        depthMask: true,
 
        /**
         * @type {boolean}
         */
        transparent: false,
        /**
         * Blend func is a callback function when the material
         * have custom blending
         * The gl context will be the only argument passed in tho the
         * blend function
         * Detail of blend function in WebGL:
         * http://www.khronos.org/registry/gles/specs/2.0/es_full_spec_2.0.25.pdf
         *
         * Example :
         * function(_gl) {
         *  _gl.blendEquation(_gl.FUNC_ADD);
         *  _gl.blendFunc(_gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA);
         * }
         */
        blend: null,
 
        /**
         * If update texture status automatically.
         */
        autoUpdateTextureStatus: true,
 
        uniforms: {},
        vertexDefines: {},
        fragmentDefines: {},
        _textureStatus: {},
 
        // shadowTransparentMap : null
        _enabledUniforms: null,
    };
}, function () {
    if (!this.name) {
        this.name = 'MATERIAL_' + this.__uid__;
    }
 
    Eif (this.shader) {
        // Keep status, mainly preset uniforms, vertexDefines and fragmentDefines
        this.attachShader(this.shader, true);
    }
},
/** @lends clay.Material.prototype */
{
    precision: 'highp',
 
    bind: function(renderer, program, prevMaterial, prevProgram) {
        var _gl = renderer.gl;
        // PENDING Same texture in different material take different slot?
 
        // May use shader of other material if shader code are same
 
        // var sameProgram = prevProgram === program;
 
        var currentTextureSlot = program.currentTextureSlot();
 
        for (var u = 0; u < this._enabledUniforms.length; u++) {
            var symbol = this._enabledUniforms[u];
            var uniformValue = this.uniforms[symbol].value;
            if (uniformValue instanceof Texture) {
                // Reset slot
                uniformValue.__slot = -1;
            }
            else if (Array.isArray(uniformValue)) {
                for (var i = 0; i < uniformValue.length; i++) {
                    if (uniformValue[i] instanceof Texture) {
                        uniformValue[i].__slot = -1;
                    }
                }
            }
        }
        // Set uniforms
        for (var u = 0; u < this._enabledUniforms.length; u++) {
            var symbol = this._enabledUniforms[u];
            var uniform = this.uniforms[symbol];
            var uniformValue = uniform.value;
            // PENDING
            // When binding two materials with the same shader
            // Many uniforms will be be set twice even if they have the same value
            // So add a evaluation to see if the uniform is really needed to be set
            // if (prevMaterial && sameShader) {
            //     if (prevMaterial.uniforms[symbol].value === uniformValue) {
            //         continue;
            //     }
            // }
 
            if (uniformValue === null) {
                // FIXME Assume material with same shader have same order uniforms
                // Or if different material use same textures,
                // the slot will be different and still skipped because optimization
                Eif (uniform.type === 't') {
                    var slot = program.currentTextureSlot();
                    var res = program.setUniform(_gl, '1i', symbol, slot);
                    Iif (res) { // Texture is enabled
                        // Still occupy the slot to make sure same texture in different materials have same slot.
                        program.takeCurrentTextureSlot(renderer, null);
                    }
                }
                continue;
            }
            else if (uniformValue instanceof Texture) {
                Eif (uniformValue.__slot < 0) {
                    var slot = program.currentTextureSlot();
                    var res = program.setUniform(_gl, '1i', symbol, slot);
                    Iif (!res) { // Texture uniform is not enabled
                        continue;
                    }
                    program.takeCurrentTextureSlot(renderer, uniformValue);
                    uniformValue.__slot = slot;
                }
                // Multiple uniform use same texture..
                else {
                    program.setUniform(_gl, '1i', symbol, uniformValue.__slot);
                }
            }
            else if (Array.isArray(uniformValue)) {
                if (uniformValue.length === 0) {
                    continue;
                }
                // Texture Array
                var exampleValue = uniformValue[0];
 
                if (exampleValue instanceof Texture) {
                    Iif (!program.hasUniform(symbol)) {
                        continue;
                    }
 
                    var arr = [];
                    for (var i = 0; i < uniformValue.length; i++) {
                        var texture = uniformValue[i];
 
                        Eif (texture.__slot < 0) {
                            var slot = program.currentTextureSlot();
                            arr.push(slot);
                            program.takeCurrentTextureSlot(renderer, texture);
                            texture.__slot = slot;
                        }
                        else {
                            arr.push(texture.__slot);
                        }
                    }
 
                    program.setUniform(_gl, '1iv', symbol, arr);
                }
                else {
                    program.setUniform(_gl, uniform.type, symbol, uniformValue);
                }
            }
            else{
                program.setUniform(_gl, uniform.type, symbol, uniformValue);
            }
        }
        // Texture slot maybe used out of material.
        program.resetTextureSlot(currentTextureSlot);
    },
 
    /**
     * Set material uniform
     * @example
     *  mat.setUniform('color', [1, 1, 1, 1]);
     * @param {string} symbol
     * @param {number|array|clay.Texture|ArrayBufferView} value
     */
    setUniform: function (symbol, value) {
        Iif (value === undefined) {
            console.warn('Uniform value "' + symbol + '" is undefined');
        }
        var uniform = this.uniforms[symbol];
        if (uniform) {
 
            Iif (typeof value === 'string') {
                // Try to parse as a color. Invalid color string will return null.
                value = parseColor(value) || value;
            }
 
            uniform.value = value;
 
            if (this.autoUpdateTextureStatus && uniform.type === 't') {
                Eif (value) {
                    this.enableTexture(symbol);
                }
                else {
                    this.disableTexture(symbol);
                }
            }
        }
    },
 
    /**
     * @param {Object} obj
     */
    setUniforms: function(obj) {
        for (var key in obj) {
            var val = obj[key];
            this.setUniform(key, val);
        }
    },
 
    // /**
    //  * Enable a uniform
    //  * It only have effect on the uniform exists in shader.
    //  * @param  {string} symbol
    //  */
    // enableUniform: function (symbol) {
    //     if (this.uniforms[symbol] && !this.isUniformEnabled(symbol)) {
    //         this._enabledUniforms.push(symbol);
    //     }
    // },
 
    // /**
    //  * Disable a uniform
    //  * It will not affect the uniform state in the shader. Because the shader uniforms is parsed from shader code with naive regex. When using micro to disable some uniforms in the shader. It will still try to set these uniforms in each rendering pass. We can disable these uniforms manually if we need this bit performance improvement. Mostly we can simply ignore it.
    //  * @param  {string} symbol
    //  */
    // disableUniform: function (symbol) {
    //     var idx = this._enabledUniforms.indexOf(symbol);
    //     if (idx >= 0) {
    //         this._enabledUniforms.splice(idx, 1);
    //     }
    // },
 
    /**
     * @param  {string}  symbol
     * @return {boolean}
     */
    isUniformEnabled: function (symbol) {
        return this._enabledUniforms.indexOf(symbol) >= 0;
    },
 
    /**
     * Alias of setUniform and setUniforms
     * @param {object|string} symbol
     * @param {number|array|clay.Texture|ArrayBufferView} [value]
     */
    set: function (symbol, value) {
        Iif (typeof(symbol) === 'object') {
            for (var key in symbol) {
                var val = symbol[key];
                this.setUniform(key, val);
            }
        }
        else {
            this.setUniform(symbol, value);
        }
    },
    /**
     * Get uniform value
     * @param  {string} symbol
     * @return {number|array|clay.Texture|ArrayBufferView}
     */
    get: function (symbol) {
        var uniform = this.uniforms[symbol];
        Eif (uniform) {
            return uniform.value;
        }
    },
    /**
     * Attach a shader instance
     * @param  {clay.Shader} shader
     * @param  {boolean} keepStatus If try to keep uniform and texture
     */
    attachShader: function(shader, keepStatus) {
        var originalUniforms = this.uniforms;
 
        // Ignore if uniform can use in shader.
        this.uniforms = shader.createUniforms();
        this.shader = shader;
 
        var uniforms = this.uniforms;
        this._enabledUniforms = Object.keys(uniforms);
        // Make sure uniforms are set in same order to avoid texture slot wrong
        this._enabledUniforms.sort();
 
        var originalVertexDefines = this.vertexDefines;
        var originalFragmentDefines = this.fragmentDefines;
 
        this.vertexDefines = util.clone(shader.vertexDefines);
        this.fragmentDefines = util.clone(shader.fragmentDefines);
 
        Eif (keepStatus) {
            for (var symbol in originalUniforms) {
                if (uniforms[symbol]) {
                    uniforms[symbol].value = originalUniforms[symbol].value;
                }
            }
 
            util.defaults(this.vertexDefines, originalVertexDefines);
            util.defaults(this.fragmentDefines, originalFragmentDefines);
        }
 
        var textureStatus = {};
        for (var key in shader.textures) {
            textureStatus[key] = {
                shaderType: shader.textures[key].shaderType,
                type: shader.textures[key].type,
                enabled: (keepStatus && this._textureStatus[key]) ? this._textureStatus[key].enabled : false
            };
        }
 
        this._textureStatus = textureStatus;
 
        this._programKey = '';
    },
 
    /**
     * Clone a new material and keep uniforms, shader will not be cloned
     * @return {clay.Material}
     */
    clone: function () {
        var material = new this.constructor({
            name: this.name,
            shader: this.shader
        });
        for (var symbol in this.uniforms) {
            material.uniforms[symbol].value = this.uniforms[symbol].value;
        }
        material.depthTest = this.depthTest;
        material.depthMask = this.depthMask;
        material.transparent = this.transparent;
        material.blend = this.blend;
 
        return material;
    },
 
    /**
     * Add a #define macro in shader code
     * @param  {string} shaderType Can be vertex, fragment or both
     * @param  {string} symbol
     * @param  {number} [val]
     */
    define: function (shaderType, symbol, val) {
        var vertexDefines = this.vertexDefines;
        var fragmentDefines = this.fragmentDefines;
        Iif (shaderType !== 'vertex' && shaderType !== 'fragment' && shaderType !== 'both'
            && arguments.length < 3
        ) {
            // shaderType default to be 'both'
            val = symbol;
            symbol = shaderType;
            shaderType = 'both';
        }
        val = val != null ? val : null;
        Iif (shaderType === 'vertex' || shaderType === 'both') {
            if (vertexDefines[symbol] !== val) {
                vertexDefines[symbol] = val;
                // Mark as dirty
                this._programKey = '';
            }
        }
        Eif (shaderType === 'fragment' || shaderType === 'both') {
            if (fragmentDefines[symbol] !== val) {
                fragmentDefines[symbol] = val;
                Eif (shaderType !== 'both') {
                    this._programKey = '';
                }
            }
        }
    },
 
    /**
     * Remove a #define macro in shader code
     * @param  {string} shaderType Can be vertex, fragment or both
     * @param  {string} symbol
     */
    undefine: function (shaderType, symbol) {
        Iif (shaderType !== 'vertex' && shaderType !== 'fragment' && shaderType !== 'both'
            && arguments.length < 2
        ) {
            // shaderType default to be 'both'
            symbol = shaderType;
            shaderType = 'both';
        }
        Iif (shaderType === 'vertex' || shaderType === 'both') {
            if (this.isDefined('vertex', symbol)) {
                delete this.vertexDefines[symbol];
                // Mark as dirty
                this._programKey = '';
            }
        }
        Eif (shaderType === 'fragment' || shaderType === 'both') {
            if (this.isDefined('fragment', symbol)) {
                delete this.fragmentDefines[symbol];
                Eif (shaderType !== 'both') {
                    this._programKey = '';
                }
            }
        }
    },
 
    /**
     * If macro is defined in shader.
     * @param  {string} shaderType Can be vertex, fragment or both
     * @param  {string} symbol
     */
    isDefined: function (shaderType, symbol) {
        // PENDING hasOwnProperty ?
        switch (shaderType) {
            case 'vertex':
                return this.vertexDefines[symbol] !== undefined;
            case 'fragment':
                return this.fragmentDefines[symbol] !== undefined;
        }
    },
    /**
     * Get macro value defined in shader.
     * @param  {string} shaderType Can be vertex, fragment or both
     * @param  {string} symbol
     */
    getDefine: function (shaderType, symbol) {
        switch(shaderType) {
            case 'vertex':
                return this.vertexDefines[symbol];
            case 'fragment':
                return this.fragmentDefines[symbol];
        }
    },
    /**
     * Enable a texture, actually it will add a #define macro in the shader code
     * For example, if texture symbol is diffuseMap, it will add a line `#define DIFFUSEMAP_ENABLED` in the shader code
     * @param  {string} symbol
     */
    enableTexture: function (symbol) {
        Iif (Array.isArray(symbol)) {
            for (var i = 0; i < symbol.length; i++) {
                this.enableTexture(symbol[i]);
            }
            return;
        }
 
        var status = this._textureStatus[symbol];
        Eif (status) {
            var isEnabled = status.enabled;
            if (!isEnabled) {
                status.enabled = true;
                this._programKey = '';
            }
        }
    },
    /**
     * Enable all textures used in the shader
     */
    enableTexturesAll: function () {
        var textureStatus = this._textureStatus;
        for (var symbol in textureStatus) {
            textureStatus[symbol].enabled = true;
        }
 
        this._programKey = '';
    },
    /**
     * Disable a texture, it remove a #define macro in the shader
     * @param  {string} symbol
     */
    disableTexture: function (symbol) {
        Iif (Array.isArray(symbol)) {
            for (var i = 0; i < symbol.length; i++) {
                this.disableTexture(symbol[i]);
            }
            return;
        }
 
        var status = this._textureStatus[symbol];
        Eif (status) {
            var isDisabled = ! status.enabled;
            Eif (!isDisabled) {
                status.enabled = false;
                this._programKey = '';
            }
        }
    },
    /**
     * Disable all textures used in the shader
     */
    disableTexturesAll: function () {
        var textureStatus = this._textureStatus;
        for (var symbol in textureStatus) {
            textureStatus[symbol].enabled = false;
        }
 
        this._programKey = '';
    },
    /**
     * If texture of given type is enabled.
     * @param  {string}  symbol
     * @return {boolean}
     */
    isTextureEnabled: function (symbol) {
        var textureStatus = this._textureStatus;
        return !!textureStatus[symbol]
            && textureStatus[symbol].enabled;
    },
 
    /**
     * Get all enabled textures
     * @return {string[]}
     */
    getEnabledTextures: function () {
        var enabledTextures = [];
        var textureStatus = this._textureStatus;
        for (var symbol in textureStatus) {
            if (textureStatus[symbol].enabled) {
                enabledTextures.push(symbol);
            }
        }
        return enabledTextures;
    },
 
    /**
     * Mark defines are updated.
     */
    dirtyDefines: function () {
        this._programKey = '';
    }
});
 
Eif (Object.defineProperty) {
    Object.defineProperty(Material.prototype, 'shader', {
        get: function () {
            return this._shader || null;
        },
 
        set: function (val) {
            // TODO
            // console.warn('You need to use attachShader to set the shader.');
            this._shader = val;
        }
    });
 
    Object.defineProperty(Material.prototype, 'programKey', {
        get: function () {
            if (!this._programKey) {
                this._programKey = getProgramKey(
                    this.vertexDefines, this.fragmentDefines, this.getEnabledTextures()
                );
            }
            return this._programKey;
        }
    });
}
 
export default Material;