<commit_before>// VVVV.js -- Visual Web Client Programming
// (c) 2011 Matthias Zauner
// VVVV.js is freely distributable under the MIT license.
// Additional authors of sub components are mentioned at the specific code locations.

var gl;
var defaultShaderAttributes = [ "PosO", "TexCd" ];
var defaultShaderUniforms = [ "tP", "tV" ];

VVVV.Types.VertexBuffer = function(position, texCoords) {

  this.positionBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(position), gl.STATIC_DRAW);

  this.texCoordBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texCoords), gl.STATIC_DRAW);

}

VVVV.Types.Mesh = function() {
  this.vertexBuffer = null;
  this.indexBuffer = null;
  this.numIndices = 0;
}

VVVV.Types.Layer = function() {
  this.mesh = null;
  this.textures = [];
  this.shaderProgram = null;
  this.uniforms = {};
  this.attributePositions = {};
  this.transform = mat4.create();
  mat4.identity(this.transform);

  this.toString = function() {
    return "Layer";
  }
}

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: FileTexture (EX9.Texture)
 Author(s): Matthias Zauner
 Original Node Author(s): VVVV Group
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.FileTexture = function(id, graph) {
  this.constructor(id, "FileTexture (EX9.Texture)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['VVVV Group'],
    credits: [],
    compatibility_issues: ['Always loads in background', 'No reload pin', 'No preload pin (preloading handled by browser)', 'No up and running pin', 'No texture info outputs']
  };

  this.auto_evaluate = true;

  this.filenamePin = this.addInputPin("Filename", [""], this);
  this.outputPin = this.addOutputPin("Texture Out", [], this);

  var textures = [];

  this.evaluate = function() {
    if (!gl)
      return;

    if (this.filenamePin.pinIsChanged()) {
      var maxSize = this.getMaxInputSliceCount();
      for (var i=0; i<maxSize; i++) {
        var filename = this.filenamePin.getValue(i);
        textures[i] = gl.createTexture();
        textures[i].image = new Image();
        textures[i].image.onload = (function(j) {
          return function() {  // this is to create a new scope within the loop. see "javascript closure in for loops" http://www.mennovanslooten.nl/blog/post/62
            gl.bindTexture(gl.TEXTURE_2D, textures[j]);
            //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textures[j].image);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
            gl.bindTexture(gl.TEXTURE_2D, null);
          }
        })(i);
        textures[i].image.src = filename;

        this.outputPin.setValue(i, textures[i]);
      }
    }

  }

}
VVVV.Nodes.FileTexture.prototype = new VVVV.Core.Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: Quad (DX9)
 Author(s): Matthias Zauner
 Original Node Author(s): VVVV Group
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.Quad = function(id, graph) {
  this.constructor(id, "Quad (DX9)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['VVVV Group'],
    credits: [],
    compatibility_issues: ['No Sampler States and Render States', 'No texture transform', 'No texture coord mapping', 'No enable pin']
  };

  this.auto_evaluate = true;

  this.addInputPin("Transform", [], this);
  this.addInputPin("Texture", [], this);
  this.addInputPin("Color", ["1.0, 1.0, 1.0, 1.0"], this);

  this.addOutputPin("Layer", [], this);

  var initialized = false;
  var layers = [];
  var mesh = null;
  var shaderProgram = null;

  this.evaluate = function() {

    if (!gl)
      return;

    if (!initialized) {

      var vertices = [
         0.5,  0.5,  0.0,
        -0.5,  0.5,  0.0,
         0.5, -0.5,  0.0,
        -0.5, -0.5,  0.0
      ];

      var texCoords = [
        1.0, 0.0,
        0.0, 0.0,
        1.0, 1.0,
        0.0, 1.0
      ];

      vertexBuffer = new VVVV.Types.VertexBuffer(vertices, texCoords);
      mesh = new VVVV.Types.Mesh();
      mesh.vertexBuffer = vertexBuffer;
      mesh.indexBuffer = gl.createBuffer();
      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, mesh.indexBuffer);
      gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint8Array([ 0, 1, 2, 1, 3, 2 ]), gl.STATIC_DRAW);
      mesh.numIndices = 6;

      // shaders

      var fragmentShaderCode = "#ifdef GL_ES\n";
      fragmentShaderCode += "precision highp float;\n";
      fragmentShaderCode += "#endif\n";
      fragmentShaderCode += "uniform vec4 col; uniform int useTexture; varying vec2 vs2psTexCd; uniform sampler2D Samp0; void main(void) { gl_FragColor = col; if (useTexture>0) gl_FragColor = gl_FragColor*texture2D(Samp0, vs2psTexCd);  }";
      var vertexShaderCode = "attribute vec3 PosO; attribute vec2 TexCd; uniform mat4 tW; uniform mat4 tV; uniform mat4 tP; varying vec2 vs2psTexCd; void main(void) { gl_Position = tP * tV * tW * vec4(PosO, 1.0); vs2psTexCd = TexCd; }";
      var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
      gl.shaderSource(fragmentShader, fragmentShaderCode);
      gl.compileShader(fragmentShader);

      if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
        alert(gl.getShaderInfoLog(fragmentShader));
      }
      var vertexShader = gl.createShader(gl.VERTEX_SHADER);
      gl.shaderSource(vertexShader, vertexShaderCode);
      gl.compileShader(vertexShader);

      if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
        alert(gl.getShaderInfoLog(vertexShader));
      }

      shaderProgram = gl.createProgram();
      gl.attachShader(shaderProgram, vertexShader);
      gl.attachShader(shaderProgram, fragmentShader);
      gl.linkProgram(shaderProgram);

      if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
        alert("Could not initialise shaders");
      }

	  var num = gl.getProgramParameter(shaderProgram,gl.ACTIVE_UNIFORMS);
	  for (var u = 0; u < num; u++)
	  {
		var inf = gl.getActiveUniform(shaderProgram,u);
	  }

      var maxSize = this.getMaxInputSliceCount();
      for (var j=0; j<maxSize; j++) {
        layers[j] = new VVVV.Types.Layer();
        layers[j].mesh = mesh;
        layers[j].shaderProgram = shaderProgram;

        for (var i=0; i<defaultShaderAttributes.length; i++) {
          layers[j].attributePositions[defaultShaderAttributes[i]] = gl.getAttribLocation(shaderProgram, defaultShaderAttributes[i]);
        }

        for (var i=0; i<defaultShaderUniforms.length; i++) {
          layers[j].uniforms[defaultShaderUniforms[i]] = { position: gl.getUniformLocation(shaderProgram, defaultShaderUniforms[i]), value: undefined };
        }
      }

    }

    var colorChanged = this.inputPins["Color"].pinIsChanged();
    var transformChanged = this.inputPins["Transform"].pinIsChanged();
    var textureChanged = this.inputPins["Texture"].pinIsChanged();

    var maxSize = this.getMaxInputSliceCount();

    if (colorChanged) {
      for (var i=0; i<maxSize; i++) {
        var color = this.inputPins["Color"].getValue(i);
        var rgba = _(color.split(',')).map(function(x) { return parseFloat(x) });
        layers[i].uniforms['col'] = { position: gl.getUniformLocation(shaderProgram, 'col'), value: new Float32Array(rgba), setter: 'gl.uniform4fv' };
      }
    }

    if (true) {
      for (var i=0; i<maxSize; i++) {
        var transform = this.inputPins["Transform"].getValue(i);
        if (transform!=undefined)
          layers[i].transform = transform;
        else
          mat4.identity(layers[i].transform);
        layers[i].uniforms['tW'] = { position: gl.getUniformLocation(shaderProgram, 'tW'), value: layers[i].transform, setter: 'gl.uniformMatrix4fv' };
      }
    }

    if (textureChanged) {
      for (var i=0; i<maxSize; i++) {
        console.log('setting texture for layer '+i);
        tex = this.inputPins["Texture"].getValue(i);
        if (tex!=undefined) {
          layers[i].textures[0] = { position: gl.getUniformLocation(shaderProgram, "Samp0"), texture: tex };
          layers[i].uniforms["useTexture"] = { position: gl.getUniformLocation(shaderProgram, 'useTexture'), value: 1, setter: 'gl.uniform1i' };
        }
        else
          layers[i].uniforms["useTexture"] = { position: gl.getUniformLocation(shaderProgram, 'useTexture'), value: 0, setter: 'gl.uniform1i' };
      }
    }

    for (var i=0; i<maxSize; i++) {
      this.outputPins["Layer"].setValue(i, layers[i]);
    }

    initialized = true;
  }

}
VVVV.Nodes.Quad.prototype = new VVVV.Core.Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: Renderer (EX9)
 Author(s): Matthias Zauner
 Original Node Author(s): VVVV Group
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.RendererWebGL = function(id, graph) {
  this.constructor(id, "Renderer (EX9)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['VVVV Group'],
    credits: [],
    compatibility_issues: ['No Clear Pin', 'No Background color pin', 'Backbuffer width and height defined by canvas size', 'No Fullscreen', 'No Enable Pin', 'No Aspect Ration and Viewport transform', 'No mouse output', 'No backbuffer dimesions output', 'No WebGL (EX9) Output Pin']
  };

  this.auto_evaluate = true;

  this.addInputPin("Layers", [], this);
  this.addInputPin("View Transform", [], this);
  this.addInputPin("Projection Transform", [], this);

  this.initialize = function() {
    if (!this.invisiblePins["Descriptive Name"])
      return;

    var selector = this.invisiblePins["Descriptive Name"].getValue(0);
    if (selector==undefined || selector=="")
      return;
    var canvas = $(selector);

    if (!canvas)
      return;

    try {
      gl = canvas.get(0).getContext("experimental-webgl");
      gl.viewportWidth = parseInt(canvas.get(0).width);
      gl.viewportHeight = parseInt(canvas.get(0).height);
    } catch (e) {
      console.log(e);
    }
    if (!gl) {
        alert("Oh gosh, can't initialize WebGL. If you're on Chrome, try launching like this: chrome.exe --ignore-gpu-blacklist . If you're on Firefox 4, go to page about:config and try to set webgl-force-enable to true.");
        return;
    }

    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    //gl.enable(gl.DEPTH_TEST);
    gl.enable(gl.BLEND);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
  }

  this.evaluate = function() {
    if (this.invisiblePins["Descriptive Name"].pinIsChanged()) {
      console.log('descriptive name chaaaanged');
      this.initialize();
    }

    if (gl==undefined)
      return;

    var layers = this.inputPins["Layers"].values;
    var pMatrix = this.inputPins["Projection Transform"].getValue(0);
    var vMatrix = this.inputPins["View Transform"].getValue(0);

    if (pMatrix==undefined) {
      pMatrix = mat4.create();
      mat4.ortho(-1, 1, -1, 1, -100, 100, pMatrix);
    }

    if (vMatrix==undefined) {
      vMatrix = mat4.create();
      mat4.identity(vMatrix);
    }

    gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    var currentShaderProgram = null;

    _(layers).each(function(layer) {
      if (currentShaderProgram!=layer.shaderProgram) {
        gl.useProgram(layer.shaderProgram);
        currentShaderProgram = layer.shaderProgram;
      }

      gl.enableVertexAttribArray(layer.attributePositions["PosO"]);
      gl.bindBuffer(gl.ARRAY_BUFFER, layer.mesh.vertexBuffer.positionBuffer);
      gl.vertexAttribPointer(layer.attributePositions["PosO"], 3, gl.FLOAT, false, 0, 0);

      gl.enableVertexAttribArray(layer.attributePositions["TexCd"]);
      gl.bindBuffer(gl.ARRAY_BUFFER, layer.mesh.vertexBuffer.texCoordBuffer);
      gl.vertexAttribPointer(layer.attributePositions["TexCd"], 2, gl.FLOAT, false, 0, 0);

      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, layer.mesh.indexBuffer);
      gl.uniformMatrix4fv(layer.uniforms["tP"].position, false, pMatrix);
      gl.uniformMatrix4fv(layer.uniforms["tV"].position, false, vMatrix);
      _(layer.uniforms).each(function(u) {
        if (u.value==undefined)
          return;
        switch (u.setter) {
          case "gl.uniformMatrix4fv": gl.uniformMatrix4fv(u.position, false, u.value); break;
          case "gl.uniform4fv": gl.uniform4fv(u.position, u.value); break;
          case "gl.uniform1i": gl.uniform1i(u.position, u.value); break;
        }
      });

      if (layer.textures.length>0) {
        var t = layer.textures[0];
        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, t.texture);
        gl.uniform1i(t.position, 0);
      }

      gl.drawElements(gl.TRIANGLES, layer.mesh.numIndices, gl.UNSIGNED_BYTE, 0);
    });

  }

}
VVVV.Nodes.RendererWebGL.prototype = new VVVV.Core.Node();<commit_msg>removes debug output<commit_after>// VVVV.js -- Visual Web Client Programming
// (c) 2011 Matthias Zauner
// VVVV.js is freely distributable under the MIT license.
// Additional authors of sub components are mentioned at the specific code locations.

var gl;
var defaultShaderAttributes = [ "PosO", "TexCd" ];
var defaultShaderUniforms = [ "tP", "tV" ];

VVVV.Types.VertexBuffer = function(position, texCoords) {

  this.positionBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(position), gl.STATIC_DRAW);

  this.texCoordBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texCoords), gl.STATIC_DRAW);

}

VVVV.Types.Mesh = function() {
  this.vertexBuffer = null;
  this.indexBuffer = null;
  this.numIndices = 0;
}

VVVV.Types.Layer = function() {
  this.mesh = null;
  this.textures = [];
  this.shaderProgram = null;
  this.uniforms = {};
  this.attributePositions = {};
  this.transform = mat4.create();
  mat4.identity(this.transform);

  this.toString = function() {
    return "Layer";
  }
}

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: FileTexture (EX9.Texture)
 Author(s): Matthias Zauner
 Original Node Author(s): VVVV Group
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.FileTexture = function(id, graph) {
  this.constructor(id, "FileTexture (EX9.Texture)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['VVVV Group'],
    credits: [],
    compatibility_issues: ['Always loads in background', 'No reload pin', 'No preload pin (preloading handled by browser)', 'No up and running pin', 'No texture info outputs']
  };

  this.auto_evaluate = true;

  this.filenamePin = this.addInputPin("Filename", [""], this);
  this.outputPin = this.addOutputPin("Texture Out", [], this);

  var textures = [];

  this.evaluate = function() {
    if (!gl)
      return;

    if (this.filenamePin.pinIsChanged()) {
      var maxSize = this.getMaxInputSliceCount();
      for (var i=0; i<maxSize; i++) {
        var filename = this.filenamePin.getValue(i);
        textures[i] = gl.createTexture();
        textures[i].image = new Image();
        textures[i].image.onload = (function(j) {
          return function() {  // this is to create a new scope within the loop. see "javascript closure in for loops" http://www.mennovanslooten.nl/blog/post/62
            gl.bindTexture(gl.TEXTURE_2D, textures[j]);
            //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textures[j].image);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
            gl.bindTexture(gl.TEXTURE_2D, null);
          }
        })(i);
        textures[i].image.src = filename;

        this.outputPin.setValue(i, textures[i]);
      }
    }

  }

}
VVVV.Nodes.FileTexture.prototype = new VVVV.Core.Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: Quad (DX9)
 Author(s): Matthias Zauner
 Original Node Author(s): VVVV Group
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.Quad = function(id, graph) {
  this.constructor(id, "Quad (DX9)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['VVVV Group'],
    credits: [],
    compatibility_issues: ['No Sampler States and Render States', 'No texture transform', 'No texture coord mapping', 'No enable pin']
  };

  this.auto_evaluate = true;

  this.addInputPin("Transform", [], this);
  this.addInputPin("Texture", [], this);
  this.addInputPin("Color", ["1.0, 1.0, 1.0, 1.0"], this);

  this.addOutputPin("Layer", [], this);

  var initialized = false;
  var layers = [];
  var mesh = null;
  var shaderProgram = null;

  this.evaluate = function() {

    if (!gl)
      return;

    if (!initialized) {

      var vertices = [
         0.5,  0.5,  0.0,
        -0.5,  0.5,  0.0,
         0.5, -0.5,  0.0,
        -0.5, -0.5,  0.0
      ];

      var texCoords = [
        1.0, 0.0,
        0.0, 0.0,
        1.0, 1.0,
        0.0, 1.0
      ];

      vertexBuffer = new VVVV.Types.VertexBuffer(vertices, texCoords);
      mesh = new VVVV.Types.Mesh();
      mesh.vertexBuffer = vertexBuffer;
      mesh.indexBuffer = gl.createBuffer();
      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, mesh.indexBuffer);
      gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint8Array([ 0, 1, 2, 1, 3, 2 ]), gl.STATIC_DRAW);
      mesh.numIndices = 6;

      // shaders

      var fragmentShaderCode = "#ifdef GL_ES\n";
      fragmentShaderCode += "precision highp float;\n";
      fragmentShaderCode += "#endif\n";
      fragmentShaderCode += "uniform vec4 col; uniform int useTexture; varying vec2 vs2psTexCd; uniform sampler2D Samp0; void main(void) { gl_FragColor = col; if (useTexture>0) gl_FragColor = gl_FragColor*texture2D(Samp0, vs2psTexCd);  }";
      var vertexShaderCode = "attribute vec3 PosO; attribute vec2 TexCd; uniform mat4 tW; uniform mat4 tV; uniform mat4 tP; varying vec2 vs2psTexCd; void main(void) { gl_Position = tP * tV * tW * vec4(PosO, 1.0); vs2psTexCd = TexCd; }";
      var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
      gl.shaderSource(fragmentShader, fragmentShaderCode);
      gl.compileShader(fragmentShader);

      if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
        alert(gl.getShaderInfoLog(fragmentShader));
      }
      var vertexShader = gl.createShader(gl.VERTEX_SHADER);
      gl.shaderSource(vertexShader, vertexShaderCode);
      gl.compileShader(vertexShader);

      if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
        alert(gl.getShaderInfoLog(vertexShader));
      }

      shaderProgram = gl.createProgram();
      gl.attachShader(shaderProgram, vertexShader);
      gl.attachShader(shaderProgram, fragmentShader);
      gl.linkProgram(shaderProgram);

      if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
        alert("Could not initialise shaders");
      }

	  var num = gl.getProgramParameter(shaderProgram,gl.ACTIVE_UNIFORMS);
	  for (var u = 0; u < num; u++)
	  {
		var inf = gl.getActiveUniform(shaderProgram,u);
	  }

      var maxSize = this.getMaxInputSliceCount();
      for (var j=0; j<maxSize; j++) {
        layers[j] = new VVVV.Types.Layer();
        layers[j].mesh = mesh;
        layers[j].shaderProgram = shaderProgram;

        for (var i=0; i<defaultShaderAttributes.length; i++) {
          layers[j].attributePositions[defaultShaderAttributes[i]] = gl.getAttribLocation(shaderProgram, defaultShaderAttributes[i]);
        }

        for (var i=0; i<defaultShaderUniforms.length; i++) {
          layers[j].uniforms[defaultShaderUniforms[i]] = { position: gl.getUniformLocation(shaderProgram, defaultShaderUniforms[i]), value: undefined };
        }
      }

    }

    var colorChanged = this.inputPins["Color"].pinIsChanged();
    var transformChanged = this.inputPins["Transform"].pinIsChanged();
    var textureChanged = this.inputPins["Texture"].pinIsChanged();

    var maxSize = this.getMaxInputSliceCount();

    if (colorChanged) {
      for (var i=0; i<maxSize; i++) {
        var color = this.inputPins["Color"].getValue(i);
        var rgba = _(color.split(',')).map(function(x) { return parseFloat(x) });
        layers[i].uniforms['col'] = { position: gl.getUniformLocation(shaderProgram, 'col'), value: new Float32Array(rgba), setter: 'gl.uniform4fv' };
      }
    }

    if (true) {
      for (var i=0; i<maxSize; i++) {
        var transform = this.inputPins["Transform"].getValue(i);
        if (transform!=undefined)
          layers[i].transform = transform;
        else
          mat4.identity(layers[i].transform);
        layers[i].uniforms['tW'] = { position: gl.getUniformLocation(shaderProgram, 'tW'), value: layers[i].transform, setter: 'gl.uniformMatrix4fv' };
      }
    }

    if (textureChanged) {
      for (var i=0; i<maxSize; i++) {
        console.log('setting texture for layer '+i);
        tex = this.inputPins["Texture"].getValue(i);
        if (tex!=undefined) {
          layers[i].textures[0] = { position: gl.getUniformLocation(shaderProgram, "Samp0"), texture: tex };
          layers[i].uniforms["useTexture"] = { position: gl.getUniformLocation(shaderProgram, 'useTexture'), value: 1, setter: 'gl.uniform1i' };
        }
        else
          layers[i].uniforms["useTexture"] = { position: gl.getUniformLocation(shaderProgram, 'useTexture'), value: 0, setter: 'gl.uniform1i' };
      }
    }

    for (var i=0; i<maxSize; i++) {
      this.outputPins["Layer"].setValue(i, layers[i]);
    }

    initialized = true;
  }

}
VVVV.Nodes.Quad.prototype = new VVVV.Core.Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: Renderer (EX9)
 Author(s): Matthias Zauner
 Original Node Author(s): VVVV Group
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.RendererWebGL = function(id, graph) {
  this.constructor(id, "Renderer (EX9)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['VVVV Group'],
    credits: [],
    compatibility_issues: ['No Clear Pin', 'No Background color pin', 'Backbuffer width and height defined by canvas size', 'No Fullscreen', 'No Enable Pin', 'No Aspect Ration and Viewport transform', 'No mouse output', 'No backbuffer dimesions output', 'No WebGL (EX9) Output Pin']
  };

  this.auto_evaluate = true;

  this.addInputPin("Layers", [], this);
  this.addInputPin("View Transform", [], this);
  this.addInputPin("Projection Transform", [], this);

  this.initialize = function() {
    if (!this.invisiblePins["Descriptive Name"])
      return;

    var selector = this.invisiblePins["Descriptive Name"].getValue(0);
    if (selector==undefined || selector=="")
      return;
    var canvas = $(selector);

    if (!canvas)
      return;

    try {
      gl = canvas.get(0).getContext("experimental-webgl");
      gl.viewportWidth = parseInt(canvas.get(0).width);
      gl.viewportHeight = parseInt(canvas.get(0).height);
    } catch (e) {
      console.log(e);
    }
    if (!gl) {
        alert("Oh gosh, can't initialize WebGL. If you're on Chrome, try launching like this: chrome.exe --ignore-gpu-blacklist . If you're on Firefox 4, go to page about:config and try to set webgl-force-enable to true.");
        return;
    }

    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    //gl.enable(gl.DEPTH_TEST);
    gl.enable(gl.BLEND);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
  }

  this.evaluate = function() {
    if (this.invisiblePins["Descriptive Name"].pinIsChanged()) {
      this.initialize();
    }

    if (gl==undefined)
      return;

    var layers = this.inputPins["Layers"].values;
    var pMatrix = this.inputPins["Projection Transform"].getValue(0);
    var vMatrix = this.inputPins["View Transform"].getValue(0);

    if (pMatrix==undefined) {
      pMatrix = mat4.create();
      mat4.ortho(-1, 1, -1, 1, -100, 100, pMatrix);
    }

    if (vMatrix==undefined) {
      vMatrix = mat4.create();
      mat4.identity(vMatrix);
    }

    gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    var currentShaderProgram = null;

    _(layers).each(function(layer) {
      if (currentShaderProgram!=layer.shaderProgram) {
        gl.useProgram(layer.shaderProgram);
        currentShaderProgram = layer.shaderProgram;
      }

      gl.enableVertexAttribArray(layer.attributePositions["PosO"]);
      gl.bindBuffer(gl.ARRAY_BUFFER, layer.mesh.vertexBuffer.positionBuffer);
      gl.vertexAttribPointer(layer.attributePositions["PosO"], 3, gl.FLOAT, false, 0, 0);

      gl.enableVertexAttribArray(layer.attributePositions["TexCd"]);
      gl.bindBuffer(gl.ARRAY_BUFFER, layer.mesh.vertexBuffer.texCoordBuffer);
      gl.vertexAttribPointer(layer.attributePositions["TexCd"], 2, gl.FLOAT, false, 0, 0);

      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, layer.mesh.indexBuffer);
      gl.uniformMatrix4fv(layer.uniforms["tP"].position, false, pMatrix);
      gl.uniformMatrix4fv(layer.uniforms["tV"].position, false, vMatrix);
      _(layer.uniforms).each(function(u) {
        if (u.value==undefined)
          return;
        switch (u.setter) {
          case "gl.uniformMatrix4fv": gl.uniformMatrix4fv(u.position, false, u.value); break;
          case "gl.uniform4fv": gl.uniform4fv(u.position, u.value); break;
          case "gl.uniform1i": gl.uniform1i(u.position, u.value); break;
        }
      });

      if (layer.textures.length>0) {
        var t = layer.textures[0];
        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, t.texture);
        gl.uniform1i(t.position, 0);
      }

      gl.drawElements(gl.TRIANGLES, layer.mesh.numIndices, gl.UNSIGNED_BYTE, 0);
    });

  }

}
VVVV.Nodes.RendererWebGL.prototype = new VVVV.Core.Node();<|endoftext|>


<commit_before>/* @flow */

import { TABLES, ROLES } from '../../lib/schema';
import { bus, cache } from '../../core-server';
import * as Constants from '../../lib/Constants';
import log from 'winston';
import User from '../../models/user';
import Counter from '../../lib/counter';
// import ThreadRel from '../../models/threadrel';
// import RoomRel from '../../models/roomrel';

bus.on('change', (changes, next) => {
	if (!changes.entities) {
		next();
		return;
	}
	const counter = new Counter();
	for (const id in changes.entities) {
		const entity = changes.entities[id];

		// 1. Increment children counts on parents
		if (
			entity.type === Constants.TYPE_TEXT ||
			entity.type === Constants.TYPE_THREAD
		) {
			if (!entity.createTime || entity.createTime !== entity.updateTime || (!entity.parents || !entity.parents.length)) {
				continue;
			}
			let inc;
			log.info('Count module reached: ', entity);
			if (entity.createTime === entity.updateTime) {
				log.info('increase count');
				inc = 1;
			} else if (entity.deleteTime) {
				inc = -1;
			}

			const parent = changes.entities[entity.parents[0]] || {};
			parent.counts = parent.counts || {};
			parent.counts.children = [ inc, '$add' ];

			parent.id = entity.parents[0];
			parent.type = (entity.type === Constants.TYPE_TEXT) ?
				Constants.TYPE_THREAD : Constants.TYPE_ROOM;

			// if (entity.type === Constants.TYPE_TEXT) {
			//
			// }
			// console.log('parents count module: ', parent);
			changes.entities[entity.parents[0]] = parent;

			// 2. Increment text/thread count of user

			const user = changes.entities[entity.creator] || new User({ id: entity.creator });

			user.counts = user.counts || {};
			user.counts[TABLES[entity.type]] = [ inc, '$add' ];
			user.id = entity.creator;
			changes.entities[entity.creator] = user;
		}

		 // 3. Increment related counts on items

		if (
			entity.type === Constants.TYPE_TEXTREL ||
			entity.type === Constants.TYPE_THREADREL ||
			entity.type === Constants.TYPE_ROOMREL ||
			entity.type === Constants.TYPE_PRIVREL ||
			entity.type === Constants.TYPE_TOPICREL
		) {
			if (!entity.id) entity.id = entity.user + '_' + entity.item;
			console.log('roomrel: , entity: ', entity);
			// if (entity.roles.length === 0) {
			// 	decrementCount(changes, entity);
			// 	continue;
			// }
			counter.inc();
			cache.getEntity(entity.id, (err, result) => {
				let exist = [], inc = 1;
				if (err) {
					counter.err(err);
					return;
				}
				console.log("result: ", result);
				if (result) {
					entity.roles.forEach((role) => {
						if (result.roles.indexOf(role) === -1) {
							exist.push(role);
						}
					});

					if (entity.roles.length === 0) {
						console.log('got roles empty');
						inc = -1;
						exist = result.roles;
					}

					if (exist.length === 0) {
						counter.dec();
						return;
					}
				} else {
					exist = entity.roles;
				}

				const item = changes.entities[entity.item] || {};

				item.counts = item.counts || {};
				// if (entity.__op__ && entity.__op__.role && entity.__op__.roles[0] === 'union') {
				// 	const rem = entity.__op__.roles[0].slice(1);
				//
				// 	rem.forEach((role) => {
				// 		if (ROLES[role]) {
				// 			item.counts[ROLES[role]] = -1;
				// 			item.counts.__op__[ROLES[role]] = 'inc';
				// 		}
				// 	});
				// }
				// console.log("exist: entity.roles: ", exist, entity.roles );
				exist.forEach((role) => {
					if (ROLES[role]) {
						item.counts[ROLES[role]] = [ inc, '$add' ];
					}
				});

				item.id = entity.item;

				switch (entity.type) {
				case Constants.TYPE_TEXTREL:
					item.type = Constants.TYPE_TEXT;
					break;
				case Constants.TYPE_THREADREL:
					item.type = Constants.TYPE_THREAD;
					break;
				case Constants.TYPE_ROOMREL:
					item.type = Constants.TYPE_ROOM;
					break;
				case Constants.TYPE_PRIVREL:
					item.type = Constants.TYPE_PRIV;
					break;
				case Constants.TYPE_TOPICREL:
					item.type = Constants.TYPE_TOPIC;
					break;
				}
				changes.entities[entity.item] = item;
				console.log("item count module: ", item);
				counter.dec();
			});
		}
	}
	counter.then(next);
}, Constants.APP_PRIORITIES.COUNT);
log.info('Count module ready.');
<commit_msg>remove console statements<commit_after>/* @flow */

import { TABLES, ROLES } from '../../lib/schema';
import { bus, cache } from '../../core-server';
import * as Constants from '../../lib/Constants';
import log from 'winston';
import User from '../../models/user';
import Counter from '../../lib/counter';
// import ThreadRel from '../../models/threadrel';
// import RoomRel from '../../models/roomrel';

bus.on('change', (changes, next) => {
	if (!changes.entities) {
		next();
		return;
	}
	const counter = new Counter();
	for (const id in changes.entities) {
		const entity = changes.entities[id];

		// 1. Increment children counts on parents
		if (
			entity.type === Constants.TYPE_TEXT ||
			entity.type === Constants.TYPE_THREAD
		) {
			if (!entity.createTime || entity.createTime !== entity.updateTime || (!entity.parents || !entity.parents.length)) {
				continue;
			}
			let inc;
			log.info('Count module reached: ', entity);
			if (entity.createTime === entity.updateTime) {
				log.info('increase count');
				inc = 1;
			} else if (entity.deleteTime) {
				inc = -1;
			}

			const parent = changes.entities[entity.parents[0]] || {};
			parent.counts = parent.counts || {};
			parent.counts.children = [ inc, '$add' ];

			parent.id = entity.parents[0];
			parent.type = (entity.type === Constants.TYPE_TEXT) ?
				Constants.TYPE_THREAD : Constants.TYPE_ROOM;

			// if (entity.type === Constants.TYPE_TEXT) {
			//
			// }
			// console.log('parents count module: ', parent);
			changes.entities[entity.parents[0]] = parent;

			// 2. Increment text/thread count of user

			const user = changes.entities[entity.creator] || new User({ id: entity.creator });

			user.counts = user.counts || {};
			user.counts[TABLES[entity.type]] = [ inc, '$add' ];
			user.id = entity.creator;
			changes.entities[entity.creator] = user;
		}

		 // 3. Increment related counts on items

		if (
			entity.type === Constants.TYPE_TEXTREL ||
			entity.type === Constants.TYPE_THREADREL ||
			entity.type === Constants.TYPE_ROOMREL ||
			entity.type === Constants.TYPE_PRIVREL ||
			entity.type === Constants.TYPE_TOPICREL
		) {
			if (!entity.id) entity.id = entity.user + '_' + entity.item;
			// console.log('roomrel: , entity: ', entity);
			// if (entity.roles.length === 0) {
			// 	decrementCount(changes, entity);
			// 	continue;
			// }
			counter.inc();
			cache.getEntity(entity.id, (err, result) => {
				let exist = [], inc = 1;
				if (err) {
					counter.err(err);
					return;
				}
				// console.log("result: ", result);
				if (result) {
					entity.roles.forEach((role) => {
						if (result.roles.indexOf(role) === -1) {
							exist.push(role);
						}
					});

					if (entity.roles.length === 0) {
						// console.log('got roles empty');
						inc = -1;
						exist = result.roles;
					}

					if (exist.length === 0) {
						counter.dec();
						return;
					}
				} else {
					exist = entity.roles;
				}

				const item = changes.entities[entity.item] || {};

				item.counts = item.counts || {};
				// if (entity.__op__ && entity.__op__.role && entity.__op__.roles[0] === 'union') {
				// 	const rem = entity.__op__.roles[0].slice(1);
				//
				// 	rem.forEach((role) => {
				// 		if (ROLES[role]) {
				// 			item.counts[ROLES[role]] = -1;
				// 			item.counts.__op__[ROLES[role]] = 'inc';
				// 		}
				// 	});
				// }
				// console.log("exist: entity.roles: ", exist, entity.roles );
				exist.forEach((role) => {
					if (ROLES[role]) {
						item.counts[ROLES[role]] = [ inc, '$add' ];
					}
				});

				item.id = entity.item;

				switch (entity.type) {
				case Constants.TYPE_TEXTREL:
					item.type = Constants.TYPE_TEXT;
					break;
				case Constants.TYPE_THREADREL:
					item.type = Constants.TYPE_THREAD;
					break;
				case Constants.TYPE_ROOMREL:
					item.type = Constants.TYPE_ROOM;
					break;
				case Constants.TYPE_PRIVREL:
					item.type = Constants.TYPE_PRIV;
					break;
				case Constants.TYPE_TOPICREL:
					item.type = Constants.TYPE_TOPIC;
					break;
				}
				changes.entities[entity.item] = item;
				console.log("item count module: ", item);
				counter.dec();
			});
		}
	}
	counter.then(next);
}, Constants.APP_PRIORITIES.COUNT);
log.info('Count module ready.');
<|endoftext|>


<commit_before>/* Beaconator js */
$(document).ready(function(){

	$option_area = $('#option_area');
	$new_options = $('#new_options');
	$add_option = $('#add_option');
	$beaconize = $('#beaconize');
	$reset = $('#reset');
	$results = $('#results');
	var num_options = 2;
	var options = [];

	// Hide results on page load
	$results.hide();

	// Adds a new option to the list
	$add_option.click(function(){

		// Increment counter
		num_options++;

		// Add preconfigured html to the page
		var opt = "
";
		opt +=       "Option " + num_options + "";
		opt +=       "
";
		opt +=         "<input type='text' id='Option" + num_options + "' class='form-control' />";
		opt +=		   "";
		opt +=		     "<input type='button' id='clear" + num_options + "' class='btn red inline clear_option' value='×' />";
		opt +=		   "";
		opt +=		 "
";
		opt +=    "
";
		$new_options.append(opt);
	});

	$(document).on('click', '.clear_option', clear);

	function clear(){

		var option_id = $(this).attr('id').value[5];

		// Clear the input value
		$("#Option" + option_id).val("");

		// Move every value below that id up one spot
		for(var i = option_id+1; i < num_options; i++){

			var input = $("#Option" + option_id).value;
			$("#Option" + (option_id-1)).val(input);
		}

		// Remove the last id

	};

	$beaconize.click(function(){

		// Clear out array
		options = [];

		// Parse options into array
		for(var i = 0; i < num_options; i++){

			var option_id = "#Option" + i;

			options.push($option_area.find(option_id).value);
		}

		// Read beacon API

		// Convert hex to decimal

		// Perform modulo

		// Display results

		$results.show();
	});

	$reset.click(function(){

		// Shut. Down. Everything.
		for(var i = 0; i < num_options; i++){

			// Reset all option values
			var option_id = "#Option" + i;
			$(option_id).val("");
		}

		// Reset options
		num_options = 2;
		options = [];

		// Clear out added options
		$new_options.empty();

		// Hide results
		$results.hide();
	});
});<commit_msg>Fixes document click structure for clear<commit_after>/* Beaconator js */
$(document).ready(function(){

	$option_area = $('#option_area');
	$new_options = $('#new_options');
	$add_option = $('#add_option');
	$beaconize = $('#beaconize');
	$reset = $('#reset');
	$results = $('#results');
	var num_options = 2;
	var options = [];

	// Hide results on page load
	$results.hide();

	// Adds a new option to the list
	$add_option.click(function(){

		// Increment counter
		num_options++;

		// Add preconfigured html to the page
		var opt = "
";
		opt +=       "Option " + num_options + "";
		opt +=       "
";
		opt +=         "<input type='text' id='Option" + num_options + "' class='form-control' />";
		opt +=		   "";
		opt +=		     "<input type='button' id='clear" + num_options + "' class='btn red inline clear_option' value='×' />";
		opt +=		   "";
		opt +=		 "
";
		opt +=    "
";
		$new_options.append(opt);
	});

	$(document).on('click', '.clear_option', function (sel){

		alert("chris sucks cause the id is: " sel.target.id);

		var option_id = $(this).attr('id').value[5];

		// Clear the input value
		$("#Option" + option_id).val("");

		// Move every value below that id up one spot
		for(var i = option_id+1; i < num_options; i++){

			var input = $("#Option" + option_id).value;
			$("#Option" + (option_id-1)).val(input);
		}

		// Remove the last id

	});

	$beaconize.click(function(){

		// Clear out array
		options = [];

		// Parse options into array
		for(var i = 0; i < num_options; i++){

			var option_id = "#Option" + i;

			options.push($option_area.find(option_id).value);
		}

		// Read beacon API

		// Convert hex to decimal

		// Perform modulo

		// Display results

		$results.show();
	});

	$reset.click(function(){

		// Shut. Down. Everything.
		for(var i = 0; i < num_options; i++){

			// Reset all option values
			var option_id = "#Option" + i;
			$(option_id).val("");
		}

		// Reset options
		num_options = 2;
		options = [];

		// Clear out added options
		$new_options.empty();

		// Hide results
		$results.hide();
	});
});<|endoftext|>


<commit_before>/*
 This page outputs information for the Space Api ( http://spaceapi.net/ ).
 Mostly static information, however the open state and the sensor properties are dynamic.

 http://spaceapi.net/specs/0.13
 */

'use strict';

var apiUtils = require(('./apiUtils.js'));

module.exports = function (app, data, config, srv) {

  function getPeopleSensor(state) {
    var value = {
      'value': state.spaceDevices.peopleCount
    };
    if (state.spaceDevices.people.length > 0) {
      value.names = state.spaceDevices.people.map(function (peopleObj) {
        return peopleObj.name;
      });
    }

    return [ value ];
  }

  app.namespace('/spaceInfo', function () {

    app.get('/', function (req, res) {

      var state = data.state.get();
      var openStatusPublic = {
        'on': 'Open!',
        'off': 'Closed!',
        'closing': 'We are closing...'
      };

      // https://github.com/slopjong/OpenSpaceLint/issues/80
      // [ 'N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW' ]
      var windDirectionTranslation = [0, 22.5, 45, 67.5, 90, 112.5, 135, 157.5, 180, 202.5, 225, 247.5, 270, 292.5, 315, 337.5 ];

      var currentStatus = {
        'api': '0.13',
        'space': 'Mainframe',
        'logo': 'http://status.mainframe.io/images/logo.png',
        'url': 'http://mainframe.io/',
        'location': {
          'address': 'Bahnhofsplatz 10, 26122 Oldenburg, Germany',
          'lat': 53.14495,
          'lon': 8.21516
        },
        'contact': {
          'irc': 'irc://freenode/#hsol',
          'twitter': '@HackspaceOL',
          'email': 'vorstand@kreativitaet-trifft-technik.de',
          'ml': 'diskussion@kreativitaet-trifft-technik.de',
          'issue_mail': 'hc@kreativitaet-trifft-technik.de'
        },
        'issue_report_channels': [ 'issue_mail'],
        'state': {
          'open': state.status.state === 'on',
          'lastchange': state.status.timestamp,
          'message': openStatusPublic[state.status.state],
          'icon': {
            'open': 'http://status.mainframe.io/images/open.png',
            'closed': 'http://status.mainframe.io/images/closed.png'
          }
        },
        'sensors': {
          'people_now_present': getPeopleSensor(state),
          'network_connections': [
            {
              'value': state.spaceDevices.deviceCount,
              'location': 'Inside'
            }
          ],
          'temperature': [
            {
              'location': 'Inside',
              'value': state.weather.Tin / 10,
              'unit': '°C'
            },
            {
              'location': 'Outside',
              'value': state.weather.Tout / 10,
              'unit': '°C'
            }
          ],

          'humidity': [
            {
              'location': 'Inside',
              'value': state.weather.Hin / 100,
              'unit': '%'
            },
            {
              'location': 'Outside',
              'value': state.weather.Hout / 100,
              'unit': '%'
            }
          ],

          'barometer': [
            {
              'location': 'Outside',
              'value': state.weather.P / 10,
              'unit': 'hPA'
            }
          ],

          'wind': [
            {
              'location': 'Outside',
              'properties': {
                'speed': {
                  'value': state.weather.Ws / 10,
                  'unit': 'm/s'
                },
                'gust': {
                  'value': state.weather.Ws / 10,
                  'unit': 'm/s'
                },
                'direction': {
                  'value': windDirectionTranslation[state.weather.Wd],
                  'unit': '\u00b0'
                },
                'elevation': {
                  // 7.701 m + the buildings roof (ca. 20m)
                  'value': 27,
                  'unit': 'm'
                }
              }
            }
          ]
        },
        'feeds': {
          'blog': {
            'type': 'application/rss+xml',
            'url': 'http://www.kreativitaet-trifft-technik.de/news.xml'
          },
          'calendar': {
            'type': 'application/calendar',
            'url': 'http://www.kreativitaet-trifft-technik.de/calendar/ical/2013-05/calendar.ics'
          }
        },
        'projects': [
          'https://github.com/ktt-ol/'
        ]
      };

      apiUtils.sendJson(res, 200, currentStatus);

    }); // end get
  });
};

<commit_msg>Updated space position (latitude and longitude)<commit_after>/*
 This page outputs information for the Space Api ( http://spaceapi.net/ ).
 Mostly static information, however the open state and the sensor properties are dynamic.

 http://spaceapi.net/specs/0.13
 */

'use strict';

var apiUtils = require(('./apiUtils.js'));

module.exports = function (app, data, config, srv) {

  function getPeopleSensor(state) {
    var value = {
      'value': state.spaceDevices.peopleCount
    };
    if (state.spaceDevices.people.length > 0) {
      value.names = state.spaceDevices.people.map(function (peopleObj) {
        return peopleObj.name;
      });
    }

    return [ value ];
  }

  app.namespace('/spaceInfo', function () {

    app.get('/', function (req, res) {

      var state = data.state.get();
      var openStatusPublic = {
        'on': 'Open!',
        'off': 'Closed!',
        'closing': 'We are closing...'
      };

      // https://github.com/slopjong/OpenSpaceLint/issues/80
      // [ 'N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW' ]
      var windDirectionTranslation = [0, 22.5, 45, 67.5, 90, 112.5, 135, 157.5, 180, 202.5, 225, 247.5, 270, 292.5, 315, 337.5 ];

      var currentStatus = {
        'api': '0.13',
        'space': 'Mainframe',
        'logo': 'http://status.mainframe.io/images/logo.png',
        'url': 'http://mainframe.io/',
        'location': {
          'address': 'Bahnhofsplatz 10, 26122 Oldenburg, Germany',
          'lat': 53.14402,
          'lon': 8.21988
        },
        'contact': {
          'irc': 'irc://freenode/#hsol',
          'twitter': '@HackspaceOL',
          'email': 'vorstand@kreativitaet-trifft-technik.de',
          'ml': 'diskussion@kreativitaet-trifft-technik.de',
          'issue_mail': 'hc@kreativitaet-trifft-technik.de'
        },
        'issue_report_channels': [ 'issue_mail'],
        'state': {
          'open': state.status.state === 'on',
          'lastchange': state.status.timestamp,
          'message': openStatusPublic[state.status.state],
          'icon': {
            'open': 'http://status.mainframe.io/images/open.png',
            'closed': 'http://status.mainframe.io/images/closed.png'
          }
        },
        'sensors': {
          'people_now_present': getPeopleSensor(state),
          'network_connections': [
            {
              'value': state.spaceDevices.deviceCount,
              'location': 'Inside'
            }
          ],
          'temperature': [
            {
              'location': 'Inside',
              'value': state.weather.Tin / 10,
              'unit': '°C'
            },
            {
              'location': 'Outside',
              'value': state.weather.Tout / 10,
              'unit': '°C'
            }
          ],

          'humidity': [
            {
              'location': 'Inside',
              'value': state.weather.Hin / 100,
              'unit': '%'
            },
            {
              'location': 'Outside',
              'value': state.weather.Hout / 100,
              'unit': '%'
            }
          ],

          'barometer': [
            {
              'location': 'Outside',
              'value': state.weather.P / 10,
              'unit': 'hPA'
            }
          ],

          'wind': [
            {
              'location': 'Outside',
              'properties': {
                'speed': {
                  'value': state.weather.Ws / 10,
                  'unit': 'm/s'
                },
                'gust': {
                  'value': state.weather.Ws / 10,
                  'unit': 'm/s'
                },
                'direction': {
                  'value': windDirectionTranslation[state.weather.Wd],
                  'unit': '\u00b0'
                },
                'elevation': {
                  // 7.701 m + the buildings roof (ca. 20m)
                  'value': 27,
                  'unit': 'm'
                }
              }
            }
          ]
        },
        'feeds': {
          'blog': {
            'type': 'application/rss+xml',
            'url': 'http://www.kreativitaet-trifft-technik.de/news.xml'
          },
          'calendar': {
            'type': 'application/calendar',
            'url': 'http://www.kreativitaet-trifft-technik.de/calendar/ical/2013-05/calendar.ics'
          }
        },
        'projects': [
          'https://github.com/ktt-ol/'
        ]
      };

      apiUtils.sendJson(res, 200, currentStatus);

    }); // end get
  });
};

<|endoftext|>


<commit_before>Ext.namespace('Ext.Gemma');

/* Ext.Gemma.PagingDataStore constructor...
 * 	ds is the backing data store
 * 	config is a hash with the following options:
 * 		...
 */
Ext.Gemma.PagingDataStore = function ( config ) {

	this.currentStartIndex = 0;
	this.pageSize = 10;
	if ( config && config.pageSize ) {
		this.pageSize = config.pageSize;
		delete config.pageSize;
	}

	Ext.Gemma.PagingDataStore.superclass.constructor.call( this, config );
};

Ext.extend( Ext.Gemma.PagingDataStore, Ext.data.Store, {

	getAt : function ( index ) {
       return Ext.Gemma.PagingDataStore.superclass.getAt.call( this, this.currentStartIndex + index );
    },

    getRange : function ( start, end ) {
	   	var windowStart = this.currentStartIndex + start;
    	var windowEnd = this.currentStartIndex + end;
		if ( windowEnd > this.currentStartIndex + this.pageSize - 1 )
   			windowEnd = this.currentStartIndex + this.pageSize - 1;
		return Ext.Gemma.PagingDataStore.superclass.getRange.call( this, windowStart, windowEnd );
    },

    indexOf : function ( record ) {
        var i = this.data.indexOf(record);
        return i - this.currentStartIndex;
    },

    indexOfId : function ( id ) {
        var i = this.data.indexOfKey(id);
        return i - this.currentStartIndex;
    },

    load : function ( options ) {
		options = options || {};
		if ( options.params.start !== undefined || options.params.limit !== undefined ) {
			if ( this.fireEvent( "beforeload", this, options ) !== false ) {
				if ( options.params.start !== undefined )
					this.currentStartIndex = options.params.start;
				if ( options.params.limit !== undefined )
					this.pageSize = options.params.limit;
				var total = this.getTotalCount();
				var records = this.getVisibleRecords();
				this.fireEvent( "datachanged", this );
				this.fireEvent( "load", this, records, options );
			}
		} else {
			this.currentStartIndex = 0;
			Ext.Gemma.PagingDataStore.superclass.load.call( this, options );
		}
    },

    getVisibleRecords : function () {
    	return this.getRange( 0, this.pageSize - 1 );
    }

} );<commit_msg>Fixed documentation.<commit_after>Ext.namespace('Ext.Gemma');

/* Ext.Gemma.PagingDataStore constructor...
 * 	ds is the backing data store
 * 	config is a hash with the following options:
 * 		pageSize is the number of rows to show on each page.
 */
Ext.Gemma.PagingDataStore = function ( config ) {

	this.currentStartIndex = 0;
	this.pageSize = 10;
	if ( config && config.pageSize ) {
		this.pageSize = config.pageSize;
		delete config.pageSize;
	}

	Ext.Gemma.PagingDataStore.superclass.constructor.call( this, config );
};

Ext.extend( Ext.Gemma.PagingDataStore, Ext.data.Store, {

	getAt : function ( index ) {
       return Ext.Gemma.PagingDataStore.superclass.getAt.call( this, this.currentStartIndex + index );
    },

    getRange : function ( start, end ) {
	   	var windowStart = this.currentStartIndex + start;
    	var windowEnd = this.currentStartIndex + end;
		if ( windowEnd > this.currentStartIndex + this.pageSize - 1 )
   			windowEnd = this.currentStartIndex + this.pageSize - 1;
		return Ext.Gemma.PagingDataStore.superclass.getRange.call( this, windowStart, windowEnd );
    },

    indexOf : function ( record ) {
        var i = this.data.indexOf(record);
        return i - this.currentStartIndex;
    },

    indexOfId : function ( id ) {
        var i = this.data.indexOfKey(id);
        return i - this.currentStartIndex;
    },

    load : function ( options ) {
		options = options || {};
		if ( options.params.start !== undefined || options.params.limit !== undefined ) {
			if ( this.fireEvent( "beforeload", this, options ) !== false ) {
				if ( options.params.start !== undefined )
					this.currentStartIndex = options.params.start;
				if ( options.params.limit !== undefined )
					this.pageSize = options.params.limit;
				var total = this.getTotalCount();
				var records = this.getVisibleRecords();
				this.fireEvent( "datachanged", this );
				this.fireEvent( "load", this, records, options );
			}
		} else {
			this.currentStartIndex = 0;
			Ext.Gemma.PagingDataStore.superclass.load.call( this, options );
		}
    },

    getVisibleRecords : function () {
    	return this.getRange( 0, this.pageSize - 1 );
    }

} );<|endoftext|>


<commit_before>suite('LengthValue', function() {
  test('fromDictionary returns instanceof a LengthValue and StyleValue', function() {
    var fromDictionary = (new LengthValue()).fromDictionary(9.2, 'px');
    assert.instanceOf(fromDictionary, SimpleLength, 'A new fromDictionary should be an instance of SimpleLength');
    assert.instanceOf(fromDictionary, LengthValue, 'A new fromDictionary should be an instance of LengthValue');
    assert.instanceOf(fromDictionary, StyleValue, 'A new fromDictionary should be an instance of StyleValue');
  });

  test('fromDictionary returns instanceof a LengthValue and StyleValue', function() {
    var fromDictionary = (new LengthValue()).fromDictionary({px: 10});
    assert.instanceOf(fromDictionary, CalcLength, 'A new fromDictionary should be an instance of CalcLength');
    assert.instanceOf(fromDictionary, LengthValue, 'A new fromDictionary should be an instance of LengthValue');
    assert.instanceOf(fromDictionary, StyleValue, 'A new fromDictionary should be an instance of StyleValue');
  });
});
<commit_msg>Fixed broken test case in length-value.js Last commit accedentaly changed a method witch broke a test in length-value.jsthis commit fixes this issue<commit_after>suite('LengthValue', function() {
  test('fromDictionary returns instanceof a LengthValue and StyleValue', function() {
    var fromDictionary = (new LengthValue()).fromValue(9.2, 'px');
    assert.instanceOf(fromDictionary, SimpleLength, 'A new fromDictionary should be an instance of SimpleLength');
    assert.instanceOf(fromDictionary, LengthValue, 'A new fromDictionary should be an instance of LengthValue');
    assert.instanceOf(fromDictionary, StyleValue, 'A new fromDictionary should be an instance of StyleValue');
  });

  test('fromDictionary returns instanceof a LengthValue and StyleValue', function() {
    var fromDictionary = (new LengthValue()).fromDictionary({px: 10});
    assert.instanceOf(fromDictionary, CalcLength, 'A new fromDictionary should be an instance of CalcLength');
    assert.instanceOf(fromDictionary, LengthValue, 'A new fromDictionary should be an instance of LengthValue');
    assert.instanceOf(fromDictionary, StyleValue, 'A new fromDictionary should be an instance of StyleValue');
  });
});
<|endoftext|>


<commit_before>/**
 * Copyright 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule ReactDOM
 */

/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/

'use strict';

var ReactDOMComponentTree = require('ReactDOMComponentTree');
var ReactDefaultInjection = require('ReactDefaultInjection');
var ReactMount = require('ReactMount');
var ReactReconciler = require('ReactReconciler');
var ReactUpdates = require('ReactUpdates');
var ReactVersion = require('ReactVersion');

var findDOMNode = require('findDOMNode');
var getHostComponentFromComposite = require('getHostComponentFromComposite');
var renderSubtreeIntoContainer = require('renderSubtreeIntoContainer');
var warning = require('warning');

ReactDefaultInjection.inject();

var ReactDOM = {
  findDOMNode: findDOMNode,
  render: ReactMount.render,
  unmountComponentAtNode: ReactMount.unmountComponentAtNode,
  version: ReactVersion,

  /* eslint-disable camelcase */
  unstable_batchedUpdates: ReactUpdates.batchedUpdates,
  unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer,
  /* eslint-enable camelcase */
};

// Inject the runtime into a devtools global hook regardless of browser.
// Allows for debugging when the hook is injected on the page.
if (
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
  __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
    ComponentTree: {
      getClosestInstanceFromNode:
        ReactDOMComponentTree.getClosestInstanceFromNode,
      getNodeFromInstance: function(inst) {
        // inst is an internal instance (but could be a composite)
        if (inst._renderedComponent) {
          inst = getHostComponentFromComposite(inst);
        }
        if (inst) {
          return ReactDOMComponentTree.getNodeFromInstance(inst);
        } else {
          return null;
        }
      },
    },
    Mount: ReactMount,
    Reconciler: ReactReconciler,
  });
}

if (__DEV__) {
  var ExecutionEnvironment = require('ExecutionEnvironment');
  if (ExecutionEnvironment.canUseDOM && window.top === window.self) {

    // First check if devtools is not installed
    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
      // If we're in Chrome or Firefox, provide a download link if not installed.
      if ((navigator.userAgent.indexOf('Chrome') > -1 &&
          navigator.userAgent.indexOf('Edge') === -1) ||
          navigator.userAgent.indexOf('Firefox') > -1) {
        // Firefox does not have the issue with devtools loaded over file://
        var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 &&
          navigator.userAgent.indexOf('Firefox') === -1;
        console.debug(
          'Download the React DevTools ' +
          (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') +
          'for a better development experience: ' +
          'https://fb.me/react-devtools'
        );
      }
    }

    var testFunc = function testFn() {};
    warning(
      (testFunc.name || testFunc.toString()).indexOf('testFn') !== -1,
      'It looks like you\'re using a minified copy of the development build ' +
      'of React. When deploying React apps to production, make sure to use ' +
      'the production build which skips development warnings and is faster. ' +
      'See https://fb.me/react-minification for more details.'
    );

    // If we're in IE8, check to see if we are in compatibility mode and provide
    // information on preventing compatibility mode
    var ieCompatibilityMode =
      document.documentMode && document.documentMode < 8;

    warning(
      !ieCompatibilityMode,
      'Internet Explorer is running in compatibility mode; please add the ' +
      'following tag to your HTML to prevent this from happening: ' +
      '<meta http-equiv="X-UA-Compatible" content="IE=edge" />'
    );

    var expectedFeatures = [
      // shims
      Array.isArray,
      Array.prototype.every,
      Array.prototype.forEach,
      Array.prototype.indexOf,
      Array.prototype.map,
      Date.now,
      Function.prototype.bind,
      Object.keys,
      String.prototype.split,
      String.prototype.trim,
    ];

    for (var i = 0; i < expectedFeatures.length; i++) {
      if (!expectedFeatures[i]) {
        warning(
          false,
          'One or more ES5 shims expected by React are not available: ' +
          'https://fb.me/react-warning-polyfills'
        );
        break;
      }
    }
  }
}

if (__DEV__) {
  var ReactInstrumentation = require('ReactInstrumentation');
  var ReactDOMUnknownPropertyHook = require('ReactDOMUnknownPropertyHook');
  var ReactDOMNullInputValuePropHook = require('ReactDOMNullInputValuePropHook');

  ReactInstrumentation.debugTool.addHook(ReactDOMUnknownPropertyHook);
  ReactInstrumentation.debugTool.addHook(ReactDOMNullInputValuePropHook);
}

module.exports = ReactDOM;
<commit_msg>Remove String.prototype.split polyfill warning (#7629)<commit_after>/**
 * Copyright 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule ReactDOM
 */

/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/

'use strict';

var ReactDOMComponentTree = require('ReactDOMComponentTree');
var ReactDefaultInjection = require('ReactDefaultInjection');
var ReactMount = require('ReactMount');
var ReactReconciler = require('ReactReconciler');
var ReactUpdates = require('ReactUpdates');
var ReactVersion = require('ReactVersion');

var findDOMNode = require('findDOMNode');
var getHostComponentFromComposite = require('getHostComponentFromComposite');
var renderSubtreeIntoContainer = require('renderSubtreeIntoContainer');
var warning = require('warning');

ReactDefaultInjection.inject();

var ReactDOM = {
  findDOMNode: findDOMNode,
  render: ReactMount.render,
  unmountComponentAtNode: ReactMount.unmountComponentAtNode,
  version: ReactVersion,

  /* eslint-disable camelcase */
  unstable_batchedUpdates: ReactUpdates.batchedUpdates,
  unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer,
  /* eslint-enable camelcase */
};

// Inject the runtime into a devtools global hook regardless of browser.
// Allows for debugging when the hook is injected on the page.
if (
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
  __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
    ComponentTree: {
      getClosestInstanceFromNode:
        ReactDOMComponentTree.getClosestInstanceFromNode,
      getNodeFromInstance: function(inst) {
        // inst is an internal instance (but could be a composite)
        if (inst._renderedComponent) {
          inst = getHostComponentFromComposite(inst);
        }
        if (inst) {
          return ReactDOMComponentTree.getNodeFromInstance(inst);
        } else {
          return null;
        }
      },
    },
    Mount: ReactMount,
    Reconciler: ReactReconciler,
  });
}

if (__DEV__) {
  var ExecutionEnvironment = require('ExecutionEnvironment');
  if (ExecutionEnvironment.canUseDOM && window.top === window.self) {

    // First check if devtools is not installed
    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
      // If we're in Chrome or Firefox, provide a download link if not installed.
      if ((navigator.userAgent.indexOf('Chrome') > -1 &&
          navigator.userAgent.indexOf('Edge') === -1) ||
          navigator.userAgent.indexOf('Firefox') > -1) {
        // Firefox does not have the issue with devtools loaded over file://
        var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 &&
          navigator.userAgent.indexOf('Firefox') === -1;
        console.debug(
          'Download the React DevTools ' +
          (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') +
          'for a better development experience: ' +
          'https://fb.me/react-devtools'
        );
      }
    }

    var testFunc = function testFn() {};
    warning(
      (testFunc.name || testFunc.toString()).indexOf('testFn') !== -1,
      'It looks like you\'re using a minified copy of the development build ' +
      'of React. When deploying React apps to production, make sure to use ' +
      'the production build which skips development warnings and is faster. ' +
      'See https://fb.me/react-minification for more details.'
    );

    // If we're in IE8, check to see if we are in compatibility mode and provide
    // information on preventing compatibility mode
    var ieCompatibilityMode =
      document.documentMode && document.documentMode < 8;

    warning(
      !ieCompatibilityMode,
      'Internet Explorer is running in compatibility mode; please add the ' +
      'following tag to your HTML to prevent this from happening: ' +
      '<meta http-equiv="X-UA-Compatible" content="IE=edge" />'
    );

    var expectedFeatures = [
      // shims
      Array.isArray,
      Array.prototype.every,
      Array.prototype.forEach,
      Array.prototype.indexOf,
      Array.prototype.map,
      Date.now,
      Function.prototype.bind,
      Object.keys,
      String.prototype.trim,
    ];

    for (var i = 0; i < expectedFeatures.length; i++) {
      if (!expectedFeatures[i]) {
        warning(
          false,
          'One or more ES5 shims expected by React are not available: ' +
          'https://fb.me/react-warning-polyfills'
        );
        break;
      }
    }
  }
}

if (__DEV__) {
  var ReactInstrumentation = require('ReactInstrumentation');
  var ReactDOMUnknownPropertyHook = require('ReactDOMUnknownPropertyHook');
  var ReactDOMNullInputValuePropHook = require('ReactDOMNullInputValuePropHook');

  ReactInstrumentation.debugTool.addHook(ReactDOMUnknownPropertyHook);
  ReactInstrumentation.debugTool.addHook(ReactDOMNullInputValuePropHook);
}

module.exports = ReactDOM;
<|endoftext|>


<commit_before>var traverse = require("../../traverse");
var util     = require("../../util");
var t        = require("../../types");
var _        = require("lodash");

var isLet = function (node, parent) {
  if (!t.isVariableDeclaration(node)) return false;
  if (node._let) return true;
  if (node.kind !== "let") return false;

  // https://github.com/6to5/6to5/issues/255
  if (!t.isFor(parent) || t.isFor(parent) && parent.left !== node) {
    _.each(node.declarations, function (declar) {
      declar.init = declar.init || t.identifier("undefined");
    });
  }

  node._let = true;
  node.kind = "var";
  return true;
};

var isVar = function (node, parent) {
  return t.isVariableDeclaration(node, { kind: "var" }) && !isLet(node, parent);
};

var standardiseLets = function (declars) {
  for (var i in declars) {
    delete declars[i]._let;
  }
};

exports.VariableDeclaration = function (node, parent) {
  isLet(node, parent);
};

exports.Loop = function (node, parent, file, scope) {
  var init = node.left || node.init;
  if (isLet(init, node)) {
    t.ensureBlock(node);
    node.body._letDeclars = [init];
  }

  if (t.isLabeledStatement(parent)) {
    // set label so `run` has access to it
    node.label = parent.label;
  }

  var letScoping = new LetScoping(node, node.body, parent, file, scope);
  letScoping.run();

  if (node.label && !t.isLabeledStatement(parent)) {
    // we've been given a label so let's wrap ourselves
    return t.labeledStatement(node.label, node);
  }
};

exports.BlockStatement = function (block, parent, file, scope) {
  if (!t.isLoop(parent)) {
    var letScoping = new LetScoping(false, block, parent, file, scope);
    letScoping.run();
  }
};

/**
 * Description
 *
 * @param {Boolean|Node} loopParent
 * @param {Node} block
 * @param {Node} parent
 * @param {File} file
 * @param {Scope} scope
 */

function LetScoping(loopParent, block, parent, file, scope) {
  this.loopParent = loopParent;
  this.parent     = parent;
  this.scope      = scope;
  this.block      = block;
  this.file       = file;

  this.letReferences = {};
  this.body          = [];
}

/**
 * Start the ball rolling.
 */

LetScoping.prototype.run = function () {
  var block = this.block;

  if (block._letDone) return;
  block._letDone = true;

  this.info = this.getInfo();

  // remap all let references that exist in upper scopes to their uid
  this.remap();

  // this is a block within a `Function` so we can safely leave it be
  if (t.isFunction(this.parent)) return this.noClosure();

  // this block has no let references so let's clean up
  if (!this.info.keys.length) return this.noClosure();

  // returns whether or not there are any outside let references within any
  // functions
  var referencesInClosure = this.getLetReferences();

  // no need for a closure so let's clean up
  if (!referencesInClosure) return this.noClosure();

  // if we're inside of a for loop then we search to see if there are any
  // `break`s, `continue`s, `return`s etc
  this.has = this.checkLoop();

  // hoist var references to retain scope
  this.hoistVarDeclarations();

  // set let references to plain var references
  standardiseLets(this.info.declarators);

  // turn letReferences into an array
  var letReferences = _.values(this.letReferences);

  // build the closure that we're going to wrap the block with
  var fn = t.functionExpression(null, letReferences, t.blockStatement(block.body));
  fn._aliasFunction = true;

  // replace the current block body with the one we're going to build
  block.body = this.body;

  // change upper scope references with their uid if they have one
  var params = this.getParams(letReferences);

  // build a call and a unique id that we can assign the return value to
  var call = t.callExpression(fn, params);
  var ret  = this.file.generateUidIdentifier("ret", this.scope);

  var hasYield = traverse.hasType(fn.body, "YieldExpression", t.FUNCTION_TYPES);
  if (hasYield) {
    fn.generator = true;
    call = t.yieldExpression(call, true);
  }

  this.build(ret, call);
};

/**
 * There are no let references accessed within a closure so we can just turn the
 * lets into vars.
 */

LetScoping.prototype.noClosure = function () {
  standardiseLets(this.info.declarators);
};

/**
 * Traverse through block and replace all references that exist in a higher
 * scope to their uids.
 */

LetScoping.prototype.remap = function () {
  var replacements = this.info.duplicates;
  var block        = this.block;

  if (!this.info.hasDuplicates) return;

  var replace = function (node, parent, scope) {
    if (!t.isIdentifier(node)) return;
    if (!t.isReferenced(node, parent)) return;
    if (scope && scope.hasOwn(node.name)) return;
    node.name = replacements[node.name] || node.name;
  };

  var traverseReplace = function (node, parent) {
    replace(node, parent);
    traverse(node, { enter: replace });
  };

  var loopParent = this.loopParent;
  if (loopParent) {
    traverseReplace(loopParent.right, loopParent);
    traverseReplace(loopParent.test, loopParent);
    traverseReplace(loopParent.update, loopParent);
  }

  traverse(block, { enter: replace });
};

/**
 * Description
 *
 * @returns {Object}
 */

LetScoping.prototype.getInfo = function () {
  var block = this.block;
  var scope = this.scope;
  var file  = this.file;

  var opts = {
    // array of `Identifier` names of let variables that appear lexically out of
    // this scope but should be accessible - eg. `ForOfStatement`.left
    outsideKeys: [],

    // array of let `VariableDeclarator`s that are a part of this block
    declarators: block._letDeclars || [],

    // object of duplicate ids and their aliases - if there's an `Identifier`
    // name that's used in an upper scope we generate a unique id and replace
    // all references with it
    duplicates:  {},

    hasDuplicates: false,

    // array of `Identifier` names of let variables that are accessible within
    // the current block
    keys:        []
  };

  var duplicates = function (id, key) {
    var has = scope.parentGet(key);

    if (has && has !== id) {
      // there's a variable with this exact name in an upper scope so we need
      // to generate a new name
      opts.duplicates[key] = id.name = file.generateUid(key, scope);
      opts.hasDuplicates = true;
    }
  };

  var i;
  var declar;

  for (i in opts.declarators) {
    declar = opts.declarators[i];
    opts.declarators.push(declar);

    var keys = t.getIds(declar, true);
    _.each(keys, duplicates);
    keys = Object.keys(keys);

    opts.outsideKeys = opts.outsideKeys.concat(keys);
    opts.keys = opts.keys.concat(keys);
  }

  for (i in block.body) {
    declar = block.body[i];
    if (!isLet(declar, block)) continue;

    _.each(t.getIds(declar, true), function (id, key) {
      duplicates(id, key);
      opts.keys.push(key);
    });
  }

  return opts;
};

/**
 * If we're inside of a loop then traverse it and check if it has one of
 * the following node types `ReturnStatement`, `BreakStatement`,
 * `ContinueStatement` and replace it with a return value that we can track
 * later on.
 *
 * @returns {Object}
 */

LetScoping.prototype.checkLoop = function () {
  var has = {
    hasContinue: false,
    hasReturn:   false,
    hasBreak:    false,
  };

  traverse(this.block, {
    enter: function (node, parent) {
      var replace;

      if (t.isFunction(node) || t.isLoop(node)) {
        return this.skip();
      }

      if (node && !node.label) {
        if (t.isBreakStatement(node)) {
          if (t.isSwitchCase(parent)) return;

          has.hasBreak = true;
          replace = t.returnStatement(t.literal("break"));
        } else if (t.isContinueStatement(node)) {
          has.hasContinue = true;
          replace = t.returnStatement(t.literal("continue"));
        }
      }

      if (t.isReturnStatement(node)) {
        has.hasReturn = true;
        replace = t.returnStatement(t.objectExpression([
          t.property("init", t.identifier("v"), node.argument || t.identifier("undefined"))
        ]));
      }

      if (replace) return t.inherits(replace, node);
    }
  });

  return has;
};

/**
 * Hoist all var declarations in this block to before it so they retain scope
 * once we wrap everything in a closure.
 */

LetScoping.prototype.hoistVarDeclarations = function () {
  var self = this;
  traverse(this.block, {
    enter: function (node, parent) {
      if (t.isForStatement(node)) {
        if (isVar(node.init, node)) {
          node.init = t.sequenceExpression(self.pushDeclar(node.init));
        }
      } else if (t.isFor(node)) {
        if (isVar(node.left, node)) {
          node.left = node.left.declarations[0].id;
        }
      } else if (isVar(node, parent)) {
        return self.pushDeclar(node).map(t.expressionStatement);
      } else if (t.isFunction(node)) {
        return this.skip();
      }
    }
  });
};

/**
 * Build up a parameter list that we'll call our closure wrapper with, replacing
 * all duplicate ids with their uid.
 *
 * @param {Array} params
 * @returns {Array}
 */

LetScoping.prototype.getParams = function (params) {
  var info = this.info;
  params = _.cloneDeep(params);
  _.each(params, function (param) {
    param.name = info.duplicates[param.name] || param.name;
  });
  return params;
};

/**
 * Get all let references within this block. Stopping whenever we reach another
 * block.
 */

LetScoping.prototype.getLetReferences = function () {
  var closurify = false;
  var self = this;

  // traverse through this block, stopping on functions and checking if they
  // contain any outside let references
  traverse(this.block, {
    enter: function (node, parent, scope) {
      if (t.isFunction(node)) {
        traverse(node, {
          enter: function (node, parent) {
            // not an identifier so we have no use
            if (!t.isIdentifier(node)) return;

            // not a direct reference
            if (!t.isReferenced(node, parent)) return;

            // this scope has a variable with the same name so it couldn't belong
            // to our let scope
            if (scope.hasOwn(node.name)) return;

            closurify = true;

            // this key doesn't appear just outside our scope
            if (!_.contains(self.info.outsideKeys, node.name)) return;

            // push this badboy
            self.letReferences[node.name] = node;
          }
        });

        return this.skip();
      }
    }
  });

  return closurify;
};

/**
 * Turn a `VariableDeclaration` into an array of `AssignmentExpressions` with
 * their declarations hoisted to before the closure wrapper.
 *
 * @param {Node} node VariableDeclaration
 * @returns {Array}
 */

LetScoping.prototype.pushDeclar = function (node) {
  this.body.push(t.variableDeclaration(node.kind, node.declarations.map(function (declar) {
    return t.variableDeclarator(declar.id);
  })));

  var replace = [];

  for (var i in node.declarations) {
    var declar = node.declarations[i];
    if (!declar.init) continue;

    var expr = t.assignmentExpression("=", declar.id, declar.init);
    replace.push(t.inherits(expr, declar));
  }

  return replace;
};

/**
 * Push the closure to the body.
 *
 * @param {Node} ret Identifier
 * @param {Node} call CallExpression
 */

LetScoping.prototype.build = function (ret, call) {
  var has = this.has;
  if (has.hasReturn || has.hasBreak || has.hasContinue) {
    this.buildHas(ret, call);
  } else {
    this.body.push(t.expressionStatement(call));
  }
};

/**
 * Description
 *
 * @param {Node} ret Identifier
 * @param {Node} call CallExpression
 */

LetScoping.prototype.buildHas = function (ret, call) {
  var body = this.body;

  body.push(t.variableDeclaration("var", [
    t.variableDeclarator(ret, call)
  ]));

  var loopParent = this.loopParent;
  var retCheck;
  var has = this.has;
  var cases = [];

  if (has.hasReturn) {
    // typeof ret === "object"
    retCheck = util.template("let-scoping-return", {
      RETURN: ret
    });
  }

  if (has.hasBreak || has.hasContinue) {
    // ensure that the parent has a label as we're building a switch and we
    // need to be able to access it
    var label = loopParent.label = loopParent.label || this.file.generateUidIdentifier("loop", this.scope);

    if (has.hasBreak) {
      cases.push(t.switchCase(t.literal("break"), [t.breakStatement(label)]));
    }

    if (has.hasContinue) {
      cases.push(t.switchCase(t.literal("continue"), [t.continueStatement(label)]));
    }

    if (has.hasReturn) {
      cases.push(t.switchCase(null, [retCheck]));
    }

    if (cases.length === 1) {
      var single = cases[0];
      body.push(t.ifStatement(
        t.binaryExpression("===", ret, single.test),
        single.consequent[0]
      ));
    } else {
      body.push(t.switchStatement(ret, cases));
    }
  } else {
    if (has.hasReturn) body.push(retCheck);
  }
};
<commit_msg>only check declarations in let scoping reference check<commit_after>var traverse = require("../../traverse");
var util     = require("../../util");
var t        = require("../../types");
var _        = require("lodash");

var isLet = function (node, parent) {
  if (!t.isVariableDeclaration(node)) return false;
  if (node._let) return true;
  if (node.kind !== "let") return false;

  // https://github.com/6to5/6to5/issues/255
  if (!t.isFor(parent) || t.isFor(parent) && parent.left !== node) {
    _.each(node.declarations, function (declar) {
      declar.init = declar.init || t.identifier("undefined");
    });
  }

  node._let = true;
  node.kind = "var";
  return true;
};

var isVar = function (node, parent) {
  return t.isVariableDeclaration(node, { kind: "var" }) && !isLet(node, parent);
};

var standardiseLets = function (declars) {
  for (var i in declars) {
    delete declars[i]._let;
  }
};

exports.VariableDeclaration = function (node, parent) {
  isLet(node, parent);
};

exports.Loop = function (node, parent, file, scope) {
  var init = node.left || node.init;
  if (isLet(init, node)) {
    t.ensureBlock(node);
    node.body._letDeclars = [init];
  }

  if (t.isLabeledStatement(parent)) {
    // set label so `run` has access to it
    node.label = parent.label;
  }

  var letScoping = new LetScoping(node, node.body, parent, file, scope);
  letScoping.run();

  if (node.label && !t.isLabeledStatement(parent)) {
    // we've been given a label so let's wrap ourselves
    return t.labeledStatement(node.label, node);
  }
};

exports.BlockStatement = function (block, parent, file, scope) {
  if (!t.isLoop(parent)) {
    var letScoping = new LetScoping(false, block, parent, file, scope);
    letScoping.run();
  }
};

/**
 * Description
 *
 * @param {Boolean|Node} loopParent
 * @param {Node} block
 * @param {Node} parent
 * @param {File} file
 * @param {Scope} scope
 */

function LetScoping(loopParent, block, parent, file, scope) {
  this.loopParent = loopParent;
  this.parent     = parent;
  this.scope      = scope;
  this.block      = block;
  this.file       = file;

  this.letReferences = {};
  this.body          = [];
}

/**
 * Start the ball rolling.
 */

LetScoping.prototype.run = function () {
  var block = this.block;

  if (block._letDone) return;
  block._letDone = true;

  this.info = this.getInfo();

  // remap all let references that exist in upper scopes to their uid
  this.remap();

  // this is a block within a `Function` so we can safely leave it be
  if (t.isFunction(this.parent)) return this.noClosure();

  // this block has no let references so let's clean up
  if (!this.info.keys.length) return this.noClosure();

  // returns whether or not there are any outside let references within any
  // functions
  var referencesInClosure = this.getLetReferences();

  // no need for a closure so let's clean up
  if (!referencesInClosure) return this.noClosure();

  // if we're inside of a for loop then we search to see if there are any
  // `break`s, `continue`s, `return`s etc
  this.has = this.checkLoop();

  // hoist var references to retain scope
  this.hoistVarDeclarations();

  // set let references to plain var references
  standardiseLets(this.info.declarators);

  // turn letReferences into an array
  var letReferences = _.values(this.letReferences);

  // build the closure that we're going to wrap the block with
  var fn = t.functionExpression(null, letReferences, t.blockStatement(block.body));
  fn._aliasFunction = true;

  // replace the current block body with the one we're going to build
  block.body = this.body;

  // change upper scope references with their uid if they have one
  var params = this.getParams(letReferences);

  // build a call and a unique id that we can assign the return value to
  var call = t.callExpression(fn, params);
  var ret  = this.file.generateUidIdentifier("ret", this.scope);

  var hasYield = traverse.hasType(fn.body, "YieldExpression", t.FUNCTION_TYPES);
  if (hasYield) {
    fn.generator = true;
    call = t.yieldExpression(call, true);
  }

  this.build(ret, call);
};

/**
 * There are no let references accessed within a closure so we can just turn the
 * lets into vars.
 */

LetScoping.prototype.noClosure = function () {
  standardiseLets(this.info.declarators);
};

/**
 * Traverse through block and replace all references that exist in a higher
 * scope to their uids.
 */

LetScoping.prototype.remap = function () {
  var replacements = this.info.duplicates;
  var block        = this.block;

  if (!this.info.hasDuplicates) return;

  var replace = function (node, parent, scope) {
    if (!t.isIdentifier(node)) return;
    if (!t.isReferenced(node, parent)) return;
    if (scope && scope.hasOwn(node.name)) return;
    node.name = replacements[node.name] || node.name;
  };

  var traverseReplace = function (node, parent) {
    replace(node, parent);
    traverse(node, { enter: replace });
  };

  var loopParent = this.loopParent;
  if (loopParent) {
    traverseReplace(loopParent.right, loopParent);
    traverseReplace(loopParent.test, loopParent);
    traverseReplace(loopParent.update, loopParent);
  }

  traverse(block, { enter: replace });
};

/**
 * Description
 *
 * @returns {Object}
 */

LetScoping.prototype.getInfo = function () {
  var block = this.block;
  var scope = this.scope;
  var file  = this.file;

  var opts = {
    // array of `Identifier` names of let variables that appear lexically out of
    // this scope but should be accessible - eg. `ForOfStatement`.left
    outsideKeys: [],

    // array of let `VariableDeclarator`s that are a part of this block
    declarators: block._letDeclars || [],

    // object of duplicate ids and their aliases - if there's an `Identifier`
    // name that's used in an upper scope we generate a unique id and replace
    // all references with it
    duplicates:  {},

    hasDuplicates: false,

    // array of `Identifier` names of let variables that are accessible within
    // the current block
    keys:        []
  };

  var duplicates = function (id, key) {
    var has = scope.parentGet(key);

    if (has && has !== id) {
      // there's a variable with this exact name in an upper scope so we need
      // to generate a new name
      opts.duplicates[key] = id.name = file.generateUid(key, scope);
      opts.hasDuplicates = true;
    }
  };

  var i;
  var declar;

  for (i in opts.declarators) {
    declar = opts.declarators[i];
    opts.declarators.push(declar);

    var keys = t.getIds(declar, true);
    _.each(keys, duplicates);
    keys = Object.keys(keys);

    opts.outsideKeys = opts.outsideKeys.concat(keys);
    opts.keys = opts.keys.concat(keys);
  }

  for (i in block.body) {
    declar = block.body[i];
    if (!isLet(declar, block)) continue;

    _.each(t.getIds(declar, true), function (id, key) {
      duplicates(id, key);
      opts.keys.push(key);
    });
  }

  return opts;
};

/**
 * If we're inside of a loop then traverse it and check if it has one of
 * the following node types `ReturnStatement`, `BreakStatement`,
 * `ContinueStatement` and replace it with a return value that we can track
 * later on.
 *
 * @returns {Object}
 */

LetScoping.prototype.checkLoop = function () {
  var has = {
    hasContinue: false,
    hasReturn:   false,
    hasBreak:    false,
  };

  traverse(this.block, {
    enter: function (node, parent) {
      var replace;

      if (t.isFunction(node) || t.isLoop(node)) {
        return this.skip();
      }

      if (node && !node.label) {
        if (t.isBreakStatement(node)) {
          if (t.isSwitchCase(parent)) return;

          has.hasBreak = true;
          replace = t.returnStatement(t.literal("break"));
        } else if (t.isContinueStatement(node)) {
          has.hasContinue = true;
          replace = t.returnStatement(t.literal("continue"));
        }
      }

      if (t.isReturnStatement(node)) {
        has.hasReturn = true;
        replace = t.returnStatement(t.objectExpression([
          t.property("init", t.identifier("v"), node.argument || t.identifier("undefined"))
        ]));
      }

      if (replace) return t.inherits(replace, node);
    }
  });

  return has;
};

/**
 * Hoist all var declarations in this block to before it so they retain scope
 * once we wrap everything in a closure.
 */

LetScoping.prototype.hoistVarDeclarations = function () {
  var self = this;
  traverse(this.block, {
    enter: function (node, parent) {
      if (t.isForStatement(node)) {
        if (isVar(node.init, node)) {
          node.init = t.sequenceExpression(self.pushDeclar(node.init));
        }
      } else if (t.isFor(node)) {
        if (isVar(node.left, node)) {
          node.left = node.left.declarations[0].id;
        }
      } else if (isVar(node, parent)) {
        return self.pushDeclar(node).map(t.expressionStatement);
      } else if (t.isFunction(node)) {
        return this.skip();
      }
    }
  });
};

/**
 * Build up a parameter list that we'll call our closure wrapper with, replacing
 * all duplicate ids with their uid.
 *
 * @param {Array} params
 * @returns {Array}
 */

LetScoping.prototype.getParams = function (params) {
  var info = this.info;
  params = _.cloneDeep(params);
  _.each(params, function (param) {
    param.name = info.duplicates[param.name] || param.name;
  });
  return params;
};

/**
 * Get all let references within this block. Stopping whenever we reach another
 * block.
 */

LetScoping.prototype.getLetReferences = function () {
  var closurify = false;
  var self = this;

  // traverse through this block, stopping on functions and checking if they
  // contain any outside let references
  traverse(this.block, {
    enter: function (node, parent, scope) {
      if (t.isFunction(node)) {
        traverse(node, {
          enter: function (node, parent) {
            // not an identifier so we have no use
            if (!t.isIdentifier(node)) return;

            // not a direct reference
            if (!t.isReferenced(node, parent)) return;

            // this scope has a variable with the same name so it couldn't belong
            // to our let scope
            if (scope.hasOwn(node.name, true)) return;

            closurify = true;

            // this key doesn't appear just outside our scope
            if (!_.contains(self.info.outsideKeys, node.name)) return;

            // push this badboy
            self.letReferences[node.name] = node;
          }
        });

        return this.skip();
      }
    }
  });

  return closurify;
};

/**
 * Turn a `VariableDeclaration` into an array of `AssignmentExpressions` with
 * their declarations hoisted to before the closure wrapper.
 *
 * @param {Node} node VariableDeclaration
 * @returns {Array}
 */

LetScoping.prototype.pushDeclar = function (node) {
  this.body.push(t.variableDeclaration(node.kind, node.declarations.map(function (declar) {
    return t.variableDeclarator(declar.id);
  })));

  var replace = [];

  for (var i in node.declarations) {
    var declar = node.declarations[i];
    if (!declar.init) continue;

    var expr = t.assignmentExpression("=", declar.id, declar.init);
    replace.push(t.inherits(expr, declar));
  }

  return replace;
};

/**
 * Push the closure to the body.
 *
 * @param {Node} ret Identifier
 * @param {Node} call CallExpression
 */

LetScoping.prototype.build = function (ret, call) {
  var has = this.has;
  if (has.hasReturn || has.hasBreak || has.hasContinue) {
    this.buildHas(ret, call);
  } else {
    this.body.push(t.expressionStatement(call));
  }
};

/**
 * Description
 *
 * @param {Node} ret Identifier
 * @param {Node} call CallExpression
 */

LetScoping.prototype.buildHas = function (ret, call) {
  var body = this.body;

  body.push(t.variableDeclaration("var", [
    t.variableDeclarator(ret, call)
  ]));

  var loopParent = this.loopParent;
  var retCheck;
  var has = this.has;
  var cases = [];

  if (has.hasReturn) {
    // typeof ret === "object"
    retCheck = util.template("let-scoping-return", {
      RETURN: ret
    });
  }

  if (has.hasBreak || has.hasContinue) {
    // ensure that the parent has a label as we're building a switch and we
    // need to be able to access it
    var label = loopParent.label = loopParent.label || this.file.generateUidIdentifier("loop", this.scope);

    if (has.hasBreak) {
      cases.push(t.switchCase(t.literal("break"), [t.breakStatement(label)]));
    }

    if (has.hasContinue) {
      cases.push(t.switchCase(t.literal("continue"), [t.continueStatement(label)]));
    }

    if (has.hasReturn) {
      cases.push(t.switchCase(null, [retCheck]));
    }

    if (cases.length === 1) {
      var single = cases[0];
      body.push(t.ifStatement(
        t.binaryExpression("===", ret, single.test),
        single.consequent[0]
      ));
    } else {
      body.push(t.switchStatement(ret, cases));
    }
  } else {
    if (has.hasReturn) body.push(retCheck);
  }
};
<|endoftext|>


<commit_before>// gulpfile.js

var gulp = require('gulp');
var del = require('del');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var reactify = require('reactify');
var minifyify = require('minifyify');
var karma = require('karma').server;
var jshint = require('gulp-jshint');
var sass = require('gulp-sass');

var handleError = function(err) {
  console.log(err.toString());
};

gulp.task('clean', function(done) {
  del([
    './public/js/**/*.js',
    './public/css/**/*.css'
  ], done);
});

gulp.task('browserify', function() {
  browserify({
    entries: ['./src/main/js/main.js'],
    transform: [reactify],
    debug: true
  })
    .plugin('minifyify', {output: './public/js/bundle.map.json'})
    .bundle()
    .on('error', handleError)
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('./public/js/'));
});

gulp.task('karma', ['browserify'], function(done) {
  karma.start({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, function(exitStatus) {
    done(exitStatus ? 'There are failing unit tests' : undefined);
  });
});

gulp.task('jsxhint', function() {
  gulp.src(['./src/main/js/**/*.js'])
    .pipe(jshint({
      linter: require('jshint-jsx').JSXHINT
    }))
    .pipe(jshint.reporter('default'));
});

gulp.task('sass', function() {
  gulp.src('./src/main/css/*.scss')
    .pipe(sass())
    .pipe(gulp.dest('./public/css/'))
    .pipe(gulp.dest('./doc/styleguide/'));
});

gulp.task('scss', ['sass']);

gulp.task('watch', function() {
  gulp.watch(['./src/main/js/**/*.js', './src/test/js/**/*.js'], ['browserify']);
  gulp.watch(['./src/main/css/**/*.scss'], ['sass']);
});

gulp.task('build', ['browserify', 'sass']);
<commit_msg>gulpタスクのなかで必要なモジュールをrequireするように変えた<commit_after>// gulpfile.js
var gulp = require('gulp');

var handleError = function(err) {
  console.log(err.toString());
};

gulp.task('clean', function(done) {
  var del = require('del');

  del([
    './public/js/**/*.js',
    './public/css/**/*.css'
  ], done);
});

gulp.task('browserify', function() {
  var browserify = require('browserify');
  var source = require('vinyl-source-stream');
  var reactify = require('reactify');
  var minifyify = require('minifyify');

  browserify({
    entries: ['./src/main/js/main.js'],
    transform: [reactify],
    debug: true
  })
    .plugin('minifyify', {output: './public/js/bundle.map.json'})
    .bundle()
    .on('error', handleError)
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('./public/js/'));
});

gulp.task('karma', ['browserify'], function(done) {
  var karma = require('karma').server;

  karma.start({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, function(exitStatus) {
    done(exitStatus ? 'There are failing unit tests' : undefined);
  });
});

gulp.task('test', ['karma']);

gulp.task('jsxhint', function() {
  var jshint = require('gulp-jshint');

  gulp.src(['./src/main/js/**/*.js'])
    .pipe(jshint({
      linter: require('jshint-jsx').JSXHINT
    }))
    .pipe(jshint.reporter('default'));
});

gulp.task('sass', function() {
  var sass = require('gulp-sass');

  gulp.src('./src/main/css/*.scss')
    .pipe(sass())
    .pipe(gulp.dest('./public/css/'))
    .pipe(gulp.dest('./doc/styleguide/'));
});

gulp.task('scss', ['sass']);

gulp.task('watch', function() {
  gulp.watch(['./src/main/js/**/*.js', './src/test/js/**/*.js'], ['browserify']);
  gulp.watch(['./src/main/css/**/*.scss'], ['sass']);
});

gulp.task('build', ['browserify', 'sass']);
<|endoftext|>