<commit_before>// Copyright 2002-2015, University of Colorado Boulder

/**
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var ScreenView = require( 'JOIST/ScreenView' );
  var ResetAllButton = require( 'SCENERY_PHET/buttons/ResetAllButton' );
  var MonsterNode = require( 'MRCHOMPY/mrchompy/view/MonsterNode' );
  var Bounds2 = require( 'DOT/Bounds2' );
  var Vector2 = require( 'DOT/Vector2' );
  var title = require( 'image!MRCHOMPY/mrchompy.png' );
  var Image = require( 'SCENERY/nodes/Image' );

  /**
   * @param {MrchompyModel} mrchompyModel
   * @constructor
   */
  function MrchompyScreenView( mrchompyModel ) {

    ScreenView.call( this, {
      layoutBounds: new Bounds2( 0, 0, 1024, 618 )
    } );
    var mrchompyScreenView = this;

    var Matter = window.Matter;
    console.log( Matter );

    var Demo = {};
    Matter.Demo = Demo;

    // Matter aliases
    var Engine = Matter.Engine,
      World = Matter.World,
      Bodies = Matter.Bodies,
      Body = Matter.Body,
      Composite = Matter.Composite,
      Composites = Matter.Composites,
      Common = Matter.Common,
      Constraint = Matter.Constraint,
      Events = Matter.Events,
      Bounds = Matter.Bounds,
      Vector = Matter.Vector,
      Vertices = Matter.Vertices,
      MouseConstraint = Matter.MouseConstraint,
      Mouse = Matter.Mouse,
      Query = Matter.Query,
      Svg = Matter.Svg;

    var _isBrowser = true;

    var _engine,
      _runner,
      _gui,
      _inspector,
      _sceneName,
      _mouseConstraint,
      _sceneEvents = [],
      _useInspector = _isBrowser && window.location.hash.indexOf( '-inspect' ) !== -1,
      _isMobile = _isBrowser && /(ipad|iphone|ipod|android)/gi.test( navigator.userAgent ),
      _isAutomatedTest = !_isBrowser || window._phantom;

    // initialise the demo

    Demo.init = function() {
      // some example engine options
      var options = {
        positionIterations: 6,
        velocityIterations: 4,
        enableSleeping: false,
        metrics: { extended: true },
        render: {}
      };

      // create a Matter engine
      // NOTE: this is actually Matter.Engine.create(), see the aliases at top of this file
      var container = document.getElementById( 'canvas-container' );
      _engine = Engine.create( container, options );

      // engine reference for external use
      Matter.Demo._engine = _engine;

      // run the engine
      Engine.run( _engine );

      Demo.mixed();
    };

    // call init when the page has loaded fully

    if ( window.addEventListener ) {
      window.addEventListener( 'load', Demo.init );
    }
    else if ( window.attachEvent ) {
      window.attachEvent( 'load', Demo.init );
    }

    // each demo scene is set up in its own function, see below

    Demo.mixed = function() {
      var _world = _engine.world;

      _world.bounds = {
        min: {
          x: 0, y: 0
        },
        max: { x: 5000, y: 800 }
      };

      Demo.reset();

      var particleOptions = {
        friction: 0.05,
        frictionStatic: 0.1
      };

      var elements = [
        //xx, yy, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions
        Composites.softBody( 800, 0, 6, 6, 0, 0, true, 27, particleOptions ),
        //Composites.softBody( 250, 300, 8, 3, 0, 0, true, 15, particleOptions ),
        //Composites.softBody( 250, 400, 4, 4, 0, 0, true, 15, particleOptions ),
        Bodies.rectangle( 200, 100, 100, 100 )
      ];
      World.add( _world, elements );

      var groupId = Body.nextGroupId();

      var ropeA = Composites.stack( 600, 0, 5, 2, 10, 10, function( x, y, column, row ) {
        return Bodies.rectangle( x, y, 50, 20, { groupId: groupId } );
      } );

      Composites.chain( ropeA, 0.5, 0, -0.5, 0, { stiffness: 0.8, length: 2 } );
      Composite.add( ropeA, Constraint.create( {
        bodyA: elements[ 0 ].bodies[ 0 ],
        bodyB: ropeA.bodies[ ropeA.bodies.length - 1 ],
        stiffness: 1
      } ) );
      World.add( _world, ropeA );
      elements = elements.concat( ropeA );

      groupId = Body.nextGroupId();

      var ropeB = Composites.stack( 1000, 0, 5, 2, 10, 10, function( x, y, column, row ) {
        return Bodies.rectangle( x, y, 50, 20, { groupId: groupId } );
      } );

      Composites.chain( ropeB, 0.5, 0, -0.5, 0, { stiffness: 0.8, length: 2 } );
      Composite.add( ropeB, Constraint.create( {
        bodyA: elements[ 0 ].bodies[ 5 ],
        bodyB: ropeB.bodies[ 0 ],
        stiffness: 1
      } ) );

      World.add( _world, ropeB );

      elements = elements.concat( ropeB );

      mrchompyScreenView.elements = elements;
    };

    Demo.reset = function() {
      var _world = _engine.world, i;

      World.clear( _world );
      Engine.clear( _engine );

      // clear scene graph (if defined in controller)
      if ( _engine.render ) {
        var renderController = _engine.render.controller;
        if ( renderController && renderController.clear ) {
          renderController.clear( _engine.render );
        }
      }

      // clear all scene events
      if ( _engine.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _engine, _sceneEvents[ i ] );
        }
      }

      if ( _mouseConstraint && _mouseConstraint.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _mouseConstraint, _sceneEvents[ i ] );
        }
      }

      if ( _world.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _world, _sceneEvents[ i ] );
        }
      }

      if ( _runner && _runner.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _runner, _sceneEvents[ i ] );
        }
      }

      if ( _engine.render && _engine.render.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _engine.render, _sceneEvents[ i ] );
        }
      }

      _sceneEvents = [];

      // reset id pool
      Common._nextId = 0;

      // reset random seed
      Common._seed = 0;

      _engine.enableSleeping = false;
      _engine.world.gravity.y = 1;
      _engine.world.gravity.x = 0;
      _engine.timing.timeScale = 1;

      var offset = 5;
      World.add( _world, [
        //Bodies.rectangle( 400, -offset, 800.5 + 2 * offset, 50.5, { isStatic: true } ),
        Bodies.rectangle( 400, 600 + offset, 10000, 50.5, { isStatic: true } ),
        //Bodies.rectangle( 800 + offset, 300, 50.5, 600.5 + 2 * offset, { isStatic: true } ),
        Bodies.rectangle( -offset, 300, 50.5, 600.5 + 2 * offset, { isStatic: true } )
      ] );
    };

    Demo.init();

    var triangles = [ { x1: 0, y1: 0, x2: 100, y2: 0, x3: 50, y3: 50, r: 1, g: 0, b: 0, a: 1 } ];
    var offset = new Vector2( 0, 0 );
    var monsterNode = new MonsterNode( this.layoutBounds.width, this.layoutBounds.height, triangles, offset );
    this.addChild( monsterNode );

    this.events.on( 'layoutFinished', function( dx, dy, width, height ) {
        monsterNode.setCanvasBounds( new Bounds2( -dx, -dy, width - dx, height - dy ) );
      }
    );

    var addRectangle = function( x, y, width, height, r, g, b, a ) {
      triangles.push( { x1: x, y1: y, x2: x + width, y2: y, x3: x + width, y3: y + height, r: r, g: g, b: b, a: a } );
      triangles.push( {
        x1: x,
        y1: y,
        x2: x,
        y2: y + height,
        x3: x + width,
        y3: y + height,
        r: r,
        g: g,
        b: b,
        a: a
      } );
    };

    this.step = function( dt ) {

      console.log( _engine.pairs.collisionActive.length );
      var force = 0.05;
      if ( pressedKeys[ 39 ] ) {

        // right
        console.log( 'right' );
        Matter.Body.applyForce( mrchompyScreenView.elements[ 0 ].bodies[ 30 ], { x: 0, y: 0 }, { x: force / 2, y: 0 } );
        Matter.Body.applyForce( mrchompyScreenView.elements[ 0 ].bodies[ 35 ], { x: 0, y: 0 }, { x: force / 2, y: 0 } );
      }
      if ( pressedKeys[ 37 ] ) {
        Matter.Body.applyForce( mrchompyScreenView.elements[ 0 ].bodies[ 30 ], { x: 0, y: 0 }, {
          x: -force / 2,
          y: 0
        } );
        Matter.Body.applyForce( mrchompyScreenView.elements[ 0 ].bodies[ 35 ], { x: 0, y: 0 }, {
          x: -force / 2,
          y: 0
        } );
      }
      if ( pressedKeys[ 38 ] && _engine.pairs.collisionActive.length > 35 ) {
        for ( var i = 0; i < mrchompyScreenView.elements[ 0 ].bodies.length; i++ ) {
          var b = mrchompyScreenView.elements[ 0 ].bodies[ i ];
          Matter.Body.applyForce( b, { x: 0, y: 0 }, {
            x: 0,
            y: -0.2 / mrchompyScreenView.elements[ 0 ].bodies.length
          } );
        }
      }
      triangles.length = 0;
      for ( var i = 0; i < mrchompyScreenView.elements.length; i++ ) {
        var element = mrchompyScreenView.elements[ i ];
        if ( element.bodies ) {
          for ( var k = 0; k < element.bodies.length; k++ ) {
            var body = element.bodies[ k ];
            console.log( 'v', body.vertices.length );

            triangles.push( {
              x1: body.position.x, y1: body.position.y,
              x2: body.position.x + 35, y2: body.position.y,
              x3: body.position.x, y3: body.position.y + 35,
              r: k === 35 ? 1 : 0.1, g: 0.1, b: 0.1, a: 1
            } );
          }
        }
        else {
          if ( element.label === 'Rectangle Body' ) {
            var body = element;

            triangles.push( {
              x1: body.vertices[ 0 ].x, y1: body.vertices[ 0 ].y,
              x2: body.vertices[ 1 ].x, y2: body.vertices[ 1 ].y,
              x3: body.vertices[ 2 ].x, y3: body.vertices[ 2 ].y,
              r: 0.1, g: 0.1, b: 0.1, a: 1
            } );

            triangles.push( {
              x1: body.vertices[ 0 ].x, y1: body.vertices[ 0 ].y,
              x2: body.vertices[ 2 ].x, y2: body.vertices[ 2 ].y,
              x3: body.vertices[ 3 ].x, y3: body.vertices[ 3 ].y,
              r: 0.1, g: 0.1, b: 0.1, a: 1
            } );
          }
        }
      }

      addRectangle( -1000, -1000, 1000 + 25, 600 + 1000, 0.1, 0.1, 0.1, 0.3 );
      addRectangle( -1000, 600, 10000, 1000, 9 / 255, 46 / 255, 13 / 255, 1 );

      offset.x = -mrchompyScreenView.elements[ 0 ].bodies[ 0 ].position.x + this.layoutBounds.width / 2;
      titleNode.x = offset.x + 420;
      monsterNode.invalidatePaint();
    };

    // Key listeners
    // http://stackoverflow.com/questions/16089421/simplest-way-to-detect-keypresses-in-javascript
    function addEvent( element, eventName, callback ) {
      if ( element.addEventListener ) {
        element.addEventListener( eventName, callback, false );
      }
      else if ( element.attachEvent ) {
        element.attachEvent( "on" + eventName, callback );
      }
      else {
        element[ "on" + eventName ] = callback;
      }
    }

    var pressedKeys = {};
    addEvent( document, "keydown", function( e ) {
      var e = e || window.event;
      // use e.keyCode
      console.log( e.keyCode );
      pressedKeys[ e.keyCode ] = true;
    } );

    addEvent( document, "keyup", function( e ) {
      var e = e || window.event;
      // use e.keyCode
      console.log( e.keyCode );
      pressedKeys[ e.keyCode ] = false;
    } );

    var titleNode = new Image( title, {
      centerX: this.layoutBounds.centerX,
      top: 100
    } );
    this.addChild( titleNode );
  }

  return inherit( ScreenView, MrchompyScreenView, {} );
} );<commit_msg>tests for 2nd tentacle<commit_after>// Copyright 2002-2015, University of Colorado Boulder

/**
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var ScreenView = require( 'JOIST/ScreenView' );
  var ResetAllButton = require( 'SCENERY_PHET/buttons/ResetAllButton' );
  var MonsterNode = require( 'MRCHOMPY/mrchompy/view/MonsterNode' );
  var Bounds2 = require( 'DOT/Bounds2' );
  var Vector2 = require( 'DOT/Vector2' );
  var title = require( 'image!MRCHOMPY/mrchompy.png' );
  var Image = require( 'SCENERY/nodes/Image' );

  /**
   * @param {MrchompyModel} mrchompyModel
   * @constructor
   */
  function MrchompyScreenView( mrchompyModel ) {

    ScreenView.call( this, {
      layoutBounds: new Bounds2( 0, 0, 1024, 618 )
    } );
    var mrchompyScreenView = this;

    var Matter = window.Matter;
    console.log( Matter );

    var Demo = {};
    Matter.Demo = Demo;

    // Matter aliases
    var Engine = Matter.Engine,
      World = Matter.World,
      Bodies = Matter.Bodies,
      Body = Matter.Body,
      Composite = Matter.Composite,
      Composites = Matter.Composites,
      Common = Matter.Common,
      Constraint = Matter.Constraint,
      Events = Matter.Events,
      Bounds = Matter.Bounds,
      Vector = Matter.Vector,
      Vertices = Matter.Vertices,
      MouseConstraint = Matter.MouseConstraint,
      Mouse = Matter.Mouse,
      Query = Matter.Query,
      Svg = Matter.Svg;

    var _isBrowser = true;

    var _engine,
      _runner,
      _gui,
      _inspector,
      _sceneName,
      _mouseConstraint,
      _sceneEvents = [],
      _useInspector = _isBrowser && window.location.hash.indexOf( '-inspect' ) !== -1,
      _isMobile = _isBrowser && /(ipad|iphone|ipod|android)/gi.test( navigator.userAgent ),
      _isAutomatedTest = !_isBrowser || window._phantom;

    // initialise the demo

    Demo.init = function() {
      // some example engine options
      var options = {
        positionIterations: 6,
        velocityIterations: 4,
        enableSleeping: false,
        metrics: { extended: true },
        render: {}
      };

      // create a Matter engine
      // NOTE: this is actually Matter.Engine.create(), see the aliases at top of this file
      var container = document.getElementById( 'canvas-container' );
      _engine = Engine.create( container, options );

      // engine reference for external use
      Matter.Demo._engine = _engine;

      // run the engine
      Engine.run( _engine );

      Demo.mixed();
    };

    // call init when the page has loaded fully

    if ( window.addEventListener ) {
      window.addEventListener( 'load', Demo.init );
    }
    else if ( window.attachEvent ) {
      window.attachEvent( 'load', Demo.init );
    }

    // each demo scene is set up in its own function, see below

    Demo.mixed = function() {
      var _world = _engine.world;

      _world.bounds = {
        min: {
          x: 0, y: 0
        },
        max: { x: 5000, y: 800 }
      };

      Demo.reset();

      var particleOptions = {
        friction: 0.05,
        frictionStatic: 0.1
      };

      var elements = [
        //xx, yy, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions
        Composites.softBody( 800, 0, 6, 6, 0, 0, true, 27, particleOptions ),
        //Composites.softBody( 250, 300, 8, 3, 0, 0, true, 15, particleOptions ),
        //Composites.softBody( 250, 400, 4, 4, 0, 0, true, 15, particleOptions ),
        Bodies.rectangle( 200, 100, 100, 100 )
      ];
      World.add( _world, elements );

      var groupId = Body.nextGroupId();

      var ropeA = Composites.stack( 600, 0, 5, 2, 10, 10, function( x, y, column, row ) {
        return Bodies.rectangle( x, y, 50, 20, { groupId: groupId } );
      } );

      Composites.chain( ropeA, 0.5, 0, -0.5, 0, { stiffness: 0.8, length: 2 } );
      Composite.add( ropeA, Constraint.create( {
        bodyA: elements[ 0 ].bodies[ 6 ],
        bodyB: ropeA.bodies[ ropeA.bodies.length - 1 ],
        stiffness: 1
      } ) );
      World.add( _world, ropeA );
      elements = elements.concat( ropeA );

      groupId = Body.nextGroupId();

      //var ropeB = Composites.stack( 700, 400, 5, 2, 10, 10, function( x, y, column, row ) {
      //  return Bodies.rectangle( x, y, 50, 20, { groupId: groupId } );
      //} );

      //Composites.chain( ropeB, 0.5, 0, -0.5, 0, { stiffness: 0.8, length: 2 } );
      //Composite.add( ropeB, Constraint.create( {
      //  bodyA: elements[ 0 ].bodies[ 30 ],
      //  bodyB: ropeB.bodies[ 0 ],
      //  stiffness: 1
      //} ) );
      //
      //World.add( _world, ropeB );
      //
      //elements = elements.concat( ropeB );

      mrchompyScreenView.elements = elements;
    };

    Demo.reset = function() {
      var _world = _engine.world, i;

      World.clear( _world );
      Engine.clear( _engine );

      // clear scene graph (if defined in controller)
      if ( _engine.render ) {
        var renderController = _engine.render.controller;
        if ( renderController && renderController.clear ) {
          renderController.clear( _engine.render );
        }
      }

      // clear all scene events
      if ( _engine.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _engine, _sceneEvents[ i ] );
        }
      }

      if ( _mouseConstraint && _mouseConstraint.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _mouseConstraint, _sceneEvents[ i ] );
        }
      }

      if ( _world.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _world, _sceneEvents[ i ] );
        }
      }

      if ( _runner && _runner.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _runner, _sceneEvents[ i ] );
        }
      }

      if ( _engine.render && _engine.render.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _engine.render, _sceneEvents[ i ] );
        }
      }

      _sceneEvents = [];

      // reset id pool
      Common._nextId = 0;

      // reset random seed
      Common._seed = 0;

      _engine.enableSleeping = false;
      _engine.world.gravity.y = 1;
      _engine.world.gravity.x = 0;
      _engine.timing.timeScale = 1;

      var offset = 5;
      World.add( _world, [
        //Bodies.rectangle( 400, -offset, 800.5 + 2 * offset, 50.5, { isStatic: true } ),
        Bodies.rectangle( 400, 600 + offset, 10000, 50.5, { isStatic: true } ),
        //Bodies.rectangle( 800 + offset, 300, 50.5, 600.5 + 2 * offset, { isStatic: true } ),
        Bodies.rectangle( -offset, 300, 50.5, 600.5 + 2 * offset, { isStatic: true } )
      ] );
    };

    Demo.init();

    var triangles = [ { x1: 0, y1: 0, x2: 100, y2: 0, x3: 50, y3: 50, r: 1, g: 0, b: 0, a: 1 } ];
    var offset = new Vector2( 0, 0 );
    var monsterNode = new MonsterNode( this.layoutBounds.width, this.layoutBounds.height, triangles, offset );
    this.addChild( monsterNode );

    this.events.on( 'layoutFinished', function( dx, dy, width, height ) {
        monsterNode.setCanvasBounds( new Bounds2( -dx, -dy, width - dx, height - dy ) );
      }
    );

    var addRectangle = function( x, y, width, height, r, g, b, a ) {
      triangles.push( { x1: x, y1: y, x2: x + width, y2: y, x3: x + width, y3: y + height, r: r, g: g, b: b, a: a } );
      triangles.push( {
        x1: x,
        y1: y,
        x2: x,
        y2: y + height,
        x3: x + width,
        y3: y + height,
        r: r,
        g: g,
        b: b,
        a: a
      } );
    };

    this.step = function( dt ) {

      console.log( _engine.pairs.collisionActive.length );
      var force = 0.05;
      if ( pressedKeys[ 39 ] ) {

        // right
        console.log( 'right' );
        Matter.Body.applyForce( mrchompyScreenView.elements[ 0 ].bodies[ 30 ], { x: 0, y: 0 }, { x: force / 2, y: 0 } );
        Matter.Body.applyForce( mrchompyScreenView.elements[ 0 ].bodies[ 35 ], { x: 0, y: 0 }, { x: force / 2, y: 0 } );
      }
      if ( pressedKeys[ 37 ] ) {
        Matter.Body.applyForce( mrchompyScreenView.elements[ 0 ].bodies[ 30 ], { x: 0, y: 0 }, {
          x: -force / 2,
          y: 0
        } );
        Matter.Body.applyForce( mrchompyScreenView.elements[ 0 ].bodies[ 35 ], { x: 0, y: 0 }, {
          x: -force / 2,
          y: 0
        } );
      }
      if ( pressedKeys[ 38 ] && _engine.pairs.collisionActive.length > 35 ) {
        for ( var i = 0; i < mrchompyScreenView.elements[ 0 ].bodies.length; i++ ) {
          var b = mrchompyScreenView.elements[ 0 ].bodies[ i ];
          Matter.Body.applyForce( b, { x: 0, y: 0 }, {
            x: 0,
            y: -0.2 / mrchompyScreenView.elements[ 0 ].bodies.length
          } );
        }
      }
      triangles.length = 0;
      for ( var i = 0; i < mrchompyScreenView.elements.length; i++ ) {
        var element = mrchompyScreenView.elements[ i ];
        if ( element.bodies ) {
          for ( var k = 0; k < element.bodies.length; k++ ) {
            var body = element.bodies[ k ];

            for ( var v = 0; v < body.vertices.length - 2; v++ ) {
              var a = body.vertices[ v ];
              var b = body.vertices[ v + 1 ];
              var c = body.vertices[ v + 2 ];
              triangles.push( {
                x1: a.x,
                y1: a.y,
                x2: b.x,
                y2: b.y,
                x3: c.x,
                y3: c.y,
                r: k === 30 ? 1 : 0.1,
                g: 0.1,
                b: 0.1,
                a: 1
              } );
            }
          }
        }
        else {
          if ( element.label === 'Rectangle Body' ) {
            var body = element;

            triangles.push( {
              x1: body.vertices[ 0 ].x, y1: body.vertices[ 0 ].y,
              x2: body.vertices[ 1 ].x, y2: body.vertices[ 1 ].y,
              x3: body.vertices[ 2 ].x, y3: body.vertices[ 2 ].y,
              r: 0.1, g: 0.1, b: 0.1, a: 1
            } );

            triangles.push( {
              x1: body.vertices[ 0 ].x, y1: body.vertices[ 0 ].y,
              x2: body.vertices[ 2 ].x, y2: body.vertices[ 2 ].y,
              x3: body.vertices[ 3 ].x, y3: body.vertices[ 3 ].y,
              r: 0.1, g: 0.1, b: 0.1, a: 1
            } );
          }
        }
      }

      addRectangle( -1000, -1000, 1000 + 25, 600 + 1000, 0.1, 0.1, 0.1, 0.3 );
      addRectangle( -1000, 600, 10000, 1000, 9 / 255, 46 / 255, 13 / 255, 1 );

      offset.x = -mrchompyScreenView.elements[ 0 ].bodies[ 0 ].position.x + this.layoutBounds.width / 2-300;
      titleNode.x = offset.x + 420;
      monsterNode.invalidatePaint();
    };

    // Key listeners
    // http://stackoverflow.com/questions/16089421/simplest-way-to-detect-keypresses-in-javascript
    function addEvent( element, eventName, callback ) {
      if ( element.addEventListener ) {
        element.addEventListener( eventName, callback, false );
      }
      else if ( element.attachEvent ) {
        element.attachEvent( "on" + eventName, callback );
      }
      else {
        element[ "on" + eventName ] = callback;
      }
    }

    var pressedKeys = {};
    addEvent( document, "keydown", function( e ) {
      var e = e || window.event;
      // use e.keyCode
      console.log( e.keyCode );
      pressedKeys[ e.keyCode ] = true;
    } );

    addEvent( document, "keyup", function( e ) {
      var e = e || window.event;
      // use e.keyCode
      console.log( e.keyCode );
      pressedKeys[ e.keyCode ] = false;
    } );

    var titleNode = new Image( title, {
      centerX: this.layoutBounds.centerX,
      top: 100
    } );
    this.addChild( titleNode );
  }

  return inherit( ScreenView, MrchompyScreenView, {} );
} );<|endoftext|>


<commit_before>// Copyright 2002-2015, University of Colorado Boulder

/**
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var ScreenView = require( 'JOIST/ScreenView' );
  var ResetAllButton = require( 'SCENERY_PHET/buttons/ResetAllButton' );
  var MonsterNode = require( 'MRCHOMPY/mrchompy/view/MonsterNode' );
  var Bounds2 = require( 'DOT/Bounds2' );
  var Vector2 = require( 'DOT/Vector2' );
  var title = require( 'image!MRCHOMPY/mrchompy.png' );
  var Image = require( 'SCENERY/nodes/Image' );

  /**
   * @param {MrchompyModel} mrchompyModel
   * @constructor
   */
  function MrchompyScreenView( mrchompyModel ) {

    ScreenView.call( this, {
      layoutBounds: new Bounds2( 0, 0, 1024, 618 )
    } );
    var mrchompyScreenView = this;

    var Matter = window.Matter;
    console.log( Matter );

    var Demo = {};
    Matter.Demo = Demo;

    // Matter aliases
    var Engine = Matter.Engine,
      World = Matter.World,
      Bodies = Matter.Bodies,
      Body = Matter.Body,
      Composite = Matter.Composite,
      Composites = Matter.Composites,
      Common = Matter.Common,
      Constraint = Matter.Constraint,
      Events = Matter.Events,
      Bounds = Matter.Bounds,
      Vector = Matter.Vector,
      Vertices = Matter.Vertices,
      MouseConstraint = Matter.MouseConstraint,
      Mouse = Matter.Mouse,
      Query = Matter.Query,
      Svg = Matter.Svg;

    var _isBrowser = true;

    var _engine,
      _runner,
      _gui,
      _inspector,
      _sceneName,
      _mouseConstraint,
      _sceneEvents = [],
      _useInspector = _isBrowser && window.location.hash.indexOf( '-inspect' ) !== -1,
      _isMobile = _isBrowser && /(ipad|iphone|ipod|android)/gi.test( navigator.userAgent ),
      _isAutomatedTest = !_isBrowser || window._phantom;

    // initialise the demo

    Demo.init = function() {
      // some example engine options
      var options = {
        positionIterations: 6,
        velocityIterations: 4,
        enableSleeping: false,
        metrics: { extended: true },
        render: {}
      };

      // create a Matter engine
      // NOTE: this is actually Matter.Engine.create(), see the aliases at top of this file
      var container = document.getElementById( 'canvas-container' );
      _engine = Engine.create( container, options );

      // engine reference for external use
      Matter.Demo._engine = _engine;

      // run the engine
      Engine.run( _engine );

      Demo.mixed();
    };

    // call init when the page has loaded fully

    if ( window.addEventListener ) {
      window.addEventListener( 'load', Demo.init );
    }
    else if ( window.attachEvent ) {
      window.attachEvent( 'load', Demo.init );
    }

    // each demo scene is set up in its own function, see below

    Demo.mixed = function() {
      var _world = _engine.world;

      _world.bounds = {
        min: {
          x: 0, y: 0
        },
        max: { x: 5000, y: 800 }
      };

      Demo.reset();

      var particleOptions = {
        friction: 0.05,
        frictionStatic: 0.1
      };

      var elements = [
        //xx, yy, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions
        Composites.softBody( 800, 0, 6, 6, 0, 0, true, 27, particleOptions ),
        //Composites.softBody( 250, 300, 8, 3, 0, 0, true, 15, particleOptions ),
        //Composites.softBody( 250, 400, 4, 4, 0, 0, true, 15, particleOptions ),
        Bodies.rectangle( 200, 100, 100, 100 )
      ];
      World.add( _world, elements );

      var groupId = Body.nextGroupId();

      var ropeA = Composites.stack( 200, 100, 5, 2, 10, 10, function( x, y, column, row ) {
        return Bodies.rectangle( x, y, 50, 20, { groupId: groupId } );
      } );

      Composites.chain( ropeA, 0.5, 0, -0.5, 0, { stiffness: 0.8, length: 2 } );
      Composite.add( ropeA, Constraint.create( {
        bodyB: ropeA.bodies[ 0 ],
        pointB: { x: -25, y: 0 },
        pointA: { x: 200, y: 100 },
        stiffness: 0.5
      } ) );

      World.add( _world, ropeA );

      elements = elements.concat( ropeA );
      mrchompyScreenView.elements = elements;
    };

    Demo.reset = function() {
      var _world = _engine.world, i;

      World.clear( _world );
      Engine.clear( _engine );

      // clear scene graph (if defined in controller)
      if ( _engine.render ) {
        var renderController = _engine.render.controller;
        if ( renderController && renderController.clear ) {
          renderController.clear( _engine.render );
        }
      }

      // clear all scene events
      if ( _engine.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _engine, _sceneEvents[ i ] );
        }
      }

      if ( _mouseConstraint && _mouseConstraint.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _mouseConstraint, _sceneEvents[ i ] );
        }
      }

      if ( _world.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _world, _sceneEvents[ i ] );
        }
      }

      if ( _runner && _runner.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _runner, _sceneEvents[ i ] );
        }
      }

      if ( _engine.render && _engine.render.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _engine.render, _sceneEvents[ i ] );
        }
      }

      _sceneEvents = [];

      // reset id pool
      Common._nextId = 0;

      // reset random seed
      Common._seed = 0;

      _engine.enableSleeping = false;
      _engine.world.gravity.y = 1;
      _engine.world.gravity.x = 0;
      _engine.timing.timeScale = 1;

      var offset = 5;
      World.add( _world, [
        //Bodies.rectangle( 400, -offset, 800.5 + 2 * offset, 50.5, { isStatic: true } ),
        Bodies.rectangle( 400, 600 + offset, 10000, 50.5, { isStatic: true } ),
        //Bodies.rectangle( 800 + offset, 300, 50.5, 600.5 + 2 * offset, { isStatic: true } ),
        Bodies.rectangle( -offset, 300, 50.5, 600.5 + 2 * offset, { isStatic: true } )
      ] );
    };

    Demo.init();

    var triangles = [ { x1: 0, y1: 0, x2: 100, y2: 0, x3: 50, y3: 50, r: 1, g: 0, b: 0, a: 1 } ];
    var offset = new Vector2( 0, 0 );
    var monsterNode = new MonsterNode( this.layoutBounds.width, this.layoutBounds.height, triangles, offset );
    this.addChild( monsterNode );

    this.events.on( 'layoutFinished', function( dx, dy, width, height ) {
        monsterNode.setCanvasBounds( new Bounds2( -dx, -dy, width - dx, height - dy ) );
      }
    );

    var addRectangle = function( x, y, width, height, r, g, b, a ) {
      triangles.push( { x1: x, y1: y, x2: x + width, y2: y, x3: x + width, y3: y + height, r: r, g: g, b: b, a: a } );
      triangles.push( {
        x1: x,
        y1: y,
        x2: x,
        y2: y + height,
        x3: x + width,
        y3: y + height,
        r: r,
        g: g,
        b: b,
        a: a
      } );
    };

    this.step = function( dt ) {

      console.log( _engine.pairs.collisionActive.length );
      var force = 0.05;
      if ( pressedKeys[ 39 ] ) {

        // right
        console.log( 'right' );
        Matter.Body.applyForce( mrchompyScreenView.elements[ 0 ].bodies[ 0 ], { x: 0, y: 0 }, { x: force, y: 0 } );
      }
      if ( pressedKeys[ 37 ] ) {
        Matter.Body.applyForce( mrchompyScreenView.elements[ 0 ].bodies[ 0 ], { x: 0, y: 0 }, { x: -force, y: 0 } );
      }
      if ( pressedKeys[ 38 ] && _engine.pairs.collisionActive.length > 35 ) {
        for ( var i = 0; i < mrchompyScreenView.elements[ 0 ].bodies.length; i++ ) {
          var b = mrchompyScreenView.elements[ 0 ].bodies[ i ];
          Matter.Body.applyForce( b, { x: 0, y: 0 }, {
            x: 0,
            y: -2 / mrchompyScreenView.elements[ 0 ].bodies.length
          } );
        }
      }
      triangles.length = 0;
      for ( var i = 0; i < mrchompyScreenView.elements.length; i++ ) {
        var element = mrchompyScreenView.elements[ i ];
        if ( element.bodies ) {
          for ( var k = 0; k < element.bodies.length; k++ ) {
            var body = element.bodies[ k ];

            triangles.push( {
              x1: body.position.x, y1: body.position.y,
              x2: body.position.x + 35, y2: body.position.y,
              x3: body.position.x, y3: body.position.y + 35,
              r: 0.1, g: 0.1, b: 0.1, a: 1
            } );
          }
        }
        else {
          if ( element.label === 'Rectangle Body' ) {
            var body = element;

            triangles.push( {
              x1: body.vertices[ 0 ].x, y1: body.vertices[ 0 ].y,
              x2: body.vertices[ 1 ].x, y2: body.vertices[ 1 ].y,
              x3: body.vertices[ 2 ].x, y3: body.vertices[ 2 ].y,
              r: 0.1, g: 0.1, b: 0.1, a: 1
            } );

            triangles.push( {
              x1: body.vertices[ 0 ].x, y1: body.vertices[ 0 ].y,
              x2: body.vertices[ 2 ].x, y2: body.vertices[ 2 ].y,
              x3: body.vertices[ 3 ].x, y3: body.vertices[ 3 ].y,
              r: 0.1, g: 0.1, b: 0.1, a: 1
            } );
          }
        }
      }

      addRectangle( -1000, -1000, 1000 + 25, 600 + 1000, 0.1, 0.1, 0.1, 0.3 );
      addRectangle( -1000, 600, 10000, 1000, 9 / 255, 46 / 255, 13 / 255, 1 );

      offset.x = -mrchompyScreenView.elements[ 0 ].bodies[ 0 ].position.x + this.layoutBounds.width / 2;
      titleNode.x = offset.x + 420;
      monsterNode.invalidatePaint();
    };

    // Key listeners
    // http://stackoverflow.com/questions/16089421/simplest-way-to-detect-keypresses-in-javascript
    function addEvent( element, eventName, callback ) {
      if ( element.addEventListener ) {
        element.addEventListener( eventName, callback, false );
      }
      else if ( element.attachEvent ) {
        element.attachEvent( "on" + eventName, callback );
      }
      else {
        element[ "on" + eventName ] = callback;
      }
    }

    var pressedKeys = {};
    addEvent( document, "keydown", function( e ) {
      var e = e || window.event;
      // use e.keyCode
      console.log( e.keyCode );
      pressedKeys[ e.keyCode ] = true;
    } );

    addEvent( document, "keyup", function( e ) {
      var e = e || window.event;
      // use e.keyCode
      console.log( e.keyCode );
      pressedKeys[ e.keyCode ] = false;
    } );

    var titleNode = new Image( title, {
      centerX: this.layoutBounds.centerX,
      top: 100
    } );
    this.addChild( titleNode );
  }

  return inherit( ScreenView, MrchompyScreenView, {} );
} );<commit_msg>Added tentacles<commit_after>// Copyright 2002-2015, University of Colorado Boulder

/**
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var ScreenView = require( 'JOIST/ScreenView' );
  var ResetAllButton = require( 'SCENERY_PHET/buttons/ResetAllButton' );
  var MonsterNode = require( 'MRCHOMPY/mrchompy/view/MonsterNode' );
  var Bounds2 = require( 'DOT/Bounds2' );
  var Vector2 = require( 'DOT/Vector2' );
  var title = require( 'image!MRCHOMPY/mrchompy.png' );
  var Image = require( 'SCENERY/nodes/Image' );

  /**
   * @param {MrchompyModel} mrchompyModel
   * @constructor
   */
  function MrchompyScreenView( mrchompyModel ) {

    ScreenView.call( this, {
      layoutBounds: new Bounds2( 0, 0, 1024, 618 )
    } );
    var mrchompyScreenView = this;

    var Matter = window.Matter;
    console.log( Matter );

    var Demo = {};
    Matter.Demo = Demo;

    // Matter aliases
    var Engine = Matter.Engine,
      World = Matter.World,
      Bodies = Matter.Bodies,
      Body = Matter.Body,
      Composite = Matter.Composite,
      Composites = Matter.Composites,
      Common = Matter.Common,
      Constraint = Matter.Constraint,
      Events = Matter.Events,
      Bounds = Matter.Bounds,
      Vector = Matter.Vector,
      Vertices = Matter.Vertices,
      MouseConstraint = Matter.MouseConstraint,
      Mouse = Matter.Mouse,
      Query = Matter.Query,
      Svg = Matter.Svg;

    var _isBrowser = true;

    var _engine,
      _runner,
      _gui,
      _inspector,
      _sceneName,
      _mouseConstraint,
      _sceneEvents = [],
      _useInspector = _isBrowser && window.location.hash.indexOf( '-inspect' ) !== -1,
      _isMobile = _isBrowser && /(ipad|iphone|ipod|android)/gi.test( navigator.userAgent ),
      _isAutomatedTest = !_isBrowser || window._phantom;

    // initialise the demo

    Demo.init = function() {
      // some example engine options
      var options = {
        positionIterations: 6,
        velocityIterations: 4,
        enableSleeping: false,
        metrics: { extended: true },
        render: {}
      };

      // create a Matter engine
      // NOTE: this is actually Matter.Engine.create(), see the aliases at top of this file
      var container = document.getElementById( 'canvas-container' );
      _engine = Engine.create( container, options );

      // engine reference for external use
      Matter.Demo._engine = _engine;

      // run the engine
      Engine.run( _engine );

      Demo.mixed();
    };

    // call init when the page has loaded fully

    if ( window.addEventListener ) {
      window.addEventListener( 'load', Demo.init );
    }
    else if ( window.attachEvent ) {
      window.attachEvent( 'load', Demo.init );
    }

    // each demo scene is set up in its own function, see below

    Demo.mixed = function() {
      var _world = _engine.world;

      _world.bounds = {
        min: {
          x: 0, y: 0
        },
        max: { x: 5000, y: 800 }
      };

      Demo.reset();

      var particleOptions = {
        friction: 0.05,
        frictionStatic: 0.1
      };

      var elements = [
        //xx, yy, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions
        Composites.softBody( 800, 0, 6, 6, 0, 0, true, 27, particleOptions ),
        //Composites.softBody( 250, 300, 8, 3, 0, 0, true, 15, particleOptions ),
        //Composites.softBody( 250, 400, 4, 4, 0, 0, true, 15, particleOptions ),
        Bodies.rectangle( 200, 100, 100, 100 )
      ];
      World.add( _world, elements );

      var groupId = Body.nextGroupId();

      var ropeA = Composites.stack( 600, 0, 5, 2, 10, 10, function( x, y, column, row ) {
        return Bodies.rectangle( x, y, 50, 20, { groupId: groupId } );
      } );

      Composites.chain( ropeA, 0.5, 0, -0.5, 0, { stiffness: 0.8, length: 2 } );
      Composite.add( ropeA, Constraint.create( {
        bodyA: elements[ 0 ].bodies[ 0 ],
        bodyB: ropeA.bodies[ ropeA.bodies.length - 1 ],
        stiffness: 1
      } ) );
      World.add( _world, ropeA );
      elements = elements.concat( ropeA );

      groupId = Body.nextGroupId();

      var ropeB = Composites.stack( 1000, 0, 5, 2, 10, 10, function( x, y, column, row ) {
        return Bodies.rectangle( x, y, 50, 20, { groupId: groupId } );
      } );

      Composites.chain( ropeB, 0.5, 0, -0.5, 0, { stiffness: 0.8, length: 2 } );
      Composite.add( ropeB, Constraint.create( {
        bodyA: elements[ 0 ].bodies[ 5 ],
        bodyB: ropeB.bodies[ 0 ],
        stiffness: 1
      } ) );

      World.add( _world, ropeB );

      elements = elements.concat( ropeB );

      mrchompyScreenView.elements = elements;
    };

    Demo.reset = function() {
      var _world = _engine.world, i;

      World.clear( _world );
      Engine.clear( _engine );

      // clear scene graph (if defined in controller)
      if ( _engine.render ) {
        var renderController = _engine.render.controller;
        if ( renderController && renderController.clear ) {
          renderController.clear( _engine.render );
        }
      }

      // clear all scene events
      if ( _engine.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _engine, _sceneEvents[ i ] );
        }
      }

      if ( _mouseConstraint && _mouseConstraint.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _mouseConstraint, _sceneEvents[ i ] );
        }
      }

      if ( _world.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _world, _sceneEvents[ i ] );
        }
      }

      if ( _runner && _runner.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _runner, _sceneEvents[ i ] );
        }
      }

      if ( _engine.render && _engine.render.events ) {
        for ( i = 0; i < _sceneEvents.length; i++ ) {
          Events.off( _engine.render, _sceneEvents[ i ] );
        }
      }

      _sceneEvents = [];

      // reset id pool
      Common._nextId = 0;

      // reset random seed
      Common._seed = 0;

      _engine.enableSleeping = false;
      _engine.world.gravity.y = 1;
      _engine.world.gravity.x = 0;
      _engine.timing.timeScale = 1;

      var offset = 5;
      World.add( _world, [
        //Bodies.rectangle( 400, -offset, 800.5 + 2 * offset, 50.5, { isStatic: true } ),
        Bodies.rectangle( 400, 600 + offset, 10000, 50.5, { isStatic: true } ),
        //Bodies.rectangle( 800 + offset, 300, 50.5, 600.5 + 2 * offset, { isStatic: true } ),
        Bodies.rectangle( -offset, 300, 50.5, 600.5 + 2 * offset, { isStatic: true } )
      ] );
    };

    Demo.init();

    var triangles = [ { x1: 0, y1: 0, x2: 100, y2: 0, x3: 50, y3: 50, r: 1, g: 0, b: 0, a: 1 } ];
    var offset = new Vector2( 0, 0 );
    var monsterNode = new MonsterNode( this.layoutBounds.width, this.layoutBounds.height, triangles, offset );
    this.addChild( monsterNode );

    this.events.on( 'layoutFinished', function( dx, dy, width, height ) {
        monsterNode.setCanvasBounds( new Bounds2( -dx, -dy, width - dx, height - dy ) );
      }
    );

    var addRectangle = function( x, y, width, height, r, g, b, a ) {
      triangles.push( { x1: x, y1: y, x2: x + width, y2: y, x3: x + width, y3: y + height, r: r, g: g, b: b, a: a } );
      triangles.push( {
        x1: x,
        y1: y,
        x2: x,
        y2: y + height,
        x3: x + width,
        y3: y + height,
        r: r,
        g: g,
        b: b,
        a: a
      } );
    };

    this.step = function( dt ) {

      console.log( _engine.pairs.collisionActive.length );
      var force = 0.05;
      if ( pressedKeys[ 39 ] ) {

        // right
        console.log( 'right' );
        Matter.Body.applyForce( mrchompyScreenView.elements[ 0 ].bodies[ 30 ], { x: 0, y: 0 }, { x: force / 2, y: 0 } );
        Matter.Body.applyForce( mrchompyScreenView.elements[ 0 ].bodies[ 35 ], { x: 0, y: 0 }, { x: force / 2, y: 0 } );
      }
      if ( pressedKeys[ 37 ] ) {
        Matter.Body.applyForce( mrchompyScreenView.elements[ 0 ].bodies[ 30 ], { x: 0, y: 0 }, {
          x: -force / 2,
          y: 0
        } );
        Matter.Body.applyForce( mrchompyScreenView.elements[ 0 ].bodies[ 35 ], { x: 0, y: 0 }, {
          x: -force / 2,
          y: 0
        } );
      }
      if ( pressedKeys[ 38 ] && _engine.pairs.collisionActive.length > 35 ) {
        for ( var i = 0; i < mrchompyScreenView.elements[ 0 ].bodies.length; i++ ) {
          var b = mrchompyScreenView.elements[ 0 ].bodies[ i ];
          Matter.Body.applyForce( b, { x: 0, y: 0 }, {
            x: 0,
            y: -0.2 / mrchompyScreenView.elements[ 0 ].bodies.length
          } );
        }
      }
      triangles.length = 0;
      for ( var i = 0; i < mrchompyScreenView.elements.length; i++ ) {
        var element = mrchompyScreenView.elements[ i ];
        if ( element.bodies ) {
          for ( var k = 0; k < element.bodies.length; k++ ) {
            var body = element.bodies[ k ];
            console.log( 'v', body.vertices.length );

            triangles.push( {
              x1: body.position.x, y1: body.position.y,
              x2: body.position.x + 35, y2: body.position.y,
              x3: body.position.x, y3: body.position.y + 35,
              r: k === 35 ? 1 : 0.1, g: 0.1, b: 0.1, a: 1
            } );
          }
        }
        else {
          if ( element.label === 'Rectangle Body' ) {
            var body = element;

            triangles.push( {
              x1: body.vertices[ 0 ].x, y1: body.vertices[ 0 ].y,
              x2: body.vertices[ 1 ].x, y2: body.vertices[ 1 ].y,
              x3: body.vertices[ 2 ].x, y3: body.vertices[ 2 ].y,
              r: 0.1, g: 0.1, b: 0.1, a: 1
            } );

            triangles.push( {
              x1: body.vertices[ 0 ].x, y1: body.vertices[ 0 ].y,
              x2: body.vertices[ 2 ].x, y2: body.vertices[ 2 ].y,
              x3: body.vertices[ 3 ].x, y3: body.vertices[ 3 ].y,
              r: 0.1, g: 0.1, b: 0.1, a: 1
            } );
          }
        }
      }

      addRectangle( -1000, -1000, 1000 + 25, 600 + 1000, 0.1, 0.1, 0.1, 0.3 );
      addRectangle( -1000, 600, 10000, 1000, 9 / 255, 46 / 255, 13 / 255, 1 );

      offset.x = -mrchompyScreenView.elements[ 0 ].bodies[ 0 ].position.x + this.layoutBounds.width / 2;
      titleNode.x = offset.x + 420;
      monsterNode.invalidatePaint();
    };

    // Key listeners
    // http://stackoverflow.com/questions/16089421/simplest-way-to-detect-keypresses-in-javascript
    function addEvent( element, eventName, callback ) {
      if ( element.addEventListener ) {
        element.addEventListener( eventName, callback, false );
      }
      else if ( element.attachEvent ) {
        element.attachEvent( "on" + eventName, callback );
      }
      else {
        element[ "on" + eventName ] = callback;
      }
    }

    var pressedKeys = {};
    addEvent( document, "keydown", function( e ) {
      var e = e || window.event;
      // use e.keyCode
      console.log( e.keyCode );
      pressedKeys[ e.keyCode ] = true;
    } );

    addEvent( document, "keyup", function( e ) {
      var e = e || window.event;
      // use e.keyCode
      console.log( e.keyCode );
      pressedKeys[ e.keyCode ] = false;
    } );

    var titleNode = new Image( title, {
      centerX: this.layoutBounds.centerX,
      top: 100
    } );
    this.addChild( titleNode );
  }

  return inherit( ScreenView, MrchompyScreenView, {} );
} );<|endoftext|>


<commit_before>
// set up environment
$(document).ready(function(){
    var evt = $.Event('imready');

    // Fetch my data from server
    $get('/mydata', function(data){

        // if not logged in, redirect to login
        if (!data) return window.location.href = '/login';
        evt.myObj = data;

        // show page
        $(window).trigger(evt);
    });
});

// upon environment set up
$(window).on('imready', function(im){

    $("button").attr('disabled', 'disabled').click(function () {
        // alert("sfd");
        // Commands.exec(CommandName.rollDice, CommandsData.rollDice());
        /**
        let input1 = parseInt($("input[name='input1']").val());
        let input2 = parseInt($("input[name='input2']").val());
        Commands.exec(CommandName.buildEstablishment, CommandsData.buildEstablishment(input1, 1));**/
    });
    //test

    let CircularJSON = window.CircularJSON;

    window.myObj = im.myObj;
    //console.log(window.myObj);
    let roomId = window.location.pathname.split("/").pop();

    // parse a fake room data just for test
    //var room = window.room = {users: []};

    // template for user
    var fakeUser = window.fakeUser = {
        resourcesAndCommodities: {"Lumber":0,"Brick":0,"Grain":0,"Ore":0,"Wool":0,"Gold":2,"Cloth":0,"Coin":0,"Paper":0}
    };

    // on page load, join room
    sock.emit('JOIN_ROOM', roomId);

    //test data
    //for now, assume player choose this map
    let mapConfig = {'scenario':'Heading For New Shores'};
    sock.emit('MAP_CONFIG', mapConfig);

    // when sock disconnects and reconnects, join room again
    sock.on('reconnect', function(){
        sock.emit('JOIN_ROOM', roomId);
    });

    // upon successfully joined room, server will send back a message
    sock.on('JOIN_ROOM_SUCCESS', function(msg){
        let room = CircularJSON.parse(msg);
        app.room = room;
        app.setMy();
        console.log(room);
    });

    sock.on('NEW_PLAYER_JOINED', function (msg) {
        let room = CircularJSON.parse(msg);
        app.room = room;
       //alert('NEW_PLAYER_JOINED');
       //change ui
    });

    sock.on('GAME_START', function (msg) {
        alert('Game start');
        //entry point for max's code

    });

    sock.on('TAKE_TURN', function (msg) {
        alert('Take turn');
        $("button").removeAttr('disabled');
    });

    // ----------------------------- View Layer ----------------------------- //

    var app = window.app = new Vue({
        el: '#page',
        data: {
            me: myObj,
            my: fakeUser,
            room: room,
            logs: [
                { user: null, action: 'The game starts.', system: true },
                { user: 'Yuan', action: 'places a city.', system: true },
                { user: 'jack', action: 'places a road.', system: true },
                { user: 'Max', action: "stop cheating man", system: false },
                { user: 'Emol', action: "i aint cheating -_-", system: false }
            ]
        },
        mounted: function(){
            $('body').showV();
            adjustUI();
            console.log('mounted');
        },
        updated: function(){
            console.log('updated');
            adjustUI();
        },
        filters: {
            capitalize: beautify.capitalize
        },
        methods: {
            // make 'my' point to my object inside users
            setMy: function(){
                var my = this.room.users[myObj.username];
                if (my) this.my = my;
            },
            // save match
            save: function(){
                Toast.show('Saved!');
            },

            // continue previously saved match
            open: function(){
                Toast.show('Open');
            },

            // quit match
            quit: function(){
                Toast.show('Match ended!');
            },

            // append to log
            log: function(user, action, system){
                this.logs.push({ user, action, system });
                NextTick(function(){
                    $('#log .msgs').scrollTop($('#log .msgs')[0].scrollHeight);
                });
            },

            // chat in room
            sendMessage: function(){
                var content = $('#log input').val();
                sock.emit('send-message', content);
                $('#log input').val('');
            },

            // roll dice
            rollDice: function(){
                Commands.rollDice();
            }
        }
    });

    // adjust UI when resize screen
    function adjustUI(){
        // adjust system log height
        $('#log').outerHeight($('#right-screen').height() - $('#users').outerHeight() - $('#match-opts').outerHeight());
    }
    $(window).resize(adjustUI);

    // receive message
    sock.on('receive-message', function(msg){
        app.log(msg.username, msg.content, false);
    });

    //game stuff, maybe move to another js file later
    //here are just tests, call the functions when the certain button is pressed.
    //sock.emit('rollDice', roomId);

    //sock.emit('LOL');

});<commit_msg>map helper function in client side<commit_after>
// set up environment
$(document).ready(function(){
    var evt = $.Event('imready');

    // Fetch my data from server
    $get('/mydata', function(data){

        // if not logged in, redirect to login
        if (!data) return window.location.href = '/login';
        evt.myObj = data;

        // show page
        $(window).trigger(evt);
    });
});

// upon environment set up
$(window).on('imready', function(im){

    $("button").attr('disabled', 'disabled').click(function () {
        // alert("sfd");
        // Commands.exec(CommandName.rollDice, CommandsData.rollDice());
        /**
        let input1 = parseInt($("input[name='input1']").val());
        let input2 = parseInt($("input[name='input2']").val());
        Commands.exec(CommandName.buildEstablishment, CommandsData.buildEstablishment(input1, 1));**/
    });
    //test

    let CircularJSON = window.CircularJSON;

    window.myObj = im.myObj;
    //console.log(window.myObj);
    let roomId = window.location.pathname.split("/").pop();

    // parse a fake room data just for test
    //var room = window.room = {users: []};

    // template for user
    var fakeUser = window.fakeUser = {
        resourcesAndCommodities: {"Lumber":0,"Brick":0,"Grain":0,"Ore":0,"Wool":0,"Gold":2,"Cloth":0,"Coin":0,"Paper":0}
    };

    // on page load, join room
    sock.emit('JOIN_ROOM', roomId);

    //test data
    //for now, assume player choose this map
    let mapConfig = {'scenario':'Heading For New Shores'};
    sock.emit('MAP_CONFIG', mapConfig);

    // when sock disconnects and reconnects, join room again
    sock.on('reconnect', function(){
        sock.emit('JOIN_ROOM', roomId);
    });

    // upon successfully joined room, server will send back a message
    sock.on('JOIN_ROOM_SUCCESS', function(msg){
        let room = CircularJSON.parse(msg);
        app.room = room;
        app.setMy();
        console.log(room);
    });

    sock.on('NEW_PLAYER_JOINED', function (msg) {
        let room = CircularJSON.parse(msg);
        app.room = room;
       //alert('NEW_PLAYER_JOINED');
       //change ui
    });

    sock.on('GAME_START', function (msg) {
        alert('Game start');
        //entry point for max's code

    });

    sock.on('TAKE_TURN', function (msg) {
        alert('Take turn');
        $("button").removeAttr('disabled');
    });

    // ----------------------------- View Layer ----------------------------- //

    var app = window.app = new Vue({
        el: '#page',
        data: {
            me: myObj,
            my: fakeUser,
            room: room,
            logs: [
                { user: null, action: 'The game starts.', system: true },
                { user: 'Yuan', action: 'places a city.', system: true },
                { user: 'jack', action: 'places a road.', system: true },
                { user: 'Max', action: "stop cheating man", system: false },
                { user: 'Emol', action: "i aint cheating -_-", system: false }
            ]
        },
        mounted: function(){
            $('body').showV();
            adjustUI();
            console.log('mounted');
        },
        updated: function(){
            console.log('updated');
            adjustUI();
        },
        filters: {
            capitalize: beautify.capitalize
        },
        methods: {
            // make 'my' point to my object inside users
            setMy: function(){
                var my = this.room.users[myObj.username];
                if (my) this.my = my;
            },
            // save match
            save: function(){
                Toast.show('Saved!');
            },

            // continue previously saved match
            open: function(){
                Toast.show('Open');
            },

            // quit match
            quit: function(){
                Toast.show('Match ended!');
            },

            // append to log
            log: function(user, action, system){
                this.logs.push({ user, action, system });
                NextTick(function(){
                    $('#log .msgs').scrollTop($('#log .msgs')[0].scrollHeight);
                });
            },

            // chat in room
            sendMessage: function(){
                var content = $('#log input').val();
                sock.emit('send-message', content);
                $('#log input').val('');
            },

            // roll dice
            rollDice: function(){
                Commands.rollDice();
            },

            endTurn: function () {
            }
        }
    });

    // adjust UI when resize screen
    function adjustUI(){
        // adjust system log height
        $('#log').outerHeight($('#right-screen').height() - $('#users').outerHeight() - $('#match-opts').outerHeight());
    }
    $(window).resize(adjustUI);

    // receive message
    sock.on('receive-message', function(msg){
        app.log(msg.username, msg.content, false);
    });

    //game stuff, maybe move to another js file later
    //here are just tests, call the functions when the certain button is pressed.
    //sock.emit('rollDice', roomId);

    //sock.emit('LOL');

});<|endoftext|>


<commit_before>console.log('show: coming online');

$(function(){

  console.log('show DOM: loaded');

  // Ajax Share List
  // Catch the default submit event for the share list form and then
  // make an ajax call to the share list route and update the DOM
  // to reflect the change
  $('form.fmShareList').on('submit', function(e) {
    e.preventDefault();
    var form = $(this);
    var method = form.attr('method');
    var url = form.attr('action');
    var data = form.serialize();
    console.log('Method:', method);
    console.log('Action:', url);
    console.log('Form Data:', data);

    $.ajax({
      method: method,
      url: url,
      data: data
    }).done(function(data) {
      if (!data.errors) {
        console.log('Save complete', data);
        if(method==='POST') {
          $('#fmShareList').hide();
          $('#ShareDesc').hide();
          $('#fmUnShareList').show();
          $('#unShareDesc').show();
          $('#commentscol').show();
          var editor = new EpicEditor(opts).load();
        } else {
          $('#fmShareList').show();
          $('#ShareDesc').show();
          $('#fmUnShareList').hide();
          $('#unShareDesc').hide();
          $('#commentscol').fadeOut('slow', function() {});
          $('.comment.well').fadeOut('slow', function() {
            $(this).remove();
          });
        }
      } else {
        alert(data.message);
        // editor.edit();
        // editor.focus();
      }
    })
  })

  // Load EpicEditor
  var opts = {
    container: 'epiceditor',
    textarea: comment,
    basePath: '../../',
    clientSideStorage: false,
    localStorageName: 'epiceditor',
    useNativeFullscreen: true,
    parser: marked,
    file: {
      name: 'epiceditor',
      defaultContent: '',
      autoSave: 100
    },
    theme: {
      base: '/themes/base/epiceditor.css',
      preview: '/themes/preview/github.css',
      editor: '/themes/editor/epic-light.css'
    },
    button: {
      preview: true,
      fullscreen: false,
      bar: true
    },
    focusOnLoad: true,
    shortcut: {
      modifier: 18,
      fullscreen: 70,
      preview: 80
    },
    string: {
      togglePreview: 'Toggle Preview Mode',
      toggleEdit: 'Toggle Edit Mode',
      toggleFullscreen: 'Enter Fullscreen'
    },
    autogrow: {
      minHeight: 150,
      maxHeight: 400,
      scroll: false
    }
  }

  var editor = new EpicEditor(opts).load();

  // AJAX Add Comments
  $('form.add-comment').on('submit', function(e) {
    e.preventDefault();

    var postUrl = $(this).attr('action');
    var twitter_list_id = $('form.add-comment #twitter_list_id').val();
    // If you don't preview the editor, sometimes the innerHTML doesn't get
    // updated
    editor.preview();
    var comment = editor.getElement('previewer').body.innerHTML
    var postData = {
                      twitter_list_id: twitter_list_id,
                      comment: comment
                    }

    $.ajax({
      method: 'POST',
      url: postUrl,
      data: postData
    }).done(function(data) {

      if (!data.errors) {
        console.log('Comment saved', data);

        // Create new div and append it here
        var newDiv = $('
' +
                      'You' +
                      'Just Now' +
                      '
' + comment + '
');
        newDiv.prependTo('div.comments');
        newDiv.show('slow', function() {
          editor.edit();
          editor.getElement('editor').body.innerHTML = '';
        });
      } else {
        alert(data.message);
        editor.edit();
        editor.focus();
      }
    })
  })

})
<commit_msg>Really fix issue with epic editor not loading on share list<commit_after>console.log('show: coming online');

$(function(){

  var editor;

  console.log('show DOM: loaded');

    // Load EpicEditor
  var loadEdit = function() {
    var opts = {
      container: 'epiceditor',
      textarea: comment,
      basePath: '../../',
      clientSideStorage: false,
      localStorageName: 'epiceditor',
      useNativeFullscreen: true,
      parser: marked,
      file: {
        name: 'epiceditor',
        defaultContent: '',
        autoSave: 100
      },
      theme: {
        base: '/themes/base/epiceditor.css',
        preview: '/themes/preview/github.css',
        editor: '/themes/editor/epic-light.css'
      },
      button: {
        preview: true,
        fullscreen: false,
        bar: true
      },
      focusOnLoad: true,
      shortcut: {
        modifier: 18,
        fullscreen: 70,
        preview: 80
      },
      string: {
        togglePreview: 'Toggle Preview Mode',
        toggleEdit: 'Toggle Edit Mode',
        toggleFullscreen: 'Enter Fullscreen'
      },
      autogrow: {
        minHeight: 150,
        maxHeight: 400,
        scroll: false
      }
    }

    editor = new EpicEditor(opts).load();
  }

  // Ajax Share List
  // Catch the default submit event for the share list form and then
  // make an ajax call to the share list route and update the DOM
  // to reflect the change
  $('form.fmShareList').on('submit', function(e) {
    e.preventDefault();
    var form = $(this);
    var method = form.attr('method');
    var url = form.attr('action');
    var data = form.serialize();
    console.log('Method:', method);
    console.log('Action:', url);
    console.log('Form Data:', data);

    $.ajax({
      method: method,
      url: url,
      data: data
    }).done(function(data) {
      if (!data.errors) {
        console.log('Save complete', data);
        if(method==='POST') {
          $('#fmShareList').hide();
          $('#ShareDesc').hide();
          $('#fmUnShareList').show();
          $('#unShareDesc').show();
          $('#commentscol').show();
          // var editor = new EpicEditor(opts).load();
          // editor.load();
          loadEdit();
        } else {
          $('#fmShareList').show();
          $('#ShareDesc').show();
          $('#fmUnShareList').hide();
          $('#unShareDesc').hide();
          $('#commentscol').fadeOut('slow', function() {});
          $('.comment.well').fadeOut('slow', function() {
            $(this).remove();
          });
        }
      } else {
        alert(data.message);
        // editor.edit();
        // editor.focus();
      }
    })
  })

  loadEdit();

  // AJAX Add Comments
  $('form.add-comment').on('submit', function(e) {
    e.preventDefault();

    var postUrl = $(this).attr('action');
    var twitter_list_id = $('form.add-comment #twitter_list_id').val();
    // If you don't preview the editor, sometimes the innerHTML doesn't get
    // updated
    editor.preview();
    var comment = editor.getElement('previewer').body.innerHTML
    var postData = {
                      twitter_list_id: twitter_list_id,
                      comment: comment
                    }

    $.ajax({
      method: 'POST',
      url: postUrl,
      data: postData
    }).done(function(data) {

      if (!data.errors) {
        console.log('Comment saved', data);

        // Create new div and append it here
        var newDiv = $('
' +
                      'You' +
                      'Just Now' +
                      '
' + comment + '
');
        newDiv.prependTo('div.comments');
        newDiv.show('slow', function() {
          editor.edit();
          editor.getElement('editor').body.innerHTML = '';
        });
      } else {
        alert(data.message);
        editor.edit();
        editor.focus();
      }
    })
  })

})
<|endoftext|>


<commit_before>
$(document).ready(function() {
  var w = window,
      d = document,
      e = d.documentElement,
      g = d.getElementsByTagName('body')[0],
      x = w.innerWidth || e.clientWidth || g.clientWidth,
      y = w.innerHeight|| e.clientHeight|| g.clientHeight;

  window.viewport = {
      width: x, height: y
  };
  console.log("Viewport: w=" + viewport.width + ", h=" + viewport.height);
});

/*
 * Exploring the various ways of rendering the images:
 *  - series of img tags
 *  - series of canvas tags
 *  - single canvas, add all photos to it
 */
var once = 1;

function render_to_1canvas(im, hscale, alpha) {
  var canvas;
  if (once-- > 0) {
    canvas = document.createElement('canvas');
    canvas.id = 'c1';
    var canvases = document.getElementById("canvases");
    canvases.appendChild(canvas);
    canvas.width  = viewport.width;
    canvas.height = viewport.height;
  } else {
    canvas = document.getElementById("c1");
  }
  var ctx = canvas.getContext('2d');
  // alpha (0-1): conversion from opacity (0-100 percent)
  ctx.globalAlpha = alpha;

  // horizontal scaling
  ctx.scale(hscale, 1.0);

  ctx.drawImage(im,0,0, viewport.width, viewport.height);
}

function render_canvas(img, hstretch, opacity) {
  $('#hidden-images').append(img);
  var alpha = (opacity / 100.0);
  render_to_1canvas(img, hstretch, alpha);
}

var ImagesView = Backbone.View.extend({

  initialize: function(options) {
    this.collection.on("add", this.onAdd);
    this.collection.on("remove", this.onRemove);
    this.collection.on("update", this.onUpdate);
    this.__whoami = 'ImagesView'; //debugging
  },

  onAdd: function(img_model) {
    var self = this;
    var vp_width = viewport.width;
    var url = img_model.get('proxy_url');
    var iid = img_model.get('image_id'); // flickr image id
    var eid = img_model.get('eqid');
    var depth = img_model.get('depth');
    var mag = img_model.get('mag');
    console.log("add-image: iid=" +iid +" for " +img_model.get('eqid') +": " + depth);

    /*
     * Apply effects to the image
     */

    // depth translates to blur, from 0-800 range to 0.0-3.0
    var blur_by_depth = (depth / 200.0);

    // mag(nitude) translates to opacity & horizontal-stretch
    //   ranges:: mag: 0-10, opacity: 10-90 percent, hstretch: 1.0-3.0
    //var opacity_by_mag = (parseFloat(img_model.get('mag')) / 12.0);
    var opacity_by_mag = Math.floor(8.0 * mag + 10.0); // percent: 10-90 range
    var hstretch_by_mag = (mag / 5.0) + 1.0;

    var img = new Image();
    img.onload = function(ev) {
      var img_elem = ev.srcElement; // still need this here?
      Pixastic.process(img, "blurfast", {amount: blur_by_depth});
      render_canvas(img_elem, hstretch_by_mag, opacity_by_mag);
    }
    // w/jquery set img element's attributes before it is loaded
    var jq_img = $(img);
    jq_img.attr({id: eid});
    if (vp_width > 50) {
      jq_img.attr({width: vp_width});
    }
    jq_img.css({opacity: opacity_by_mag});
    img.src = url;
    console.log(" *onAdd-image(queued): " + eid);
  },

  onRemove: function(img_model) {
    var eid = img_model.get('eqid');
    console.log(" *onRemove-image: " + eid);
    $('#' + eid).remove();
  },

  onUpdate: function(img_model)  {
    var eid = img_model.get('eqid');
    console.log(" *onUpdate-image: " + eid);
  },

});

<commit_msg>refactor canvas rendering methods into view class<commit_after>
$(document).ready(function() {
  var w = window,
      d = document,
      e = d.documentElement,
      g = d.getElementsByTagName('body')[0],
      x = w.innerWidth || e.clientWidth || g.clientWidth,
      y = w.innerHeight|| e.clientHeight|| g.clientHeight;

  window.viewport = {
      width: x, height: y
  };
  console.log("Viewport: w=" + viewport.width + ", h=" + viewport.height);
});

/*
 * Exploring the various ways of rendering the images:
 *  - series of img tags
 *  - series of canvas tags
 *  - single canvas, add all photos to it
 */

// moving within ImagesView
var xoncex = 1;

// moving within ImagesView
function xrender_to_1canvasx(im, hscale, alpha) {
  var canvas;
  if (once-- > 0) {
    canvas = document.createElement('canvas');
    canvas.id = 'c1';
    var canvases = document.getElementById("canvases");
    canvases.appendChild(canvas);
    canvas.width  = viewport.width;
    canvas.height = viewport.height;
  } else {
    canvas = document.getElementById("c1");
  }
  var ctx = canvas.getContext('2d');
  // alpha (0-1): conversion from opacity (0-100 percent)
  ctx.globalAlpha = alpha;
  // horizontal scaling
  ctx.scale(hscale, 1.0);
  ctx.drawImage(im,0,0, viewport.width, viewport.height);
}

// moving within ImagesView
function xrender_canvasx(img, hstretch, opacity) {
  $('#hidden-images').append(img);
  var alpha = (opacity / 100.0);
  render_to_1canvas(img, hstretch, alpha);
}

var ImagesView = Backbone.View.extend({

  initialize: function(options) {
    this.collection.on("add", this.onAdd, this);
    this.collection.on("remove", this.onRemove, this);
    this.collection.on("update", this.onUpdate, this);
    this.__whoami = 'ImagesView'; //debugging
    this.once = 1;
  },

  render_to_1canvas: function(im, hscale, alpha) {
    var self = this;
    var canvas;

    // TODO: refactor this logic into initialize
    if (self.once-- > 0) {
      canvas = document.createElement('canvas');
      canvas.id = 'c1';
      var canvases = document.getElementById("canvases");
      canvases.appendChild(canvas);
      canvas.width  = viewport.width;
      canvas.height = viewport.height;
    } else {
      canvas = document.getElementById("c1");
    }
    var ctx = canvas.getContext('2d');
    // alpha (0-1): conversion from opacity (0-100 percent)
    ctx.globalAlpha = alpha;
    // horizontal scaling
    ctx.scale(hscale, 1.0);
    ctx.drawImage(im,0,0, viewport.width, viewport.height);
  },

  render_canvas: function(img, hstretch, opacity) {
    var self = this;
    $('#hidden-images').append(img);
    var alpha = (opacity / 100.0);
    self.render_to_1canvas(img, hstretch, alpha);
  },

  onAdd: function(img_model) {
    var self = this;
    var vp_width = viewport.width;
    var url = img_model.get('proxy_url');
    var iid = img_model.get('image_id'); // flickr image id
    var eid = img_model.get('eqid');
    var depth = img_model.get('depth');
    var mag = img_model.get('mag');
    console.log("add-image: iid=" +iid +" for " +img_model.get('eqid') +": " + depth);

    /*
     * Apply effects to the image
     */

    // depth translates to blur, from 0-800 range to 0.0-3.0
    var blur_by_depth = (depth / 200.0);

    // mag(nitude) translates to opacity & horizontal-stretch
    //   ranges:: mag: 0-10, opacity: 10-90 percent, hstretch: 1.0-3.0
    //var opacity_by_mag = (parseFloat(img_model.get('mag')) / 12.0);
    var opacity_by_mag = Math.floor(8.0 * mag + 10.0); // percent: 10-90 range
    var hstretch_by_mag = (mag / 5.0) + 1.0;

    var img = new Image();
    img.onload = function(ev, alt) {
      var img_elem = ev.srcElement; // still need this here?
      Pixastic.process(img, "blurfast", {amount: blur_by_depth});
      self.render_canvas(img_elem, hstretch_by_mag, opacity_by_mag);
    }
    // w/jquery set img element's attributes before it is loaded
    var jq_img = $(img);
    jq_img.attr({id: eid});
    if (vp_width > 50) {
      jq_img.attr({width: vp_width});
    }
    jq_img.css({opacity: opacity_by_mag});
    img.src = url;
    console.log(" *onAdd-image(queued): " + eid);
  },

  onRemove: function(img_model) {
    var eid = img_model.get('eqid');
    console.log(" *onRemove-image: " + eid);
    $('#' + eid).remove();
  },

  onUpdate: function(img_model)  {
    var eid = img_model.get('eqid');
    console.log(" *onUpdate-image: " + eid);
  },

});

<|endoftext|>


<commit_before>d3plus.apps.tree_map = {}
d3plus.apps.tree_map.data = "nested";
d3plus.apps.tree_map.requirements = ["size"];
d3plus.apps.tree_map.tooltip = "follow"
d3plus.apps.tree_map.shapes = ["square"];

d3plus.apps.tree_map.draw = function(vars) {

  var data = d3.layout.treemap()
    .round(false)
    .size([vars.app_width, vars.app_height])
    .children(function(d) { return d.children; })
    .padding(1)
    .sort(function(a, b) { return a.value - b.value; })
    .value(function(d) { return d3plus.variable.value(vars,d,vars.size.key); })
    .nodes({"name":"root", "children": vars.data.app})
    .filter(function(d) {
      return !d.children && d.area;
    })

  if (data.length) {

    var root = data[0]
    while (root.parent) {
      root = root.parent
    }

    data.forEach(function(d){
      d.d3plus.x = d.x+d.dx/2
      d.d3plus.y = d.y+d.dy/2
      d.d3plus.width = d.dx
      d.d3plus.height = d.dy
      d.d3plus.share = d.value/root.value
    })

  }

  return data

}
<commit_msg>moved grouping function inside of tree_map<commit_after>d3plus.apps.tree_map = {}
d3plus.apps.tree_map.data = "grouped";
d3plus.apps.tree_map.requirements = ["size"];
d3plus.apps.tree_map.tooltip = "follow"
d3plus.apps.tree_map.shapes = ["square"];

d3plus.apps.tree_map.draw = function(vars) {

  var grouped_data = d3.nest()

  vars.id.nesting.forEach(function(n,i){
    if (i < vars.depth.value) {
      grouped_data.key(function(d){return d[n]})
    }
  })

  grouped_data = grouped_data.entries(vars.data.app)

  var data = d3.layout.treemap()
    .round(true)
    .size([vars.app_width, vars.app_height])
    .children(function(d) { return d.values; })
    .padding(1)
    .sort(function(a, b) { return a.value - b.value; })
    .value(function(d) { return d3plus.variable.value(vars,d,vars.size.key); })
    .nodes({"name":"root", "values": grouped_data})
    .filter(function(d) {
      return !d.values && d.area;
    })

  if (data.length) {

    var root = data[0]
    while (root.parent) {
      root = root.parent
    }

    data.forEach(function(d){
      d.d3plus.x = d.x+d.dx/2
      d.d3plus.y = d.y+d.dy/2
      d.d3plus.width = d.dx
      d.d3plus.height = d.dy
      d.d3plus.share = d.value/root.value
    })

  }

  return data

}
<|endoftext|>


<commit_before>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe(FILL_ME_IN);
    expect(overrideMessage()).toBe(FILL_ME_IN);
    expect(message).toBe(FILL_ME_IN);
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe(FILL_ME_IN);
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(FILL_ME_IN);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<commit_msg>COMPLETE: AboutFunctions - 'should know internal variables override outer variables'<commit_after>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe("Outer");
    expect(overrideMessage()).toBe("Inner");
    expect(message).toBe("Outer");
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe(FILL_ME_IN);
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(FILL_ME_IN);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<|endoftext|>