Changeset 21094


Ignore:
Timestamp:
08/04/16 21:02:55 (9 years ago)
Author:
dlcheng
Message:

CHG (JS): Optimized to use litegl framework.

Location:
issm/trunk-jpl/src/m/plot
Files:
5 edited

Legend:

Unmodified
Added
Removed
  • issm/trunk-jpl/src/m/plot/plot_mesh.js

    r20769 r21094  
    6363        scale = 1 / (xmax - xmin);
    6464        node["shaderName"] = "colored";
    65         node["shader"] = gl["shaders"][node["shaderName"]]["program"];
     65        node["shader"] = gl["shaders"][node["shaderName"]];
    6666        node["lineWidth"] = options.getfieldvalue('linewidth',1);
    6767        node["scale"] = [scale, scale, scale * matrixscale];
     
    7373        node["maskHeight"] = options.getfieldvalue('innermaskheight',150.0)*options.getfieldvalue('heightscale',1);
    7474        node["maskColor"] = options.getfieldvalue('innermaskcolor',[0.0,0.0,1.0,1.0]);
    75                                
    76         //some defaults:
    77         colors.itemSize = 4;
    7875
    7976        //retrieve some options
     
    8885        }
    8986        else{ //2D triangular elements
    90                 vertices.itemSize = 3;
    9187                var xyz = vec3.create();
    9288                var direction = vec3.create();
     
    135131                        indices[indices.length] = element[0];
    136132                }
    137                 indices.itemSize = 1;
    138133        }
    139134        //}}}
    140 
    141         /*Initalize buffers: */
    142         node["arrays"] = [vertices, colors, indices];
    143         node["buffers"] = initBuffers(gl, node["arrays"]);
     135        node["mesh"] = GL.Mesh.load({vertices:vertices, colors:colors, indices:indices});
    144136}
  • issm/trunk-jpl/src/m/plot/plot_overlay.js

    r20769 r21094  
    6363        scale = 1 / (xmax - xmin);
    6464        node["shaderName"] = "unlit_textured";
    65         node["shader"] = gl["shaders"][node["shaderName"]]["program"];
     65        node["shader"] = gl["shaders"][node["shaderName"]];
    6666        node["scale"] = [scale, scale, scale * matrixscale];
    6767        node["translation"] = [(xmin + xmax) / (-2 / scale), (ymin + ymax) / (-2 / scale), (zmin + zmax) / (2 / scale)];
     
    7373        node["maskHeight"] = options.getfieldvalue('outermaskheight',150.0);
    7474        node["maskColor"] = options.getfieldvalue('outermaskcolor',[0.0,0.0,1.0,1.0]);
    75                                
    76         //some defaults:
    77         texcoords.itemSize = 2;
    78         vertices.itemSize = 3;
    7975       
    8076        //Handle outer radaroverlay
     
    152148                }
    153149        }
    154 
    155150        //linearize the elements array:
    156151        var element;
     
    162157                indices[indices.length] = element[2];
    163158        }
    164         indices.itemSize = 1;
    165        
    166         /*Initalize buffers: */
    167         node["arrays"] = [vertices, texcoords, indices];
    168         node["buffers"] = initBuffers(gl,node["arrays"]);       
     159        node["mesh"] = GL.Mesh.load({vertices:vertices, coords:texcoords, indices:indices});
    169160}
  • issm/trunk-jpl/src/m/plot/plot_quiver.js

    r20792 r21094  
    1111        var indices = [];
    1212        var colors = [];
    13         var rgbcolor = [];
    1413        var xmin,xmax;
    1514        var ymin,ymax;
     
    6665        scale = 1 / (xmax - xmin);
    6766        node["shaderName"] = "colored";
    68         node["shader"] = gl["shaders"][node["shaderName"]]["program"];
     67        node["shader"] = gl["shaders"][node["shaderName"]];
    6968        node["lineWidth"] = options.getfieldvalue('linewidth',1);
    7069        node["scale"] = [scale, scale, scale * matrixscale];
     
    7776        node["maskHeight"] = options.getfieldvalue('innermaskheight',150.0)*options.getfieldvalue('heightscale',1);
    7877        node["maskColor"] = options.getfieldvalue('innermaskcolor',[0.0,0.0,1.0,1.0]);
    79                                
    80         //some defaults:
    81         colors.itemSize = 4;
    8278
    8379        //retrieve some options
     
    9288        }
    9389        else{ //2D triangular elements
    94                 vertices.itemSize = 3;
    9590                var xyz = vec3.create();
    9691                var xyz = vec3.create();
     
    137132        }
    138133        //}}}
    139 
    140         /*Initalize buffers: */
    141         node["arrays"] = [vertices, colors];
    142         node["buffers"] = initBuffers(gl, node["arrays"]);
     134        node["mesh"] = GL.Mesh.load({vertices:vertices, colors:colors});
    143135}
  • issm/trunk-jpl/src/m/plot/plot_unit.js

    r20920 r21094  
    88
    99        //declare variables:  {{{
    10         var vertices = [];
    11         var indices = [];
    12         var texcoords = [];
    13         var nanindices = {};
    14         var xmin,xmax;
    15         var ymin,ymax;
    16         var zmin,zmax;
    17         var datamin,datamax,datadelta;
    18         var scale,matrixscale,vertexscale;
    19 
    2010        //Process data and model
    2111        var meshresults = processmesh(md,data,options);
     
    2616        var is2d = meshresults[4];
    2717        var isplanet = meshresults[5];
     18       
     19        var vertices = new Float32Array(x.length * 3);
     20        var texcoords = new Float32Array(x.length * 2);
     21        var indices = new Uint16Array(elements.length * 3);
     22        var nanindices = {};
     23        var xmin,xmax;
     24        var ymin,ymax;
     25        var zmin,zmax;
     26        var datamin,datamax,datadelta;
     27        var scale,matrixscale,vertexscale;
    2828
    2929        //Compue scaling through matrices for 2d meshes and vertices for 3d meshes
     
    6565        scale = 1 / (xmax - xmin);
    6666        node["shaderName"] = "unlit_textured";
    67         node["shader"] = gl["shaders"][node["shaderName"]]["program"];
     67        node["shader"] = gl["shaders"][node["shaderName"]];
    6868        node["scale"] = [scale, scale, scale * matrixscale];
    6969        node["translation"] = [(xmin + xmax) / (-2 / scale), (ymin + ymax) / (-2 / scale), (zmin + zmax) / (2 / scale)];
     
    101101                                datadelta = datamax - datamin;
    102102
    103                                 vertices.itemSize = 3;
    104                                 texcoords.itemSize = 2;
    105                                
    106103                                var xyz = vec3.create();
    107104                                var direction = vec3.create();
     
    109106                                var magnitude;
    110107
    111                                 for(var i = 0; i < x.length; i++){
     108                                for(var i = 0, vindex = 0, tindex = 0; i < x.length; i++){
    112109                                        //Check for NaN values and remove from indices array as necessary, but preserve vertex array spacing
    113110                                        if (isNaN(x[i]) || isNaN(y[i]) || isNaN(z[i]) || isNaN(data[i])) {
    114111                                                nanindices[i] = i;
    115                                                 vertices[vertices.length] = vertex[0];
    116                                                 vertices[vertices.length] = vertex[1];
    117                                                 vertices[vertices.length] = vertex[2];
     112                                                vertices[vindex++] = vertex[0];
     113                                                vertices[vindex++] = vertex[1];
     114                                                vertices[vindex++] = vertex[2];
    118115                                               
    119                                                 texcoords[texcoords.length] = 0.0;
    120                                                 texcoords[texcoords.length] = 0.0;
     116                                                texcoords[tindex++] = 0.0;
     117                                                texcoords[tindex++] = 0.0;
    121118                                                continue;
    122119                                        }
     
    126123                                        vec3.normalize(direction, xyz);
    127124                                        vec3.scale(vertex, direction, magnitude);
    128                                         vertices[vertices.length] = vertex[0];
    129                                         vertices[vertices.length] = vertex[1];
    130                                         vertices[vertices.length] = vertex[2];
    131 
    132                                         texcoords[texcoords.length] = 0.5;
    133                                         texcoords[texcoords.length] = (data[i] - datamin) / datadelta;
     125                                        vertices[vindex++] = vertex[0];
     126                                        vertices[vindex++] = vertex[1];
     127                                        vertices[vindex++] = vertex[2];
     128
     129                                        texcoords[tindex++] = 0.5;
     130                                        texcoords[tindex++] = (data[i] - datamin) / datadelta;
    134131                                }
    135132
    136133                                //linearize the elements array:
    137134                                var element;
    138                                 for(var i = 0; i < elements.length; i++){
     135                                for(var i = 0, iindex = 0; i < elements.length; i++){
    139136                                        element = [elements[i][0] - 1, elements[i][1] - 1, elements[i][2] - 1];
    140137                                        if (element[0] in nanindices || element[1] in nanindices || element[2] in nanindices) continue;
    141                                         indices[indices.length] = element[0];
    142                                         indices[indices.length] = element[1];
    143                                         indices[indices.length] = element[2];
    144                                 }
    145                                 indices.itemSize = 1;
    146 
    147                         }
    148                
    149                         //Initalize buffers
    150                         node["arrays"] = [vertices, texcoords, indices];
    151                         node["buffers"] = initBuffers(gl,node["arrays"]);
     138                                        indices[iindex++] = element[0];
     139                                        indices[iindex++] = element[1];
     140                                        indices[iindex++] = element[2];
     141                                }
     142                        }
     143                        node["mesh"] = GL.Mesh.load({vertices:vertices, coords:texcoords, indices:indices});
    152144                        break;
    153145                //}}}
     
    169161                        }
    170162                        else{ //triangular elements
    171                                 vertices.itemSize = 3;
    172                                
    173163                                var xyz = vec3.create();
    174164                                var direction = vec3.create();
     
    176166                                var magnitude;
    177167                                var timestamps = data[data.length-1];
    178                                 for(var i = 0; i < x.length; i++){
     168                                for(var i = 0, vindex = 0, tindex = 0; i < x.length; i++){
    179169                                        //Check for NaN values and remove from indices array as necessary, but preserve vertex array spacing
    180170                                        if (isNaN(x[i]) || isNaN(y[i]) || isNaN(z[i]) || isNaN(data[i][0])) {
    181171                                                nanindices[i] = i;
    182                                                 vertices[vertices.length] = vertex[0];
    183                                                 vertices[vertices.length] = vertex[1];
    184                                                 vertices[vertices.length] = vertex[2];
    185                                                
    186                                                 texcoords[texcoords.length] = 0.0;
    187                                                 texcoords[texcoords.length] = 0.0;
    188                                                 continue;
    189                                         }
    190                                         //Scale vertices
    191                                         xyz = vec3.fromValues(x[i], y[i], z[i]);
    192                                         magnitude = vec3.length(xyz) + md.geometry.surface[i] * vertexscale;
    193                                         vec3.normalize(direction, xyz);
    194                                         vec3.scale(vertex, direction, magnitude);
    195                                         vertices[vertices.length] = vertex[0];
    196                                         vertices[vertices.length] = vertex[1];
    197                                         vertices[vertices.length] = vertex[2];
     172                                        }
     173                                        else {
     174                                                //Scale vertices
     175                                                xyz = vec3.fromValues(x[i], y[i], z[i]);
     176                                                magnitude = vec3.length(xyz) + md.geometry.surface[i] * vertexscale;
     177                                                vec3.normalize(direction, xyz);
     178                                                vec3.scale(vertex, direction, magnitude);
     179                                        }
     180                                        vertices[vindex++] = vertex[0];
     181                                        vertices[vindex++] = vertex[1];
     182                                        vertices[vindex++] = vertex[2];
    198183                                }       
    199184                                //Transpose data to obtain column addressable data matrix
     
    204189                                });
    205190                                //Prevent evaluation of datasubarray min/max if caxis exists
    206                                 if (options.exist('caxis')) {
    207                                         caxis = options.getfieldvalue('caxis');
    208                                 }
    209                                 else {
    210                                         caxis = [ArrayMin(data[0]),ArrayMax(data[0].slice(0,-1))];
    211                                 }
     191                                if (options.exist('caxis')) caxis = options.getfieldvalue('caxis');
     192                                else caxis = [ArrayMin(data[0]),ArrayMax(data[0].slice(0,-1))];
    212193                                if (options.getfieldvalue('log','off')!='off') caxis = [Math.log10(caxis[0])/Math.log10(options.getfieldvalue('log',10)),Math.log10(caxis[1])/Math.log10(options.getfieldvalue('log',10))];
    213                                
     194                                //Prepare texcoords to hold array of data values
     195                                texcoords = [];
    214196                                for(var i = 0; i < data.length; i++){                                   
    215197                                        datamin = caxis[0];
    216198                                        datamax = caxis[1];
    217199                                        datadelta = datamax - datamin;
    218 
    219200                                        //Precalculate arrays for each datasubarray, trimming off timestamp value by using x.length instead of data[i].length
    220                                         texcoords[i] = [];
    221                                         texcoords[i].itemSize = 2;
    222                                         for(var j = 0; j < x.length; j++){
    223                                                 texcoords[i][texcoords[i].length] = 0.5;
    224                                                 texcoords[i][texcoords[i].length] = (data[i][j] - datamin) / datadelta;
     201                                        texcoords[i] = new Float32Array(x.length * 2);
     202                                        for(var j = 0, index = 0; j < x.length; j++){
     203                                                texcoords[i][index++] = 0.5;
     204                                                texcoords[i][index++] = (data[i][j] - datamin) / datadelta;
    225205                                        }
    226206                                }
     
    228208                                //linearize the elements array:
    229209                                var element;
    230                                 for(var i = 0; i < elements.length; i++){
     210                                for(var i = 0, iindex = 0; i < elements.length; i++){
    231211                                        element = [elements[i][0] - 1, elements[i][1] - 1, elements[i][2] - 1];
    232212                                        if (element[0] in nanindices || element[1] in nanindices || element[2] in nanindices) continue;
    233                                         indices[indices.length] = element[0];
    234                                         indices[indices.length] = element[1];
    235                                         indices[indices.length] = element[2];
    236                                 }
    237                                 indices.itemSize = 1;
     213                                        indices[iindex++] = element[0];
     214                                        indices[iindex++] = element[1];
     215                                        indices[iindex++] = element[2];
     216                                }
    238217                       
    239218                                //Initialize movie loop
     
    242221                                node["movieLength"] = timestamps.length;
    243222                                node["movieFrame"] = 0;
    244 
    245223                                if (canvas["movieHandler"])     clearInterval(canvas["movieHandler"]);
    246224                                canvas["movieHandler"] = setInterval(function () {
    247225                                                node["movieFrame"] = canvas["movieFrame"];
    248226                                                if (canvas["moviePlay"] && canvas["movieIncrement"]) {
    249                                                         if (canvas["movieReverse"]) {
    250                                                                 node["movieFrame"] = (((node["movieFrame"] - 1) % node["movieLength"]) + node["movieLength"]) % node["movieLength"]; //Handle negative modulus
    251                                                         }
    252                                                         else {
    253                                                                 node["movieFrame"] = (((node["movieFrame"] + 1) % node["movieLength"]) + node["movieLength"]) % node["movieLength"]; //Handle negative modulus
    254                                                         }
     227                                                        if (canvas["movieReverse"]) node["movieFrame"] = (((node["movieFrame"] - 1) % node["movieLength"]) + node["movieLength"]) % node["movieLength"]; //Handle negative modulus
     228                                                        else node["movieFrame"] = (((node["movieFrame"] + 1) % node["movieLength"]) + node["movieLength"]) % node["movieLength"]; //Handle negative modulus
    255229                                                }
    256                                                 if (canvas["timeLabel"]) {
    257                                                         canvas["timeLabel"].html(node["movieTimestamps"][node["movieFrame"]].toFixed(0) + " " + options.getfieldvalue("movietimeunit","yr"));
    258                                                 }
     230                                                if (canvas["timeLabel"]) canvas["timeLabel"].html(node["movieTimestamps"][node["movieFrame"]].toFixed(0) + " " + options.getfieldvalue("movietimeunit","yr"));
    259231                                                if (canvas["progressBar"]) {
    260232                                                        canvas["progressBar"].val(node["movieFrame"]);
    261233                                                        canvas["progressBar"].slider('refresh');
    262234                                                }
    263                                                 node["buffers"] = node["buffersArray"][node["movieFrame"]];
    264235                                                canvas["movieFrame"] = node["movieFrame"];
     236                                                var buffer = node["mesh"].getBuffer("coords");
     237                                                buffer.data = texcoords[node["movieFrame"]];
     238                                                buffer.upload(gl.DYNAMIC_DRAW);
    265239                                        }, node["movieInterval"]);
    266240                                if (canvas["progressBar"]) {
     
    271245                                }
    272246                        }
    273                        
    274                         //Initialize buffers
    275                         node["arrays"] = [vertices, texcoords, indices];
    276                         node["buffersArray"] = [];
    277                         for(var i = 0; i < timestamps.length; i++){
    278                                 node["buffersArray"][i] = initBuffers(gl,[node["arrays"][0],node["arrays"][1][i],node["arrays"][2]]);
    279                         }
    280                         node["buffers"] = node["buffersArray"][0];
     247                        node["mesh"] = GL.Mesh.load({vertices:vertices, coords:texcoords[0], indices:indices});
    281248                        break;
    282249                //}}}
  • issm/trunk-jpl/src/m/plot/webgl.js

    r20920 r21094  
    1515function initWebGL(canvas,options) { //{{{
    1616        var gl;
    17 
    1817        try {
    19                 // Try to grab the standard context. If it fails, fallback to experimental.
    20                 gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
    21         }
    22         catch(e) {}
    23 
    24         // If we don't have a GL context, give up now
    25         if (!gl) {
    26                 alert("Unable to initialize WebGL. Your browser may not support it.");
    27         }
    28                
     18                if (!canvas.gl) gl = GL.create({canvas:canvas});
     19                else gl = canvas.gl;
     20        }
     21        catch(e) {
     22                console.log(e);
     23                return;
     24        }
     25
    2926        // Enable depth testing
    3027        gl.enable(gl.DEPTH_TEST);
     
    3330        // Enable color blending/overlay
    3431        gl.enable(gl.BLEND);
    35 
    36         // Allocate arrays equal to maximium number of attributes used by any one shader
    37         gl.enableVertexAttribArray(0);
    38         gl.enableVertexAttribArray(1);
    3932
    4033        // Load shaders and store them in gl object
     
    8073        return gl;
    8174} //}}}
    82 function initBuffers(gl,arrays) { //{{{
    83         var bufferArray = [];
    84         for (var i = 0; i < arrays.length; i++) {
    85                 bufferArray[i] = gl.createBuffer();     
    86                 bufferArray[i].itemSize = arrays[i].itemSize;
    87                 bufferArray[i].numItems = arrays[i].length/bufferArray[i].itemSize;
    88                
    89                 if (bufferArray[i].itemSize > 1) {
    90                         gl.bindBuffer(gl.ARRAY_BUFFER, bufferArray[i]);
    91                         gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(arrays[i]), gl.STATIC_DRAW);
    92                 }
    93                 else {
    94                         //TODO: identify index buffers uniquely (by name)
    95                         gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bufferArray[i]);
    96                         gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(arrays[i]), gl.STATIC_DRAW);
    97                 }
    98         }       
    99         return bufferArray;
    100 } //}}}
    10175function initTexture(gl,imageSource) { //{{{
    102         var texture = gl.createTexture();
    103         texture.image = new Image();
    104         texture.isLoaded = false;
    105         texture.image.onload = function () {
    106                 handleLoadedTexture(gl,texture);
    107         }
    108         texture.image.src = imageSource;
    109         return texture;
    110 } //}}}
    111 function handleLoadedTexture(gl,texture) { //{{{
    112         gl.activeTexture(gl.TEXTURE0);
    113         gl.bindTexture(gl.TEXTURE_2D, texture);
    114         gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
    115         gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.image);
    116         gl.generateMipmap(gl.TEXTURE_2D);
    117         gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_LINEAR);
    118         gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
    119         gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    120         gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    121         gl.bindTexture(gl.TEXTURE_2D, null);
    122         texture.isLoaded = true;
     76        return GL.Texture.fromURL(imageSource, {minFilter:gl.LINEAR_MIPMAP_LINEAR, magFilter:gl.LINEAR});
    12377} //}}}
    12478function Node(gl,options) { //{{{
    12579        //Returns a Node object that contains default display states for webgl object
    12680        return {buffers:[],
    127                 shader:gl.shaders["colored"]["program"],
     81                shader:gl.shaders["colored"],
    12882                draw:null,
    12983                hideOcean:false,
     
    195149        shaders = {};
    196150        shaders["colored"] = {loaded:false, vsh:{}, fsh:{}};
    197         shaders["colored"]["vsh"]["string"] =
    198                 ['attribute vec3 aVertexPosition;',
    199                 'attribute vec4 aVertexColor;',
    200                 '',
    201                 'uniform mat4 uMVPMatrix;',
    202                 'uniform float uAlpha;',
    203                 '',
    204                 'varying vec4 vColor;',
    205                 '',
    206                 'void main(void) {',
    207                 '       gl_PointSize = 3.0;',
    208                 '       gl_Position = uMVPMatrix * vec4(aVertexPosition.xyz, 1.0);',
    209                 '       vColor = vec4(aVertexColor.xyz, uAlpha);',
    210                 '}'].join('\n');
    211         shaders["colored"]["fsh"]["string"] =
    212                 ['precision mediump float;',
    213                 '',
    214                 'varying vec4 vColor;',
    215                 '',
    216                 'void main(void) {',
    217                 '       gl_FragColor = vColor;',
    218                 '}'].join('\n');
    219         shaders["unlit_textured"] = {loaded:false, vsh:{}, fsh:{}};
    220         shaders["unlit_textured"]["vsh"]["string"] =
    221                 ['attribute vec3 aVertexPosition;',
    222                 'attribute vec2 aTextureCoord;',
    223                 '',
    224                 'uniform mat4 uMVPMatrix;',
    225                 '',
    226                 'varying vec2 vTextureCoord;',
    227                 'varying float vZCoord;',
    228                 '',
    229                 'void main(void) {',
    230                 '       gl_PointSize = 3.0;',
    231                 '       gl_Position = uMVPMatrix * vec4(aVertexPosition.xyz, 1.0);',
    232                 '       vTextureCoord = aTextureCoord;',
    233                 '       vZCoord = aVertexPosition.z;',
    234                 '}'].join('\n');
    235         shaders["unlit_textured"]["fsh"]["string"] =
    236                 ['precision mediump float;',
    237                 '',
    238                 'varying vec2 vTextureCoord;',
    239                 'varying float vZCoord;',
    240                 '',
    241                 'uniform sampler2D uColorSampler;',
    242                 'uniform float uAlpha;',
    243                 'uniform bool uMaskEnabled;',
    244                 'uniform float uMaskHeight;',
    245                 'uniform vec4 uMaskColor;',
    246                 '',
    247                 'void main(void) {',
    248                 '       if (uMaskEnabled && (vZCoord < uMaskHeight)) {',
    249                 '               gl_FragColor = vec4(uMaskColor.xyz, uAlpha);',
    250                 '       }',
    251                 '       else {',
    252                 '               gl_FragColor = vec4(texture2D(uColorSampler, vec2(vTextureCoord.s, vTextureCoord.t)).rgb, uAlpha);',
    253                 '       }',
    254                 '}'].join('\n');
    255         shaderNames.forEach(function(shaderName){
    256                 shaders[shaderName]["vsh"]["shader"] = getShaderByString(gl, shaders[shaderName]["vsh"]["string"], "vsh");
    257                 shaders[shaderName]["fsh"]["shader"] = getShaderByString(gl, shaders[shaderName]["fsh"]["string"], "fsh");
    258 
    259                 shaders[shaderName]["program"] = gl.createProgram();
    260                 gl.attachShader(shaders[shaderName]["program"], shaders[shaderName]["vsh"]["shader"]);
    261                 gl.attachShader(shaders[shaderName]["program"], shaders[shaderName]["fsh"]["shader"]);
    262                 gl.linkProgram(shaders[shaderName]["program"]);
    263 
    264                 if (!gl.getProgramParameter(shaders[shaderName]["program"], gl.LINK_STATUS)) {
    265                         alert("Could not initialise shaders");
    266                 }
    267 
    268                 var vshStringArray = shaders[shaderName]["vsh"]["string"].split("\n");
    269                 var fshStringArray = shaders[shaderName]["fsh"]["string"].split("\n");
    270                 var line = "";
    271                 var property = "";
    272                 for (var i = 0; i < vshStringArray.length; i++) {
    273                         line = vshStringArray[i];
    274                         if (line.search("attribute") != -1) {
    275                                 property = nameFromLine(line);
    276                                 shaders[shaderName]["program"][property] = gl.getAttribLocation(shaders[shaderName]["program"], property);
    277                         }
    278                         else if (line.search("uniform") != -1) {
    279                                 property = nameFromLine(line);
    280                                 shaders[shaderName]["program"][property] = gl.getUniformLocation(shaders[shaderName]["program"], property);
    281                         }
    282                         else if (line.search("void main") != -1) {
    283                                 break;
    284                         }
    285                 }
    286                 for (var i = 0; i < fshStringArray.length; i++) {
    287                         line = fshStringArray[i];
    288                         if (line.search("uniform") != -1) {
    289                                 property = nameFromLine(line);
    290                                 shaders[shaderName]["program"][property] = gl.getUniformLocation(shaders[shaderName]["program"], property);
    291                         }
    292                         else if (line.search("void main") != -1) {
    293                                 break;
    294                         }
    295                 }
    296                 shaders[shaderName]["loaded"] = true;
    297         });
     151                        //basic phong shader
     152        shaders["colored"] = new Shader('\
     153                precision highp float;\
     154                attribute vec3 a_vertex;\
     155                attribute vec4 a_color;\
     156                uniform mat4 u_mvp;\
     157                uniform float u_alpha;\
     158                varying vec4 v_color;\
     159                void main() {\
     160                        gl_PointSize = 3.0;\
     161                        gl_Position = u_mvp * vec4(a_vertex.xyz, 1.0);\
     162                        v_color = vec4(a_color.xyz, u_alpha);\
     163                }\
     164                ', '\
     165                precision mediump float;\
     166                varying vec4 v_color;\
     167                void main() {\
     168                        gl_FragColor = v_color;\
     169                }\
     170        ');
     171                       
     172        shaders["unlit_textured"] = new Shader('\
     173                precision highp float;\
     174                attribute vec3 a_vertex;\
     175                attribute vec2 a_coord;\
     176                uniform mat4 u_mvp;\
     177                varying vec2 v_coord;\
     178                varying float v_z;\
     179                void main() {\
     180                        gl_PointSize = 3.0;\
     181                        gl_Position = u_mvp * vec4(a_vertex.xyz, 1.0);\
     182                        v_coord = a_coord;\
     183                        v_z = a_vertex.z;\
     184                }\
     185                ', '\
     186                precision mediump float;\
     187                varying vec2 v_coord;\
     188                varying float v_z;\
     189                uniform sampler2D u_texture;\
     190                uniform float u_alpha;\
     191                uniform bool u_maskEnabled;\
     192                uniform float u_maskHeight;\
     193                uniform vec4 u_maskColor;\
     194                void main() {\
     195                        if (u_maskEnabled && (v_z < u_maskHeight)) {\
     196                                gl_FragColor = vec4(u_maskColor.rgb, u_alpha);\
     197                        }\
     198                        else {\
     199                                gl_FragColor = vec4(texture2D(u_texture, v_coord).rgb, u_alpha);\
     200                        }\
     201                }\
     202        ');
     203        /*
     204        shaders["phong"] = new Shader('\
     205                precision highp float;\
     206                attribute vec3 a_vertex;\
     207                attribute vec3 a_normal;\
     208                attribute vec2 a_coord;\
     209                varying vec3 v_normal;\
     210                varying vec2 v_coord;\
     211                uniform mat4 u_mvp;\
     212                uniform mat4 u_model;\
     213                void main() {\
     214                        v_coord = a_coord;\
     215                        v_normal = (u_model * vec4(a_normal,0.0)).xyz;\
     216                        gl_Position = u_mvp * vec4(a_vertex,1.0);\
     217                }\
     218                ', '\
     219                precision highp float;\
     220                varying vec3 v_normal;\
     221                varying vec2 v_coord;\
     222                uniform vec3 u_lightvector;\
     223                uniform vec4 u_color;\
     224                uniform sampler2D u_texture;\
     225                void main() {\
     226                  vec3 N = normalize(v_normal);\
     227                  vec4 color = u_color * texture2D( u_texture, v_coord);\
     228                  gl_FragColor = color * max(0.0, dot(u_lightvector,N));\
     229                }\
     230        ');
     231        */
    298232        return shaders;
    299233} //}}}
    300 function getShaderByString(gl,str,type) { //{{{
    301         var shader;
    302         if (type == "fsh") {
    303                 shader = gl.createShader(gl.FRAGMENT_SHADER);
    304         }
    305         else if (type == "vsh") {
    306                 shader = gl.createShader(gl.VERTEX_SHADER);
    307         }
    308         else {
    309                 return null;
    310         }
    311        
    312         gl.shaderSource(shader, str);
    313         gl.compileShader(shader);
    314 
    315         if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {       
    316                 alert(gl.getShaderInfoLog(shader));
    317                 return null;
    318         }
    319 
    320         return shader;
    321 } //}}}
    322 function nameFromLine(line) { //{{{
    323         //returns lowerCamelCase property name from shader line
    324         var fullName = line.split(" ")[2];
    325         return fullName.slice(0, fullName.search(";"));
    326 } //}}}
    327 //}}}
    328234//{{{ Interface Functions
    329235function onPan(ev,canvas,displaylog) { //{{{
     
    428334}//}}}
    429335function drawSceneGraphNode(canvas,node) { //{{{
    430         if (!node["enabled"]) {
    431                 return;
    432         }
    433         if (node["texture"]) {
    434                 if (!node["texture"]["isLoaded"]) {
    435                         return;
    436                 }
    437         }
    438         var gl = canvas.gl;
    439         bindAttributes(gl, node["shader"], node["buffers"]);
     336        if (!node["enabled"]) return;
     337       
    440338        var mvpMatrix = mat4.create();
    441339        mat4.multiply(mvpMatrix, canvas.cameraMatrix, node["modelMatrix"]);
    442         gl.uniformMatrix4fv(node["shader"]["uMVPMatrix"], false, mvpMatrix);
    443         gl.uniform1f(node["shader"]["uAlpha"], node["alpha"]);
    444         gl.uniform1i(node["shader"]["uMaskEnabled"], node["maskEnabled"]);
    445         gl.uniform1f(node["shader"]["uMaskHeight"], node["maskHeight"]);
    446         gl.uniform4fv(node["shader"]["uMaskColor"], node["maskColor"]);
    447         if (node["texture"]) {
    448                 gl.activeTexture(gl.TEXTURE0);
    449                 gl.bindTexture(gl.TEXTURE_2D, node["texture"]);
    450                 gl.uniform1i(node["shader"]["uColorSampler"], 0);       
    451         }
    452         if (node["disableDepthTest"]) {
    453                 gl.disable(gl.DEPTH_TEST);
    454         }
     340       
     341        if (node["texture"]) node["texture"].bind(0);
     342        if (node["disableDepthTest"]) gl.disable(gl.DEPTH_TEST);
     343       
    455344        gl.lineWidth(node["lineWidth"]);
    456         gl.blendFunc (gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
    457         if  (node["useIndexBuffer"] == true) {
    458                 gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, node["buffers"][node["buffers"].length - 1]);
    459                 gl.drawElements(node["drawMode"], node["buffers"][node["buffers"].length - 1].numItems, gl.UNSIGNED_SHORT, 0);
    460         }
    461         else {
    462                 gl.drawArrays(node["drawMode"], 0, node["buffers"][0].numItems);
    463         }       
     345        gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
     346
     347        node["shader"].uniforms({
     348                u_mvp: mvpMatrix,
     349                u_texture: 0,
     350                u_alpha: node["alpha"],
     351                u_maskEnabled: node["maskEnabled"],
     352                u_maskHeight: node["maskHeight"],
     353                u_maskColor: node["maskColor"]
     354        })
     355        if (node["useIndexBuffer"] == true) node["shader"].draw(node["mesh"], node["drawMode"], "indices");
     356        else node["shader"].draw(node["mesh"], node["drawMode"]);
     357
    464358        gl.enable(gl.DEPTH_TEST);
    465359} //}}}
    466 function bindAttributes(gl,shaderProgram,bufferArray) { //{{{
    467         gl.useProgram(shaderProgram);
    468         var arrayNumber = 0;
    469         for (var propertyName in shaderProgram) {
    470                 if (propertyName[0] == "a") {
    471                         if (bufferArray[arrayNumber].itemSize > 1) {
    472                                 gl.bindBuffer(gl.ARRAY_BUFFER, bufferArray[arrayNumber]);
    473                                 gl.vertexAttribPointer(shaderProgram[propertyName], bufferArray[arrayNumber].itemSize, gl.FLOAT, false, 0, 0);
    474                                 arrayNumber++;
    475                         }
    476                 }
    477         }
    478 } //}}}
    479360function draw(canvas,options) { //{{{
    480         if (canvas.nodes.length < 1) {
    481                 canvas.drawHandler = window.requestAnimationFrame(function(time) {draw(canvas,options)});
    482                 return;
    483         }
    484361        // Ensure canvas and gl viewport sizes are the same
    485362        var displayWidth  = canvas.clientWidth;
     
    493370        if (canvas.textcanvas) canvas.textcanvas.draw(canvas);
    494371
    495         var gl = canvas.gl;
    496         gl.clearColor(canvas.backgroundcolor[0], canvas.backgroundcolor[1], canvas.backgroundcolor[2], canvas.backgroundcolor[3]);
    497                
    498         // Skip drawing of new frame if any texture is not yet loaded
    499372        var nodes = canvas.nodes;
     373        if (nodes.length < 1) {
     374                canvas.drawHandler = window.requestAnimationFrame(function(time) {draw(canvas,options)});
     375                return;
     376        }
    500377        for (var node in nodes) {
    501                 if (nodes[node]["texture"] && !nodes[node]["texture"]["isLoaded"]) {
     378                if (nodes[node]["texture"] && nodes[node]["texture"]["ready"] == false) {
    502379                        canvas.drawHandler = window.requestAnimationFrame(function(time) {draw(canvas,options)});
    503380                        return;
    504381                }
    505382        }
    506         // Else, clear the color as well as the depth buffer for new frame
     383       
     384        var gl = canvas.gl;
     385        gl.clearColor(canvas.backgroundcolor[0], canvas.backgroundcolor[1], canvas.backgroundcolor[2], canvas.backgroundcolor[3]);
    507386        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
     387       
     388       
    508389       
    509390        updateCameraMatrix(canvas);
Note: See TracChangeset for help on using the changeset viewer.