aboutsummaryrefslogtreecommitdiff
path: root/js/lib/rdge/materials/material.js
blob: 6cfc4eb4c78145633181b2217c4152a21b4c6733 (plain)
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
/* <copyright>
Copyright (c) 2012, Motorola Mobility, Inc
All Rights Reserved.
BSD License.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

  - Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
  - Neither the name of Motorola Mobility nor the names of its contributors
    may be used to endorse or promote products derived from this software
    without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
</copyright> */

var Texture = require("js/lib/rdge/texture").Texture;


///////////////////////////////////////////////////////////////////////
// Class GLMaterial
//      GL representation of a material.
///////////////////////////////////////////////////////////////////////
var Material = function GLMaterial( world ) {
    ///////////////////////////////////////////////////////////////////////
    // Instance variables
    ///////////////////////////////////////////////////////////////////////
    this._name = "GLMaterial";
    this._shaderName = "undefined";

    this._time = 0.0;
    this._dTime = 0.01;

    // keep a reference to the owning GLWorld
    this._world = null;
    if(world) {
        this._world = world;
    }

    this._glTextures = [];      // indexed by uniform name

    // vertex deformation variables
    this._hasVertexDeformation = false;
    this._vertexDeformationRange = [0, 0, 1, 1];    // (xMin, yMin, xMax, yMax)
	this._vertexDeformationTolerance = 0.02;

    // RDGE variables
    this._shader = null;
    this._materialNode = null;


    ///////////////////////////////////////////////////////////////////////
    // Property Accessors
    ///////////////////////////////////////////////////////////////////////

    this.setName = function(n) {
        this._name = n;
    };

    this.getName = function() {
        return this._name;
    };

    this.setShaderName = function(n) {
        this._shaderName = n;
    };

    this.getShaderName = function() {
        return this._shaderName;
    };

    this.setWorld = function(world) {
        this._world = world;
    };

    this.getWorld = function() {
        return this._world;
    };

    this.getShader = function() {
        return this._shader;
    };

    this.getMaterialNode = function() {
        return this._materialNode;
    };

    // a material can be animated or not. default is not.
    // Any material needing continuous rendering should override this method
    this.isAnimated = function() {
        return false;
    };

    this.getTechniqueName   = function() {
        return 'default'
    };

    // the vertex shader can apply deformations requiring refinement in
    // certain areas.
    this.hasVertexDeformation = function()  {
        return this._hasVertexDeformation;
    };

    this.getVertexDeformationRange = function() {
        return this._vertexDeformationRange.slice();
    };

    this.getVertexDeformationTolerance = function() {
        return this._vertexDeformationTolerance;
    };

    ///////////////////////////////////////////////////////////////////////
    // Common Material Methods
    ///////////////////////////////////////////////////////////////////////
    this.getProperty = function( propName ) {
        return this._propValues[propName];
    };

    this.getPropertyCount = function() {
        return this._propNames.length;
    };

    this.getPropertyAtIndex = function( index ) {
        var rtnArr = [];
        if ((index < 0) || (index >= this.getPropertyCount())) {
            throw new Error( "property index " + index + " is out of range for material" );
        }

        return [ this._propNames[index],  this._propLabels[index],  this._propTypes[index],  this._propValues[index] ];
    };

    this.getAllProperties = function( propNames,  propValues,  propTypes,  propLabels) {
        // clear all the input arrays if there is junk in them
        propNames.length    = 0;
        propValues.length   = 0;
        propTypes.length    = 0;
        propLabels.length   = 0;

        var nProps = this._propNames.length;
        for (var i=0;  i<nProps;  i++) {
            propNames[i]    = this._propNames[i];
            propValues[i]   = this._propValues[this._propNames[i]];
            propTypes[i]    = this._propTypes[i];
            propLabels[i]   = this._propLabels[i];
        }
    };

    this.hasProperty = function( prop )
    {
        var propNames = [],  dummy = [];
        this.getAllProperties( propNames, dummy, dummy, dummy )
        for (var i=0;  i<propNames.length;  i++)
        {
            if (prop === propNames[i])  return true;
        }
    };

    this.getPropertyType = function( prop )
    {
        var n = this.getPropertyCount();
        for (var i=0;  i<n;  i++)
        {
            if (prop === this._propNames[i])  return this._propTypes[i];
        }
    };

    this.dup = function ()
    {
        // get the current values;
        var propNames = [], propValues = [], propTypes = [], propLabels = [];
        this.getAllProperties(propNames, propValues, propTypes, propLabels);

        // allocate a new material
        var MaterialLibrary = require("js/models/materials-model").MaterialsModel;
        var newMat = MaterialLibrary.createMaterialByShaderName( this.getShaderName() );

        // copy over the current values;
        var n = propNames.length;
        for (var i = 0; i < n; i++)
            newMat.setProperty(propNames[i], propValues[i]);

        return newMat;
    };

    this.validateProperty = function( prop, value ) {
        if(prop === "gradient") return true;

        var rtnVal = false;
        try
        {
            //if (!this._propValues[prop])  return false;

            // find the index of the property
            var n = this._propNames.length;
            var valType =  typeof value;
            for (var i=0;  i<n;  i++) {
                if (this._propNames[i] == prop) {

                    switch (this._propTypes[i])
                    {
                        case "color":
                            rtnVal = ((valType == "object") && (value.length >= 4));
                            break;

                        case "vector2d":
                            rtnVal = ((valType == "object") && (value.length >= 2));
                            break;

                        case "vector3d":
                            rtnVal = ((valType == "object") && (value.length >= 3));
                            break;

                        case "angle":
                        case "float":
                            rtnVal = (valType == "number");
                            break;

                        case "file":
                            rtnVal = ((valType == "string") || !value);
                            break;
                    }

                    break;
                }
            }
        }
        catch(e)  {
            console.log( "setting invalid material property: " + prop + ", value: " + value );
        }

//      if (!rtnVal && (prop != 'color')) {
//          console.log( "invalid material property: " + prop + " : " + value );
//        }

        return rtnVal;
    };

    this.setProperty = function( prop,  value )
    {
        var ok = this.validateProperty( prop, value );
        if (!ok && (prop != 'color')) {
            //console.log( "invalid property in Material:" + prop + " : " + value );
            return;
        }

        // get the technique if the shader is instantiated
        var technique;
        var material = this._materialNode;
        if (material)  technique = material.shaderProgram[this.getTechniqueName()];

        if(prop === "gradient") {
            this.setGradientData(value);
        } else {
        switch (this.getPropertyType(prop))
        {
            case "angle":
            case "float":
                this._propValues[prop] = value;
                if (technique)  technique[prop].set( [value] );
                break;

            case "file":
                this._propValues[prop] = value.slice();
                if (technique)
                {
                    var glTex = new Texture( this.getWorld(),  value );
                    this._glTextures[prop] = glTex;
                    glTex.render();
                    var tex = glTex.getTexture();
                    if (tex)  technique[prop].set( tex );
                }
                break;

            case "color":
            case "vector2d":
            case "vector3d":
                this._propValues[prop] = value.slice();
                if (technique)  technique[prop].set( value );
                break;
        }
        }
    };

    this.setShaderValues = function()
    {
        var material = this._materialNode;
        if (material)
        {
            var technique = material.shaderProgram[this.getTechniqueName()];
            if (technique)
            {
                var n = this.getPropertyCount();
                for (var i=0;  i<n;  i++)
                {
                    var prop = this._propNames[i],
                        value = this._propValues[prop];

                    switch (this._propTypes[i])
                    {
                        case "angle":
                        case "float":
                            technique[prop].set( [value] );
                            break;

                        case "file":
                            var glTex = this._glTextures[prop];
                            if (glTex)
                            {
                                var tex = glTex.getTexture();
                                if (tex)  technique[prop].set( tex );
                            }
                            else
                                this.setProperty( prop, value );
                            break;

                        case "color":
                        case "vector2d":
                        case "vector3d":
                            technique[prop].set( value );
                            break;
                    }
                }
            }
        }
    };

    // JSON export
    this.exportJSON = function()
    {
        var jObj =
        {
            'material'      : this.getShaderName(),
            'name'          : this.getName(),
            'dTime'         : this._dTime
        };

        var n = this.getPropertyCount();
        for (var i=0;  i<n;  i++)
        {
            var prop  = this._propNames[i],
                value = this._propValues[prop];

            jObj[prop] = value;
        }

        if (this.customExport)
            jObj = this.customExport( jObj );

        return jObj;
    };

    this.importJSON = function (jObj) {
        if (this.getShaderName() != jObj.material) throw new Error("ill-formed material");
        this.setName(jObj.name);

        try
        {
            for (var prop in jObj)
            {
                if ((prop != 'material') && (prop != 'name'))
                {
                    var value = jObj[prop];
                    this.setProperty( prop, value );
                }
            }
        }
        catch (e) {
            throw new Error("could not import material: " + jObj);
        }
    };

    ///////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////
    // Methods
    ///////////////////////////////////////////////////////////////////////
    this.init = function( world ) {
        throw new Error( "Material.init() must be overridden by subclass" );
    };

	this.resetToDefault = function()  {
		// materials should override this functinon
	};

    this.update = function( time ) {
        // animated materials should implement the update method
    };

    this.fitToPrimitive = function( prim )  {
        // some materials need to preserve an aspect ratio - or someting else.
    };

	this.fitToPrimitiveArray = function( primArray )  {
		// some materials need to preserve an aspect ratio - or someting else.
	};

    this.registerTexture = function( texture ) {
        // the world needs to know about the texture map
        var world = this.getWorld();
        if (!world) {
            console.log( "**** world not defined for registering texture map: " + texture.lookUpName );
        } else {
            world.textureToLoad( texture );
        }
    };

    this.loadTexture = function( texMapName, wrap, mips ) {
        var tex;
        var world = this.getWorld();
        if (!world) {
            console.log( "world not defined for material with texture map" );
        } else {
            var renderer = world.getRenderer();
            tex = renderer.getTextureByName(texMapName, wrap, mips );
            this.registerTexture( tex );
        }

        return tex;
    };

    this.gradientType = null;

    this.getGradientData = function() {
        return null;
};

    this.setGradientData = function() {
        // override in linear-gradient-material and radial-gradient-material
    };
};

if (typeof exports === "object") {
    exports.Material = Material;
}