diff --git a/build/matter.js b/build/matter.js index a343bcf..4864601 100644 --- a/build/matter.js +++ b/build/matter.js @@ -1,5 +1,5 @@ /** -* matter.js edge-master 2015-07-05 +* matter.js edge-master 2015-08-13 * http://brm.io/matter-js/ * License: MIT */ @@ -4314,7 +4314,7 @@ var Common = {}; /** * The `Matter.Engine` module contains methods for creating and manipulating engines. -* An engine is a controller that manages updating and rendering the simulation of the world. +* An engine is a controller that manages updating the simulation of the world. * See `Matter.Runner` for an optional game loop utility. * * See [Demo.js](https://github.com/liabru/matter-js/blob/master/demo/js/Demo.js) @@ -4327,9 +4327,6 @@ var Engine = {}; (function() { - var _fps = 60, - _delta = 1000 / _fps; - /** * Creates a new engine. The options parameter is an object that specifies any properties you wish to override the defaults. * All properties have default values, and many are pre-calculated automatically based on other properties. @@ -4346,22 +4343,14 @@ var Engine = {}; element = Common.isElement(element) ? element : null; var defaults = { - enabled: true, positionIterations: 6, velocityIterations: 4, constraintIterations: 2, enableSleeping: false, events: [], timing: { - fps: _fps, timestamp: 0, - delta: _delta, - correction: 1, - deltaMin: 1000 / _fps, - deltaMax: 1000 / (_fps * 0.5), - timeScale: 1, - isFixed: false, - frameRequestId: 0 + timeScale: 1 }, broadphase: { controller: Grid @@ -4392,7 +4381,13 @@ var Engine = {}; }; /** - * Moves the simulation forward in time by `delta` ms. + * Moves the simulation forward in time by `delta` ms. + * The `correction` argument is an optional `Number` that specifies the time correction factor to apply to the update. + * This can help improve the accuracy of the simulation in cases where `delta` is changing between updates. + * The value of `correction` is defined as `delta / lastDelta`, i.e. the percentage change of `delta` over the last step. + * Therefore the value is always `1` (no correction) when `delta` constant (or when no correction is desired, which is the default). + * See the paper on Time Corrected Verlet for more information. + * * Triggers `beforeUpdate` and `afterUpdate` events. * Triggers `collisionStart`, `collisionActive` and `collisionEnd` events. * @method update @@ -4411,11 +4406,10 @@ var Engine = {}; // increment timestamp timing.timestamp += delta * timing.timeScale; - timing.correction = correction; // create an event object var event = { - timestamp: engine.timing.timestamp + timestamp: timing.timestamp }; Events.trigger(engine, 'beforeUpdate', event); @@ -4504,22 +4498,6 @@ var Engine = {}; return engine; }; - - /** - * Renders the world by calling its defined renderer `engine.render.controller`. Triggers `beforeRender` and `afterRender` events. - * @method render - * @param {engine} engine - */ - Engine.render = function(engine) { - // create an event object - var event = { - timestamp: engine.timing.timestamp - }; - - Events.trigger(engine, 'beforeRender', event); - engine.render.controller.world(engine); - Events.trigger(engine, 'afterRender', event); - }; /** * Merges two engines by keeping the configuration of `engineA` but replacing the world with the one from `engineB`. @@ -4629,38 +4607,12 @@ var Engine = {}; * @param {engine} engine */ - /* - * - * Events Documentation - * - */ - - /** - * Fired at the start of a tick, before any updates to the engine or timing - * - * @event beforeTick - * @param {} event An event object - * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - - /** - * Fired after engine timing updated, but just before engine state updated - * - * @event tick - * @param {} event An event object - * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - /** * Fired just before an update * * @event beforeUpdate * @param {} event An event object - * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick + * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ @@ -4670,37 +4622,7 @@ var Engine = {}; * * @event afterUpdate * @param {} event An event object - * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - - /** - * Fired just before rendering - * - * @event beforeRender - * @param {} event An event object - * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - - /** - * Fired after rendering - * - * @event afterRender - * @param {} event An event object - * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - - /** - * Fired after engine update and after rendering - * - * @event afterTick - * @param {} event An event object - * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick + * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ @@ -4711,7 +4633,7 @@ var Engine = {}; * @event collisionStart * @param {} event An event object * @param {} event.pairs List of affected pairs - * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick + * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ @@ -4722,7 +4644,7 @@ var Engine = {}; * @event collisionActive * @param {} event An event object * @param {} event.pairs List of affected pairs - * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick + * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ @@ -4733,7 +4655,7 @@ var Engine = {}; * @event collisionEnd * @param {} event An event object * @param {} event.pairs List of affected pairs - * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick + * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ @@ -4744,14 +4666,6 @@ var Engine = {}; * */ - /** - * A flag that specifies whether the engine is running or not. - * - * @property enabled - * @type boolean - * @default true - */ - /** * An integer `Number` that specifies the number of position iterations to perform each update. * The higher the value, the higher quality the simulation will be at the expense of performance. @@ -4809,46 +4723,13 @@ var Engine = {}; /** * A `Number` that specifies the current simulation-time in milliseconds starting from `0`. - * It is incremented on every `Engine.update` by the `timing.delta`. + * It is incremented on every `Engine.update` by the given `delta` argument. * * @property timing.timestamp * @type number * @default 0 */ - /** - * A `Boolean` that specifies if the `Engine.run` game loop should use a fixed timestep (otherwise it is variable). - * If timing is fixed, then the apparent simulation speed will change depending on the frame rate (but behaviour will be deterministic). - * If the timing is variable, then the apparent simulation speed will be constant (approximately, but at the cost of determininism). - * - * @property timing.isFixed - * @type boolean - * @default false - */ - - /** - * A `Number` that specifies the time step between updates in milliseconds. - * If `engine.timing.isFixed` is set to `true`, then `delta` is fixed. - * If it is `false`, then `delta` can dynamically change to maintain the correct apparent simulation speed. - * - * @property timing.delta - * @type number - * @default 1000 / 60 - */ - - /** - * A `Number` that specifies the time correction factor to apply to the current timestep. - * It is automatically handled when using `Engine.run`, but is also only optional even if you use your own game loop. - * The value is defined as `delta / lastDelta`, i.e. the percentage change of `delta` between steps. - * This value is always `1` (no correction) when frame rate is constant or `engine.timing.isFixed` is `true`. - * If the framerate and hence `delta` are changing, then correction should be applied to the current update to account for the change. - * See the paper on Time Corrected Verlet for more information. - * - * @property timing.correction - * @type number - * @default 1 - */ - /** * An instance of a `Render` controller. The default value is a `Matter.Render` instance created by `Engine.create`. * One may also develop a custom renderer module based on `Matter.Render` and pass an instance of it to `Engine.create` via `options.render`. @@ -5208,6 +5089,9 @@ var Mouse = {}; /** * The `Matter.Runner` module is an optional utility which provides a game loop, * that handles updating and rendering a `Matter.Engine` for you within a browser. +* It is intended for demo and testing purposes, but may be adequate for simple games. +* If you are using your own game loop instead, then you do not need the `Matter.Runner` module. +* Instead just call `Engine.update(engine, delta)` in your own loop. * Note that the method `Engine.run` is an alias for `Runner.run`. * * See [Demo.js](https://github.com/liabru/matter-js/blob/master/demo/js/Demo.js) @@ -5225,122 +5109,282 @@ var Runner = {}; return; } - var _fps = 60, - _deltaSampleSize = _fps, - _delta = 1000 / _fps; - var _requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame - || function(callback){ window.setTimeout(function() { callback(Common.now()); }, _delta); }; + || function(callback){ window.setTimeout(function() { callback(Common.now()); }, 1000 / 60); }; var _cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.msCancelAnimationFrame; /** - * Provides a basic game loop that handles updating the engine for you. - * Calls `Engine.update` and `Engine.render` on the `requestAnimationFrame` event automatically. - * Handles time correction and non-fixed dynamic timing (if enabled). - * Triggers `beforeTick`, `tick` and `afterTick` events. - * @method run - * @param {engine} engine + * Creates a new Runner. The options parameter is an object that specifies any properties you wish to override the defaults. + * @method create + * @param {} options */ - Runner.run = function(engine) { - var counterTimestamp = 0, - frameCounter = 0, - deltaHistory = [], - timePrev, - timeScalePrev = 1; + Runner.create = function(options) { + var defaults = { + fps: 60, + correction: 1, + deltaSampleSize: 60, + counterTimestamp: 0, + frameCounter: 0, + deltaHistory: [], + timePrev: null, + timeScalePrev: 1, + frameRequestId: null, + isFixed: false, + enabled: true + }; - (function render(time){ - var timing = engine.timing, - delta, - correction = 1; + var runner = Common.extend(defaults, options); - timing.frameRequestId = _requestAnimationFrame(render); + runner.delta = runner.delta || 1000 / runner.fps; + runner.deltaMin = runner.deltaMin || 1000 / runner.fps; + runner.deltaMax = runner.deltaMax || 1000 / (runner.fps * 0.5); + runner.fps = 1000 / runner.delta; - if (!engine.enabled) - return; - - // create an event object - var event = { - timestamp: time - }; - - Events.trigger(engine, 'beforeTick', event); - - if (timing.isFixed) { - // fixed timestep - delta = timing.delta; - } else { - // dynamic timestep based on wall clock between calls - delta = (time - timePrev) || timing.delta; - timePrev = time; - - // optimistically filter delta over a few frames, to improve stability - deltaHistory.push(delta); - deltaHistory = deltaHistory.slice(-_deltaSampleSize); - delta = Math.min.apply(null, deltaHistory); - - // limit delta - delta = delta < timing.deltaMin ? timing.deltaMin : delta; - delta = delta > timing.deltaMax ? timing.deltaMax : delta; - - // time correction for delta - correction = delta / timing.delta; - - // update engine timing object - timing.delta = delta; - } - - // time correction for time scaling - if (timeScalePrev !== 0) - correction *= timing.timeScale / timeScalePrev; - - if (timing.timeScale === 0) - correction = 0; - - timeScalePrev = timing.timeScale; - - // fps counter - frameCounter += 1; - if (time - counterTimestamp >= 1000) { - timing.fps = frameCounter * ((time - counterTimestamp) / 1000); - counterTimestamp = time; - frameCounter = 0; - } - - Events.trigger(engine, 'tick', event); - - // if world has been modified, clear the render scene graph - if (engine.world.isModified - && engine.render - && engine.render.controller - && engine.render.controller.clear) { - engine.render.controller.clear(engine.render); - } - - // update - Engine.update(engine, delta, correction); - - // render - if (engine.render) { - Engine.render(engine); - } - - Events.trigger(engine, 'afterTick', event); - })(); + return runner; }; /** - * Ends execution of `Runner.run` on the given `engine`, by canceling the animation frame request event loop. - * If you wish to only temporarily pause the engine, see `engine.enabled` instead. - * @method stop + * Continuously ticks a `Matter.Engine` by calling `Runner.tick` on the `requestAnimationFrame` event. + * @method run * @param {engine} engine */ - Runner.stop = function(engine) { - _cancelAnimationFrame(engine.timing.frameRequestId); + Runner.run = function(runner, engine) { + // create runner if engine is first argument + if (typeof runner.positionIterations !== 'undefined') { + engine = runner; + runner = Runner.create(); + } + + (function render(time){ + runner.frameRequestId = _requestAnimationFrame(render); + + if (time && runner.enabled) { + Runner.tick(runner, engine, time); + } + })(); + + return runner; }; + /** + * A game loop utility that updates the engine and renderer by one step (a 'tick'). + * Features delta smoothing, time correction and fixed or dynamic timing. + * Triggers `beforeTick`, `tick` and `afterTick` events on the engine. + * Consider just `Engine.update(engine, delta)` if you're using your own loop. + * @method tick + * @param {runner} runner + * @param {engine} engine + * @param {number} time + */ + Runner.tick = function(runner, engine, time) { + var timing = engine.timing, + correction = 1, + delta; + + // create an event object + var event = { + timestamp: timing.timestamp + }; + + Events.trigger(runner, 'beforeTick', event); + Events.trigger(engine, 'beforeTick', event); // @deprecated + + if (runner.isFixed) { + // fixed timestep + delta = runner.delta; + } else { + // dynamic timestep based on wall clock between calls + delta = (time - runner.timePrev) || runner.delta; + runner.timePrev = time; + + // optimistically filter delta over a few frames, to improve stability + runner.deltaHistory.push(delta); + runner.deltaHistory = runner.deltaHistory.slice(-runner.deltaSampleSize); + delta = Math.min.apply(null, runner.deltaHistory); + + // limit delta + delta = delta < runner.deltaMin ? runner.deltaMin : delta; + delta = delta > runner.deltaMax ? runner.deltaMax : delta; + + // correction for delta + correction = delta / runner.delta; + + // update engine timing object + runner.delta = delta; + } + + // time correction for time scaling + if (runner.timeScalePrev !== 0) + correction *= timing.timeScale / runner.timeScalePrev; + + if (timing.timeScale === 0) + correction = 0; + + runner.timeScalePrev = timing.timeScale; + runner.correction = correction; + + // fps counter + runner.frameCounter += 1; + if (time - runner.counterTimestamp >= 1000) { + runner.fps = runner.frameCounter * ((time - runner.counterTimestamp) / 1000); + runner.counterTimestamp = time; + runner.frameCounter = 0; + } + + Events.trigger(runner, 'tick', event); + Events.trigger(engine, 'tick', event); // @deprecated + + // if world has been modified, clear the render scene graph + if (engine.world.isModified + && engine.render + && engine.render.controller + && engine.render.controller.clear) { + engine.render.controller.clear(engine.render); + } + + // update + Events.trigger(runner, 'beforeUpdate', event); + Engine.update(engine, delta, correction); + Events.trigger(runner, 'afterUpdate', event); + + // render + if (engine.render) { + Events.trigger(runner, 'beforeRender', event); + Events.trigger(engine, 'beforeRender', event); // @deprecated + + engine.render.controller.world(engine); + + Events.trigger(runner, 'afterRender', event); + Events.trigger(engine, 'afterRender', event); // @deprecated + } + + Events.trigger(runner, 'afterTick', event); + Events.trigger(engine, 'afterTick', event); // @deprecated + }; + + /** + * Ends execution of `Runner.run` on the given `runner`, by canceling the animation frame request event loop. + * If you wish to only temporarily pause the engine, see `engine.enabled` instead. + * @method stop + * @param {runner} runner + */ + Runner.stop = function(runner) { + _cancelAnimationFrame(runner.frameRequestId); + }; + + /* + * + * Events Documentation + * + */ + + /** + * Fired at the start of a tick, before any updates to the engine or timing + * + * @event beforeTick + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired after engine timing updated, but just before update + * + * @event tick + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired at the end of a tick, after engine update and after rendering + * + * @event afterTick + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired before update + * + * @event beforeUpdate + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired after update + * + * @event afterUpdate + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired before rendering + * + * @event beforeRender + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired after rendering + * + * @event afterRender + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /* + * + * Properties Documentation + * + */ + + /** + * A flag that specifies whether the runner is running or not. + * + * @property enabled + * @type boolean + * @default true + */ + + /** + * A `Boolean` that specifies if the runner should use a fixed timestep (otherwise it is variable). + * If timing is fixed, then the apparent simulation speed will change depending on the frame rate (but behaviour will be deterministic). + * If the timing is variable, then the apparent simulation speed will be constant (approximately, but at the cost of determininism). + * + * @property isFixed + * @type boolean + * @default false + */ + + /** + * A `Number` that specifies the time step between updates in milliseconds. + * If `engine.timing.isFixed` is set to `true`, then `delta` is fixed. + * If it is `false`, then `delta` can dynamically change to maintain the correct apparent simulation speed. + * + * @property delta + * @type number + * @default 1000 / 60 + */ + })(); @@ -7351,6 +7395,12 @@ var Render = {}; constraints = [], i; + var event = { + timestamp: engine.timing.timestamp + }; + + Events.trigger(render, 'beforeRender', event); + // apply background if it has changed if (render.currentBackground !== background) _applyBackground(render, background); @@ -7448,6 +7498,8 @@ var Render = {}; // revert view transforms context.setTransform(options.pixelRatio, 0, 0, options.pixelRatio, 0, 0); } + + Events.trigger(render, 'afterRender', event); }; /** @@ -8227,7 +8279,7 @@ var Render = {}; } - context.setLineDash([0]); + context.setLineDash([]); context.translate(-0.5, -0.5); } @@ -8323,6 +8375,32 @@ var Render = {}; render.currentBackground = background; }; + /* + * + * Events Documentation + * + */ + + /** + * Fired before rendering + * + * @event beforeRender + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired after rendering + * + * @event afterRender + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + /* * * Properties Documentation diff --git a/build/matter.min.js b/build/matter.min.js index 74a9f5d..5b9c143 100644 --- a/build/matter.min.js +++ b/build/matter.min.js @@ -1,9 +1,9 @@ /** -* matter.min.js edge-master 2015-07-05 +* matter.min.js edge-master 2015-08-13 * http://brm.io/matter-js/ * License: MIT */ -!function(){var a={},b={};!function(){b._inertiaScale=4;var a=1,c=-1,d=1;b.create=function(a){var b={id:o.nextId(),type:"body",label:"Body",parts:[],angle:0,vertices:A.fromPath("L 0 0 L 40 0 L 40 40 L 0 40"),position:{x:0,y:0},force:{x:0,y:0},torque:0,positionImpulse:{x:0,y:0},constraintImpulse:{x:0,y:0,angle:0},totalContacts:0,speed:0,angularSpeed:0,velocity:{x:0,y:0},angularVelocity:0,isStatic:!1,isSleeping:!1,motion:0,sleepThreshold:60,density:.001,restitution:0,friction:.1,frictionStatic:.5,frictionAir:.01,collisionFilter:{category:1,mask:4294967295,group:0},slop:.05,timeScale:1,render:{visible:!0,sprite:{xScale:1,yScale:1},lineWidth:1.5}},c=o.extend(b,a);return e(c,a),c},b.nextGroup=function(b){return b?c--:a++},b.nextCategory=function(){return d<<=1};var e=function(a,c){b.set(a,{bounds:a.bounds||x.create(a.vertices),positionPrev:a.positionPrev||z.clone(a.position),anglePrev:a.anglePrev||a.angle,vertices:a.vertices,parts:a.parts||[a],isStatic:a.isStatic,isSleeping:a.isSleeping,parent:a.parent||a}),A.rotate(a.vertices,a.angle,a.position),w.rotate(a.axes,a.angle),x.update(a.bounds,a.vertices,a.velocity),b.set(a,{axes:c.axes||a.axes,area:c.area||a.area,mass:c.mass||a.mass,inertia:c.inertia||a.inertia});var d=a.isStatic?"#eeeeee":o.choose(["#556270","#4ECDC4","#C7F464","#FF6B6B","#C44D58"]),e=o.shadeColor(d,-20);a.render.fillStyle=a.render.fillStyle||d,a.render.strokeStyle=a.render.strokeStyle||e};b.set=function(a,c,d){var e;"string"==typeof c&&(e=c,c={},c[e]=d);for(e in c)if(d=c[e],c.hasOwnProperty(e))switch(e){case"isStatic":b.setStatic(a,d);break;case"isSleeping":t.set(a,d);break;case"mass":b.setMass(a,d);break;case"density":b.setDensity(a,d);break;case"inertia":b.setInertia(a,d);break;case"vertices":b.setVertices(a,d);break;case"position":b.setPosition(a,d);break;case"angle":b.setAngle(a,d);break;case"velocity":b.setVelocity(a,d);break;case"angularVelocity":b.setAngularVelocity(a,d);break;case"parts":b.setParts(a,d);break;default:a[e]=d}},b.setStatic=function(a,b){for(var c=0;c0&&z.rotateAbout(e.position,c,a.position,e.position)}},b.setVelocity=function(a,b){a.positionPrev.x=a.position.x-b.x,a.positionPrev.y=a.position.y-b.y,a.velocity.x=b.x,a.velocity.y=b.y,a.speed=z.magnitude(a.velocity)},b.setAngularVelocity=function(a,b){a.anglePrev=a.angle-b,a.angularVelocity=b,a.angularSpeed=Math.abs(a.angularVelocity)},b.translate=function(a,c){b.setPosition(a,z.add(a.position,c))},b.rotate=function(a,c){b.setAngle(a,a.angle+c)},b.scale=function(a,c,d){for(var e=0;e0&&(j.position.x+=a.velocity.x,j.position.y+=a.velocity.y),0!==a.angularVelocity&&(A.rotate(j.vertices,a.angularVelocity,a.position),w.rotate(j.axes,a.angularVelocity),i>0&&z.rotateAbout(j.position,a.angularVelocity,a.position,j.position)),x.update(j.bounds,j.vertices,a.velocity)}},b.applyForce=function(a,b,c){a.force.x+=c.x,a.force.y+=c.y;var d={x:b.x-a.position.x,y:b.y-a.position.y};a.torque+=(d.x*c.y-d.y*c.x)*a.inverseInertia};var f=function(a){for(var b={mass:0,area:0,inertia:0,centre:{x:0,y:0}},c=1===a.parts.length?0:1;c1?1:0;j1?1:0;m0:0!==(a.mask&b.category)&&0!==(b.mask&a.category)}}();var g={};!function(){g.create=function(a){var b={controller:g,detector:f.collisions,buckets:{},pairs:{},pairsList:[],bucketWidth:48,bucketHeight:48};return o.extend(b,a)},g.update=function(c,f,g,h){var l,m,n,o,p,q=g.world,r=c.buckets,s=!1;for(l=0;lq.bounds.width||t.bounds.max.y<0||t.bounds.min.y>q.bounds.height)){var u=b(c,t);if(!t.region||u.id!==t.region.id||h){(!t.region||h)&&(t.region=u);var v=a(u,t.region);for(m=v.startCol;m<=v.endCol;m++)for(n=v.startRow;n<=v.endRow;n++){p=d(m,n),o=r[p];var w=m>=u.startCol&&m<=u.endCol&&n>=u.startRow&&n<=u.endRow,x=m>=t.region.startCol&&m<=t.region.endCol&&n>=t.region.startRow&&n<=t.region.endRow;!w&&x&&x&&o&&j(c,o,t),(t.region===u||w&&!x||h)&&(o||(o=e(r,p)),i(c,o,t))}t.region=u,s=!0}}}s&&(c.pairsList=k(c))},g.clear=function(a){a.buckets={},a.pairs={},a.pairsList=[]};var a=function(a,b){var d=Math.min(a.startCol,b.startCol),e=Math.max(a.endCol,b.endCol),f=Math.min(a.startRow,b.startRow),g=Math.max(a.endRow,b.endRow);return c(d,e,f,g)},b=function(a,b){var d=b.bounds,e=Math.floor(d.min.x/a.bucketWidth),f=Math.floor(d.max.x/a.bucketWidth),g=Math.floor(d.min.y/a.bucketHeight),h=Math.floor(d.max.y/a.bucketHeight);return c(e,f,g,h)},c=function(a,b,c,d){return{id:a+","+b+","+c+","+d,startCol:a,endCol:b,startRow:c,endRow:d}},d=function(a,b){return a+","+b},e=function(a,b){var c=a[b]=[];return c},i=function(a,b,c){for(var d=0;d0?d.push(c):delete a.pairs[b[e]];return d}}();var h={};!function(){h.create=function(a,b){var c=a.bodyA,d=a.bodyB,e=a.parentA,f=a.parentB,g={id:h.id(c,d),bodyA:c,bodyB:d,contacts:{},activeContacts:[],separation:0,isActive:!0,timeCreated:b,timeUpdated:b,inverseMass:e.inverseMass+f.inverseMass,friction:Math.min(e.friction,f.friction),frictionStatic:Math.max(e.frictionStatic,f.frictionStatic),restitution:Math.max(e.restitution,f.restitution),slop:Math.max(e.slop,f.slop)};return h.update(g,a,b),g},h.update=function(a,b,c){var d=a.contacts,f=b.supports,g=a.activeContacts,i=b.parentA,j=b.parentB;if(a.collision=b,a.inverseMass=i.inverseMass+j.inverseMass,a.friction=Math.min(i.friction,j.friction),a.frictionStatic=Math.max(i.frictionStatic,j.frictionStatic),a.restitution=Math.max(i.restitution,j.restitution),a.slop=Math.max(i.slop,j.slop),g.length=0,b.collided){for(var k=0;ka&&j.push(g);for(g=0;gl.friction*l.frictionStatic*I*c&&(J=l.friction*G*c,K=F);var L=z.cross(x,q),M=z.cross(y,q),N=n.inverseMass+p.inverseMass+n.inverseInertia*L*L+p.inverseInertia*M*M;if(H*=t/N,J*=t/(1+N),0>D&&D*D>k._restingThresh*c)v.normalImpulse=0,v.tangentImpulse=0;else{var O=v.normalImpulse;v.normalImpulse=Math.min(v.normalImpulse+H,0),H=v.normalImpulse-O;var P=v.tangentImpulse;v.tangentImpulse=o.clamp(v.tangentImpulse+J,-K,K),J=v.tangentImpulse-P}d.x=q.x*H+r.x*J,d.y=q.y*H+r.y*J,n.isStatic||n.isSleeping||(n.positionPrev.x+=d.x*n.inverseMass,n.positionPrev.y+=d.y*n.inverseMass,n.anglePrev+=z.cross(x,d)*n.inverseInertia),p.isStatic||p.isSleeping||(p.positionPrev.x-=d.x*p.inverseMass,p.positionPrev.y-=d.y*p.inverseMass,p.anglePrev-=z.cross(y,d)*p.inverseInertia)}}}}}();var l={};!function(){l.collides=function(b,d,e){var f,g,h,i,j=e,k=!1;if(j){var l=b.parent,m=d.parent,n=l.speed*l.speed+l.angularSpeed*l.angularSpeed+m.speed*m.speed+m.angularSpeed*m.angularSpeed;k=j&&j.collided&&.2>n,i=j}else i={collided:!1,bodyA:b,bodyB:d};if(j&&k){var o=i.axisBody,p=o===b?d:b,q=[o.axes[j.axisNumber]];if(h=a(o.vertices,p.vertices,q),i.reused=!0,h.overlap<=0)return i.collided=!1,i}else{if(f=a(b.vertices,d.vertices,b.axes),f.overlap<=0)return i.collided=!1,i;if(g=a(d.vertices,b.vertices,d.axes),g.overlap<=0)return i.collided=!1,i;f.overlap0&&(i.normal=z.neg(i.normal)),i.tangent=z.perp(i.normal),i.penetration={x:i.normal.x*i.depth,y:i.normal.y*i.depth};var r=c(b,d,i.normal),s=i.supports||[];if(s.length=0,A.contains(b.vertices,r[0])&&s.push(r[0]),A.contains(b.vertices,r[1])&&s.push(r[1]),s.length<2){var t=c(d,b,z.neg(i.normal));A.contains(d.vertices,t[0])&&s.push(t[0]),s.length<2&&A.contains(d.vertices,t[1])&&s.push(t[1])}return s.length<1&&(s=[r[0]]),i.supports=s,i};var a=function(a,c,d){for(var e,f,g=z._temp[0],h=z._temp[1],i={overlap:Number.MAX_VALUE},j=0;j=e)return i.overlap=e,i;ee?e=g:d>g&&(d=g)}a.min=d,a.max=e},c=function(a,b,c){for(var d,e,f,g,h=Number.MAX_VALUE,i=z._temp[0],j=b.vertices,k=a.position,l=0;ld&&(h=d,f=e);var m=f.index-1>=0?f.index-1:j.length-1;e=j[m],i.x=e.x-k.x,i.y=e.y-k.y,h=-z.dot(c,i),g=e;var n=(f.index+1)%j.length;return e=j[n],i.x=e.x-k.x,i.y=e.y-k.y,d=-z.dot(c,i),h>d&&(g=e),[f,g]}}();var m={};!function(){var a=1e-6,b=.001;m.create=function(b){var c=b;c.bodyA&&!c.pointA&&(c.pointA={x:0,y:0}),c.bodyB&&!c.pointB&&(c.pointB={x:0,y:0});var d=c.bodyA?z.add(c.bodyA.position,c.pointA):c.pointA,e=c.bodyB?z.add(c.bodyB.position,c.pointB):c.pointB,f=z.magnitude(z.sub(d,e));c.length=c.length||f||a;var g={visible:!0,lineWidth:2,strokeStyle:"#666"};return c.render=o.extend(g,c.render),c.id=c.id||o.nextId(),c.label=c.label||"Constraint",c.type="constraint",c.stiffness=c.stiffness||1,c.angularStiffness=c.angularStiffness||0,c.angleA=c.bodyA?c.bodyA.angle:c.angleA,c.angleB=c.bodyB?c.bodyB.angle:c.angleB,c},m.solveAll=function(a,b){for(var c=0;c0&&(B=0);var C,D={x:n.x*B,y:n.y*B};e&&!e.isStatic&&(C=z.cross(s,D)*e.inverseInertia*(1-c.angularStiffness),t.set(e,!1),C=o.clamp(C,-.01,.01),e.constraintImpulse.x-=p.x,e.constraintImpulse.y-=p.y,e.constraintImpulse.angle+=C,e.position.x-=p.x,e.position.y-=p.y,e.angle+=C),f&&!f.isStatic&&(C=z.cross(u,D)*f.inverseInertia*(1-c.angularStiffness),t.set(f,!1),C=o.clamp(C,-.01,.01),f.constraintImpulse.x+=p.x,f.constraintImpulse.y+=p.y,f.constraintImpulse.angle-=C,f.position.x+=p.x,f.position.y+=p.y,f.angle-=C)}}},m.postSolveAll=function(a){for(var b=0;b0&&(f.position.x+=d.x,f.position.y+=d.y),0!==d.angle&&(A.rotate(f.vertices,d.angle,c.position),w.rotate(f.axes,d.angle),e>0&&z.rotateAbout(f.position,d.angle,c.position,f.position)),x.update(f.bounds,f.vertices)}d.angle=0,d.x=0,d.y=0}}}();var n={};!function(){n.create=function(b,d){var e=(b?b.mouse:null)||(d?d.mouse:null);!e&&b&&b.render&&b.render.canvas?e=r.create(b.render.canvas):(e=r.create(),o.log("MouseConstraint.create: options.mouse was undefined, engine.render.canvas was undefined, may not function as expected","warn"));var f=m.create({label:"Mouse Constraint",pointA:e.position,pointB:{x:0,y:0},length:.01,stiffness:.1,angularStiffness:1,render:{strokeStyle:"#90EE90",lineWidth:3}}),g={type:"mouseConstraint",mouse:e,body:null,constraint:f,collisionFilter:{category:1,mask:4294967295,group:0}},h=o.extend(g,d);return q.on(b,"tick",function(){var d=c.allBodies(b.world);n.update(h,d),a(h)}),h},n.update=function(a,b){var c=a.mouse,d=a.constraint,e=a.body;if(0===c.button){if(d.bodyB)t.set(d.bodyB,!1),d.pointA=c.position;else for(var g=0;g1?1:0;h>16)+d,f=(c>>8&255)+d,g=(255&c)+d;return"#"+(16777216+65536*(255>e?1>e?0:e:255)+256*(255>f?1>f?0:f:255)+(255>g?1>g?0:g:255)).toString(16).slice(1)},o.shuffle=function(a){for(var b=a.length-1;b>0;b--){var c=Math.floor(o.random()*(b+1)),d=a[b];a[b]=a[c],a[c]=d}return a},o.choose=function(a){return a[Math.floor(o.random()*a.length)]},o.isElement=function(a){try{return a instanceof HTMLElement}catch(b){return"object"==typeof a&&1===a.nodeType&&"object"==typeof a.style&&"object"==typeof a.ownerDocument}},o.isArray=function(a){return"[object Array]"===Object.prototype.toString.call(a)},o.clamp=function(a,b,c){return b>a?b:a>c?c:a},o.sign=function(a){return 0>a?-1:1},o.now=function(){var a=window.performance||{};return a.now=function(){return a.now||a.webkitNow||a.msNow||a.oNow||a.mozNow||function(){return+new Date}}(),a.now()},o.random=function(b,c){return b="undefined"!=typeof b?b:0,c="undefined"!=typeof c?c:1,b+a()*(c-b)},o.colorToNumber=function(a){return a=a.replace("#",""),3==a.length&&(a=a.charAt(0)+a.charAt(0)+a.charAt(1)+a.charAt(1)+a.charAt(2)+a.charAt(2)),parseInt(a,16)},o.log=function(a,b){if(console&&console.log&&console.warn)switch(b){case"warn":console.warn("Matter.js:",a);break;case"error":console.log("Matter.js:",a)}},o.nextId=function(){return o._nextId++},o.indexOf=function(a,b){if(a.indexOf)return a.indexOf(b);for(var c=0;c0&&q.trigger(a,"collisionStart",{pairs:v.collisionStart}),k.preSolvePosition(v.list),e=0;e0&&q.trigger(a,"collisionActive",{pairs:v.collisionActive}),v.collisionEnd.length>0&&q.trigger(a,"collisionEnd",{pairs:v.collisionEnd}),f(r),g.isModified&&c.setModified(g,!1,!1,!0),q.trigger(a,"afterUpdate",p),a},p.render=function(a){var b={timestamp:a.timing.timestamp};q.trigger(a,"beforeRender",b),a.render.controller.world(a),q.trigger(a,"afterRender",b)},p.merge=function(a,b){if(o.extend(a,b),b.world){a.world=b.world,p.clear(a);for(var d=c.allBodies(a.world),e=0;el.deltaMax?l.deltaMax:k,m=k/l.delta,l.delta=k),0!==h&&(m*=l.timeScale/h),0===l.timeScale&&(m=0),h=l.timeScale,f+=1,j-e>=1e3&&(l.fps=f*((j-e)/1e3),e=j,f=0),q.trigger(a,"tick",n),a.world.isModified&&a.render&&a.render.controller&&a.render.controller.clear&&a.render.controller.clear(a.render),p.update(a,k,m),a.render&&p.render(a),q.trigger(a,"afterTick",n)}}()},s.stop=function(a){e(a.timing.frameRequestId)}}}();var t={};!function(){t._motionWakeThreshold=.18,t._motionSleepThreshold=.08,t._minBias=.9,t.update=function(a,b){for(var c=b*b*b,d=0;d0&&e.motion=e.sleepThreshold&&t.set(e,!0)):e.sleepCounter>0&&(e.sleepCounter-=1)}else t.set(e,!1)}},t.afterCollisions=function(a,b){for(var c=b*b*b,d=0;dt._motionWakeThreshold*c&&t.set(i,!1)}}}},t.set=function(a,b){var c=a.isSleeping;b?(a.isSleeping=!0,a.sleepCounter=a.sleepThreshold,a.positionImpulse.x=0,a.positionImpulse.y=0,a.positionPrev.x=a.position.x,a.positionPrev.y=a.position.y,a.anglePrev=a.angle,a.speed=0,a.angularSpeed=0,a.motion=0,c||q.trigger(a,"sleepStart")):(a.isSleeping=!1,a.sleepCounter=0,c&&q.trigger(a,"sleepEnd"))}}();var u={};!function(){u.rectangle=function(a,c,d,e,f){f=f||{};var g={label:"Rectangle Body",position:{x:a,y:c},vertices:A.fromPath("L 0 0 L "+d+" 0 L "+d+" "+e+" L 0 "+e)};if(f.chamfer){var h=f.chamfer;g.vertices=A.chamfer(g.vertices,h.radius,h.quality,h.qualityMin,h.qualityMax),delete f.chamfer}return b.create(o.extend({},g,f))},u.trapezoid=function(a,c,d,e,f,g){g=g||{},f*=.5;var h=(1-2*f)*d,i=d*f,j=i+h,k=j+i,l={label:"Trapezoid Body",position:{x:a,y:c},vertices:A.fromPath("L 0 0 L "+i+" "+-e+" L "+j+" "+-e+" L "+k+" 0")};if(g.chamfer){var m=g.chamfer;l.vertices=A.chamfer(l.vertices,m.radius,m.quality,m.qualityMin,m.qualityMax),delete g.chamfer}return b.create(o.extend({},l,g))},u.circle=function(a,b,c,d,e){d=d||{},d.label="Circle Body",e=e||25;var f=Math.ceil(Math.max(10,Math.min(e,c)));return f%2===1&&(f+=1),d.circleRadius=c,u.polygon(a,b,f,c,d)},u.polygon=function(a,c,d,e,f){if(f=f||{},3>d)return u.circle(a,c,e,f);for(var g=2*Math.PI/d,h="",i=.5*g,j=0;d>j;j+=1){var k=i+j*g,l=Math.cos(k)*e,m=Math.sin(k)*e;h+="L "+l.toFixed(3)+" "+m.toFixed(3)+" "}var n={label:"Polygon Body",position:{x:a,y:c},vertices:A.fromPath(h)};if(f.chamfer){var p=f.chamfer;n.vertices=A.chamfer(n.vertices,p.radius,p.quality,p.qualityMin,p.qualityMax),delete f.chamfer}return b.create(o.extend({},n,f))},u.fromVertices=function(a,c,d,e,f,g,h){var i,j,k,l,m,n,p,q,r;for(e=e||{},j=[],f="undefined"!=typeof f?f:!1,g="undefined"!=typeof g?g:.01,h="undefined"!=typeof h?h:10,window.decomp||o.log("Bodies.fromVertices: poly-decomp.js required. Could not decompose vertices. Fallback to convex hull.","warn"),o.isArray(d[0])||(d=[d]),q=0;q0&&A.area(v)E&&w>F&&(C[p].isInternal=!0,D[r].isInternal=!0)}}}}}return j.length>1?(i=b.create(o.extend({parts:j.slice(0)},e)),b.setPosition(i,{x:a,y:c}),i):j[0]}}();var v={};!function(){v.stack=function(a,d,e,f,g,h,i){for(var j,k=c.create({label:"Stack"}),l=a,m=d,n=0,o=0;f>o;o++){for(var p=0,q=0;e>q;q++){var r=i(l,m,q,o,j,n);if(r){var s=r.bounds.max.y-r.bounds.min.y,t=r.bounds.max.x-r.bounds.min.x;s>p&&(p=s),b.translate(r,{x:.5*t,y:.5*s}),l=r.bounds.max.x+g,c.addBody(k,r),j=r,n+=1}else l+=g}m+=p+h,l=a}return k},v.chain=function(a,b,d,e,f,g){for(var h=a.bodies,i=1;ig;g++){for(h=1;b>h;h++)i=l[h-1+g*b],j=l[h+g*b],c.addConstraint(a,m.create(o.extend({bodyA:i,bodyB:j},f)));if(g>0)for(h=0;b>h;h++)i=l[h+(g-1)*b],j=l[h+g*b],c.addConstraint(a,m.create(o.extend({bodyA:i,bodyB:j},f))),e&&h>0&&(k=l[h-1+(g-1)*b],c.addConstraint(a,m.create(o.extend({bodyA:k,bodyB:j},f)))),e&&b-1>h&&(k=l[h+1+(g-1)*b],c.addConstraint(a,m.create(o.extend({bodyA:k,bodyB:j},f))))}return a.label+=" Mesh",a},v.pyramid=function(a,c,d,e,f,g,h){return v.stack(a,c,d,e,f,g,function(c,g,i,j,k,l){var m=Math.min(e,Math.ceil(d/2)),n=k?k.bounds.max.x-k.bounds.min.x:0;if(!(j>m)){j=m-j;var o=j,p=d-1-j;if(!(o>i||i>p)){1===l&&b.translate(k,{x:(i+(d%2===1?1:-1))*n,y:0});var q=k?i*n:0;return h(a+q+i*f,g,i,j,k,l)}}})},v.newtonsCradle=function(a,b,d,e,f){for(var g=c.create({label:"Newtons Cradle"}),h=0;d>h;h++){var i=1.9,j=u.circle(a+h*e*i,b+f,e,{inertia:99999,restitution:1,friction:0,frictionAir:1e-4,slop:.01}),k=m.create({pointA:{x:a+h*e*i,y:b},bodyB:j});c.addBody(g,j),c.addConstraint(g,k)}return g},v.car=function(a,d,e,f,g){var h=b.nextGroup(!0),i=-20,j=.5*-e+i,k=.5*e-i,l=0,n=c.create({label:"Car"}),o=u.trapezoid(a,d,e,f,.3,{collisionFilter:{group:h},friction:.01,chamfer:{radius:10}}),p=u.circle(a+j,d+l,g,{collisionFilter:{group:h},restitution:.5,friction:.9,frictionStatic:10,slop:.5,density:.01}),q=u.circle(a+k,d+l,g,{collisionFilter:{group:h},restitution:.5,friction:.9,frictionStatic:10,slop:.5,density:.01}),r=m.create({bodyA:o,pointA:{x:j,y:l},bodyB:p,stiffness:.5}),s=m.create({bodyA:o,pointA:{x:k,y:l},bodyB:q,stiffness:.5});return c.addBody(n,o),c.addBody(n,p),c.addBody(n,q),c.addConstraint(n,r),c.addConstraint(n,s),n},v.softBody=function(a,b,c,d,e,f,g,h,i,j){i=o.extend({inertia:1/0},i),j=o.extend({stiffness:.4},j);var k=v.stack(a,b,c,d,e,f,function(a,b){return u.circle(a,b,h,i)});return v.mesh(k,c,d,g,j),k.label="Soft Body",k}}();var w={};!function(){w.fromVertices=function(a){for(var b={},c=0;ca.max.x&&(a.max.x=e.x),e.xa.max.y&&(a.max.y=e.y),e.y0?a.max.x+=c.x:a.min.x+=c.x,c.y>0?a.max.y+=c.y:a.min.y+=c.y)},x.contains=function(a,b){return b.x>=a.min.x&&b.x<=a.max.x&&b.y>=a.min.y&&b.y<=a.max.y},x.overlaps=function(a,b){return a.min.x<=b.max.x&&a.max.x>=b.min.x&&a.max.y>=b.min.y&&a.min.y<=b.max.y},x.translate=function(a,b){a.min.x+=b.x,a.max.x+=b.x,a.min.y+=b.y,a.max.y+=b.y},x.shift=function(a,b){var c=a.max.x-a.min.x,d=a.max.y-a.min.y;a.min.x=b.x,a.max.x=b.x+c,a.min.y=b.y,a.max.y=b.y+d}}();var y={};!function(){y.pathToVertices=function(b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p=[],q=0,r=0,s=0;c=c||15;var t=function(a,b,c){var d=c%2===1&&c>1;if(!l||a!=l.x||b!=l.y){l&&d?(n=l.x,o=l.y):(n=0,o=0);var e={x:n+a,y:o+b};(d||!l)&&(l=e),p.push(e),r=n+a,s=o+b}},u=function(a){var b=a.pathSegTypeAsLetter.toUpperCase();if("Z"!==b){switch(b){case"M":case"L":case"T":case"C":case"S":case"Q":r=a.x,s=a.y;break;case"H":r=a.x;break;case"V":s=a.y}t(r,s,a.pathSegType)}};for(a(b),f=b.getTotalLength(),i=[],d=0;dq;){if(m=b.getPathSegAtLength(q),h=i[m],h!=k){for(;j.length&&j[0]!=h;)u(j.shift());k=h}switch(h.pathSegTypeAsLetter.toUpperCase()){case"C":case"T":case"S":case"Q":case"A":g=b.getPointAtLength(q),t(g.x,g.y,0)}q+=c}for(d=0,e=j.length;e>d;++d)u(j[d]);return p};var a=function(a){for(var b,c,d,e,f,g,h=a.pathSegList,i=0,j=0,k=h.numberOfItems,l=0;k>l;++l){var m=h.getItem(l),n=m.pathSegTypeAsLetter;if(/[MLHVCSQTA]/.test(n))"x"in m&&(i=m.x),"y"in m&&(j=m.y);else switch("x1"in m&&(d=i+m.x1),"x2"in m&&(f=i+m.x2),"y1"in m&&(e=j+m.y1),"y2"in m&&(g=j+m.y2),"x"in m&&(i+=m.x),"y"in m&&(j+=m.y),n){case"m":h.replaceItem(a.createSVGPathSegMovetoAbs(i,j),l);break;case"l":h.replaceItem(a.createSVGPathSegLinetoAbs(i,j),l);break;case"h":h.replaceItem(a.createSVGPathSegLinetoHorizontalAbs(i),l);break;case"v":h.replaceItem(a.createSVGPathSegLinetoVerticalAbs(j),l);break;case"c":h.replaceItem(a.createSVGPathSegCurvetoCubicAbs(i,j,d,e,f,g),l);break;case"s":h.replaceItem(a.createSVGPathSegCurvetoCubicSmoothAbs(i,j,f,g),l);break;case"q":h.replaceItem(a.createSVGPathSegCurvetoQuadraticAbs(i,j,d,e),l);break;case"t":h.replaceItem(a.createSVGPathSegCurvetoQuadraticSmoothAbs(i,j),l);break;case"a":h.replaceItem(a.createSVGPathSegArcAbs(i,j,m.r1,m.r2,m.angle,m.largeArcFlag,m.sweepFlag),l);break;case"z":case"Z":i=b,j=c}("M"==n||"m"==n)&&(b=i,c=j)}}}();var z={};!function(){z.create=function(a,b){return{x:a||0,y:b||0}},z.clone=function(a){return{x:a.x,y:a.y}},z.magnitude=function(a){return Math.sqrt(a.x*a.x+a.y*a.y)},z.magnitudeSquared=function(a){return a.x*a.x+a.y*a.y},z.rotate=function(a,b){var c=Math.cos(b),d=Math.sin(b);return{x:a.x*c-a.y*d,y:a.x*d+a.y*c}},z.rotateAbout=function(a,b,c,d){var e=Math.cos(b),f=Math.sin(b);d||(d={});var g=c.x+((a.x-c.x)*e-(a.y-c.y)*f);return d.y=c.y+((a.x-c.x)*f+(a.y-c.y)*e),d.x=g,d},z.normalise=function(a){var b=z.magnitude(a);return 0===b?{x:0,y:0}:{x:a.x/b,y:a.y/b}},z.dot=function(a,b){return a.x*b.x+a.y*b.y},z.cross=function(a,b){return a.x*b.y-a.y*b.x},z.cross3=function(a,b,c){return(b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x)},z.add=function(a,b,c){return c||(c={}),c.x=a.x+b.x,c.y=a.y+b.y,c},z.sub=function(a,b,c){return c||(c={}),c.x=a.x-b.x,c.y=a.y-b.y,c},z.mult=function(a,b){return{x:a.x*b,y:a.y*b}},z.div=function(a,b){return{x:a.x/b,y:a.y/b}},z.perp=function(a,b){return b=b===!0?-1:1,{x:b*-a.y,y:b*a.x}},z.neg=function(a){return{x:-a.x,y:-a.y}},z.angle=function(a,b){return Math.atan2(b.y-a.y,b.x-a.x)},z._temp=[z.create(),z.create(),z.create(),z.create(),z.create(),z.create()]}();var A={};!function(){A.create=function(a,b){for(var c=[],d=0;d0)return!1}return!0},A.scale=function(a,b,c,d){if(1===b&&1===c)return a;d=d||A.centre(a);for(var e,f,g=0;g=0?g-1:a.length-1],i=a[g],j=a[(g+1)%a.length],k=b[gv;v++)f.push(z.add(z.rotate(p,u*v),r))}else f.push(i)}return f},A.clockwiseSort=function(a){var b=A.mean(a);return a.sort(function(a,c){return z.angle(b,a)-z.angle(b,c)}),a},A.isConvex=function(a){var b,c,d,e,f=0,g=a.length;if(3>g)return null;for(b=0;g>b;b++)if(c=(b+1)%g,d=(b+2)%g,e=(a[c].x-a[b].x)*(a[d].y-a[c].y),e-=(a[c].y-a[b].y)*(a[d].x-a[c].x),0>e?f|=1:e>0&&(f|=2),3===f)return!1;return 0!==f?!0:null},A.hull=function(a){var b,c,d=[],e=[];for(a=a.slice(0),a.sort(function(a,b){var c=a.x-b.x;return 0!==c?c:a.y-b.y}),c=0;c=2&&z.cross3(e[e.length-2],e[e.length-1],b)<=0;)e.pop();e.push(b)}for(c=a.length-1;c>=0;c--){for(b=a[c];d.length>=2&&z.cross3(d[d.length-2],d[d.length-1],b)<=0;)d.pop();d.push(b)}return d.pop(),e.pop(),d.concat(e)}}();var B={};!function(){B.create=function(b){var c={controller:B,element:null,canvas:null,options:{width:800,height:600,pixelRatio:1,background:"#fafafa",wireframeBackground:"#222",hasBounds:!1,enabled:!0,wireframes:!0,showSleeping:!0,showDebug:!1,showBroadphase:!1,showBounds:!1,showVelocity:!1,showCollisions:!1,showSeparations:!1,showAxes:!1,showPositions:!1,showAngleIndicator:!1,showIds:!1,showShadows:!1,showVertexNumbers:!1,showConvexHulls:!1,showInternalEdges:!1}},d=o.extend(c,b);return d.canvas=d.canvas||a(d.options.width,d.options.height),d.context=d.canvas.getContext("2d"),d.textures={},d.bounds=d.bounds||{min:{x:0,y:0},max:{x:d.options.width,y:d.options.height}},1!==d.options.pixelRatio&&B.setPixelRatio(d,d.options.pixelRatio),o.isElement(d.element)?d.element.appendChild(d.canvas):o.log("Render.create: options.element was undefined, render.canvas was created but not appended","warn"),d},B.setPixelRatio=function(a,c){var d=a.options,e=a.canvas;"auto"===c&&(c=b(e)),d.pixelRatio=c,e.setAttribute("data-pixel-ratio",c),e.width=d.width*c,e.height=d.height*c,e.style.width=d.width+"px",e.style.height=d.height+"px",a.context.scale(c,c)},B.world=function(a){var b,d=a.render,f=a.world,h=d.canvas,i=d.context,j=d.options,k=c.allBodies(f),l=c.allConstraints(f),m=j.wireframes?j.wireframeBackground:j.background,n=[],o=[];if(d.currentBackground!==m&&e(d,m),i.globalCompositeOperation="source-in",i.fillStyle="transparent",i.fillRect(0,0,h.width,h.height),i.globalCompositeOperation="source-over",j.hasBounds){var p=d.bounds.max.x-d.bounds.min.x,q=d.bounds.max.y-d.bounds.min.y,r=p/j.width,s=q/j.height;for(b=0;b=500){var i="";i+="fps: "+Math.round(a.timing.fps)+h,f.debugString=i,f.debugTimestamp=a.timing.timestamp}if(f.debugString){d.font="12px Arial",d.fillStyle=g.wireframes?"rgba(255,255,255,0.5)":"rgba(0,0,0,0.5)";for(var j=f.debugString.split("\n"),k=0;k1?1:0;h1?1:0;h1?1:0;f1?1:0;j1?1:0;f1?1:0;f1?1:0;e0)){var l=d.activeContacts[0].vertex.x,m=d.activeContacts[0].vertex.y;2===d.activeContacts.length&&(l=(d.activeContacts[0].vertex.x+d.activeContacts[1].vertex.x)/2,m=(d.activeContacts[0].vertex.y+d.activeContacts[1].vertex.y)/2),e.bodyB===e.supports[0].body||e.bodyA.isStatic===!0?h.moveTo(l-8*e.normal.x,m-8*e.normal.y):h.moveTo(l+8*e.normal.x,m+8*e.normal.y),h.lineTo(l,m)}h.strokeStyle=i.wireframes?"rgba(255,165,0,0.7)":"orange",h.lineWidth=1,h.stroke()},B.separations=function(a,b,c){var d,e,f,g,h,i=c,j=a.render.options;for(i.beginPath(),h=0;h1?1:0;l0&&z.rotateAbout(e.position,c,a.position,e.position)}},b.setVelocity=function(a,b){a.positionPrev.x=a.position.x-b.x,a.positionPrev.y=a.position.y-b.y,a.velocity.x=b.x,a.velocity.y=b.y,a.speed=z.magnitude(a.velocity)},b.setAngularVelocity=function(a,b){a.anglePrev=a.angle-b,a.angularVelocity=b,a.angularSpeed=Math.abs(a.angularVelocity)},b.translate=function(a,c){b.setPosition(a,z.add(a.position,c))},b.rotate=function(a,c){b.setAngle(a,a.angle+c)},b.scale=function(a,c,d){for(var e=0;e0&&(j.position.x+=a.velocity.x,j.position.y+=a.velocity.y),0!==a.angularVelocity&&(A.rotate(j.vertices,a.angularVelocity,a.position),w.rotate(j.axes,a.angularVelocity),i>0&&z.rotateAbout(j.position,a.angularVelocity,a.position,j.position)),x.update(j.bounds,j.vertices,a.velocity)}},b.applyForce=function(a,b,c){a.force.x+=c.x,a.force.y+=c.y;var d={x:b.x-a.position.x,y:b.y-a.position.y};a.torque+=(d.x*c.y-d.y*c.x)*a.inverseInertia};var f=function(a){for(var b={mass:0,area:0,inertia:0,centre:{x:0,y:0}},c=1===a.parts.length?0:1;c1?1:0;j1?1:0;m0:0!==(a.mask&b.category)&&0!==(b.mask&a.category)}}();var g={};!function(){g.create=function(a){var b={controller:g,detector:f.collisions,buckets:{},pairs:{},pairsList:[],bucketWidth:48,bucketHeight:48};return o.extend(b,a)},g.update=function(c,f,g,h){var l,m,n,o,p,q=g.world,r=c.buckets,s=!1;for(l=0;lq.bounds.width||t.bounds.max.y<0||t.bounds.min.y>q.bounds.height)){var u=b(c,t);if(!t.region||u.id!==t.region.id||h){(!t.region||h)&&(t.region=u);var v=a(u,t.region);for(m=v.startCol;m<=v.endCol;m++)for(n=v.startRow;n<=v.endRow;n++){p=d(m,n),o=r[p];var w=m>=u.startCol&&m<=u.endCol&&n>=u.startRow&&n<=u.endRow,x=m>=t.region.startCol&&m<=t.region.endCol&&n>=t.region.startRow&&n<=t.region.endRow;!w&&x&&x&&o&&j(c,o,t),(t.region===u||w&&!x||h)&&(o||(o=e(r,p)),i(c,o,t))}t.region=u,s=!0}}}s&&(c.pairsList=k(c))},g.clear=function(a){a.buckets={},a.pairs={},a.pairsList=[]};var a=function(a,b){var d=Math.min(a.startCol,b.startCol),e=Math.max(a.endCol,b.endCol),f=Math.min(a.startRow,b.startRow),g=Math.max(a.endRow,b.endRow);return c(d,e,f,g)},b=function(a,b){var d=b.bounds,e=Math.floor(d.min.x/a.bucketWidth),f=Math.floor(d.max.x/a.bucketWidth),g=Math.floor(d.min.y/a.bucketHeight),h=Math.floor(d.max.y/a.bucketHeight);return c(e,f,g,h)},c=function(a,b,c,d){return{id:a+","+b+","+c+","+d,startCol:a,endCol:b,startRow:c,endRow:d}},d=function(a,b){return a+","+b},e=function(a,b){var c=a[b]=[];return c},i=function(a,b,c){for(var d=0;d0?d.push(c):delete a.pairs[b[e]];return d}}();var h={};!function(){h.create=function(a,b){var c=a.bodyA,d=a.bodyB,e=a.parentA,f=a.parentB,g={id:h.id(c,d),bodyA:c,bodyB:d,contacts:{},activeContacts:[],separation:0,isActive:!0,timeCreated:b,timeUpdated:b,inverseMass:e.inverseMass+f.inverseMass,friction:Math.min(e.friction,f.friction),frictionStatic:Math.max(e.frictionStatic,f.frictionStatic),restitution:Math.max(e.restitution,f.restitution),slop:Math.max(e.slop,f.slop)};return h.update(g,a,b),g},h.update=function(a,b,c){var d=a.contacts,f=b.supports,g=a.activeContacts,i=b.parentA,j=b.parentB;if(a.collision=b,a.inverseMass=i.inverseMass+j.inverseMass,a.friction=Math.min(i.friction,j.friction),a.frictionStatic=Math.max(i.frictionStatic,j.frictionStatic),a.restitution=Math.max(i.restitution,j.restitution),a.slop=Math.max(i.slop,j.slop),g.length=0,b.collided){for(var k=0;ka&&j.push(g);for(g=0;gl.friction*l.frictionStatic*I*c&&(J=l.friction*G*c,K=F);var L=z.cross(x,q),M=z.cross(y,q),N=n.inverseMass+p.inverseMass+n.inverseInertia*L*L+p.inverseInertia*M*M;if(H*=t/N,J*=t/(1+N),0>D&&D*D>k._restingThresh*c)v.normalImpulse=0,v.tangentImpulse=0;else{var O=v.normalImpulse;v.normalImpulse=Math.min(v.normalImpulse+H,0),H=v.normalImpulse-O;var P=v.tangentImpulse;v.tangentImpulse=o.clamp(v.tangentImpulse+J,-K,K),J=v.tangentImpulse-P}d.x=q.x*H+r.x*J,d.y=q.y*H+r.y*J,n.isStatic||n.isSleeping||(n.positionPrev.x+=d.x*n.inverseMass,n.positionPrev.y+=d.y*n.inverseMass,n.anglePrev+=z.cross(x,d)*n.inverseInertia),p.isStatic||p.isSleeping||(p.positionPrev.x-=d.x*p.inverseMass,p.positionPrev.y-=d.y*p.inverseMass,p.anglePrev-=z.cross(y,d)*p.inverseInertia)}}}}}();var l={};!function(){l.collides=function(b,d,e){var f,g,h,i,j=e,k=!1;if(j){var l=b.parent,m=d.parent,n=l.speed*l.speed+l.angularSpeed*l.angularSpeed+m.speed*m.speed+m.angularSpeed*m.angularSpeed;k=j&&j.collided&&.2>n,i=j}else i={collided:!1,bodyA:b,bodyB:d};if(j&&k){var o=i.axisBody,p=o===b?d:b,q=[o.axes[j.axisNumber]];if(h=a(o.vertices,p.vertices,q),i.reused=!0,h.overlap<=0)return i.collided=!1,i}else{if(f=a(b.vertices,d.vertices,b.axes),f.overlap<=0)return i.collided=!1,i;if(g=a(d.vertices,b.vertices,d.axes),g.overlap<=0)return i.collided=!1,i;f.overlap0&&(i.normal=z.neg(i.normal)),i.tangent=z.perp(i.normal),i.penetration={x:i.normal.x*i.depth,y:i.normal.y*i.depth};var r=c(b,d,i.normal),s=i.supports||[];if(s.length=0,A.contains(b.vertices,r[0])&&s.push(r[0]),A.contains(b.vertices,r[1])&&s.push(r[1]),s.length<2){var t=c(d,b,z.neg(i.normal));A.contains(d.vertices,t[0])&&s.push(t[0]),s.length<2&&A.contains(d.vertices,t[1])&&s.push(t[1])}return s.length<1&&(s=[r[0]]),i.supports=s,i};var a=function(a,c,d){for(var e,f,g=z._temp[0],h=z._temp[1],i={overlap:Number.MAX_VALUE},j=0;j=e)return i.overlap=e,i;ee?e=g:d>g&&(d=g)}a.min=d,a.max=e},c=function(a,b,c){for(var d,e,f,g,h=Number.MAX_VALUE,i=z._temp[0],j=b.vertices,k=a.position,l=0;ld&&(h=d,f=e);var m=f.index-1>=0?f.index-1:j.length-1;e=j[m],i.x=e.x-k.x,i.y=e.y-k.y,h=-z.dot(c,i),g=e;var n=(f.index+1)%j.length;return e=j[n],i.x=e.x-k.x,i.y=e.y-k.y,d=-z.dot(c,i),h>d&&(g=e),[f,g]}}();var m={};!function(){var a=1e-6,b=.001;m.create=function(b){var c=b;c.bodyA&&!c.pointA&&(c.pointA={x:0,y:0}),c.bodyB&&!c.pointB&&(c.pointB={x:0,y:0});var d=c.bodyA?z.add(c.bodyA.position,c.pointA):c.pointA,e=c.bodyB?z.add(c.bodyB.position,c.pointB):c.pointB,f=z.magnitude(z.sub(d,e));c.length=c.length||f||a;var g={visible:!0,lineWidth:2,strokeStyle:"#666"};return c.render=o.extend(g,c.render),c.id=c.id||o.nextId(),c.label=c.label||"Constraint",c.type="constraint",c.stiffness=c.stiffness||1,c.angularStiffness=c.angularStiffness||0,c.angleA=c.bodyA?c.bodyA.angle:c.angleA,c.angleB=c.bodyB?c.bodyB.angle:c.angleB,c},m.solveAll=function(a,b){for(var c=0;c0&&(B=0);var C,D={x:n.x*B,y:n.y*B};e&&!e.isStatic&&(C=z.cross(s,D)*e.inverseInertia*(1-c.angularStiffness),t.set(e,!1),C=o.clamp(C,-.01,.01),e.constraintImpulse.x-=p.x,e.constraintImpulse.y-=p.y,e.constraintImpulse.angle+=C,e.position.x-=p.x,e.position.y-=p.y,e.angle+=C),f&&!f.isStatic&&(C=z.cross(u,D)*f.inverseInertia*(1-c.angularStiffness),t.set(f,!1),C=o.clamp(C,-.01,.01),f.constraintImpulse.x+=p.x,f.constraintImpulse.y+=p.y,f.constraintImpulse.angle-=C,f.position.x+=p.x,f.position.y+=p.y,f.angle-=C)}}},m.postSolveAll=function(a){for(var b=0;b0&&(f.position.x+=d.x,f.position.y+=d.y),0!==d.angle&&(A.rotate(f.vertices,d.angle,c.position),w.rotate(f.axes,d.angle),e>0&&z.rotateAbout(f.position,d.angle,c.position,f.position)),x.update(f.bounds,f.vertices)}d.angle=0,d.x=0,d.y=0}}}();var n={};!function(){n.create=function(b,d){var e=(b?b.mouse:null)||(d?d.mouse:null);!e&&b&&b.render&&b.render.canvas?e=r.create(b.render.canvas):(e=r.create(),o.log("MouseConstraint.create: options.mouse was undefined, engine.render.canvas was undefined, may not function as expected","warn"));var f=m.create({label:"Mouse Constraint",pointA:e.position,pointB:{x:0,y:0},length:.01,stiffness:.1,angularStiffness:1,render:{strokeStyle:"#90EE90",lineWidth:3}}),g={type:"mouseConstraint",mouse:e,body:null,constraint:f,collisionFilter:{category:1,mask:4294967295,group:0}},h=o.extend(g,d);return q.on(b,"tick",function(){var d=c.allBodies(b.world);n.update(h,d),a(h)}),h},n.update=function(a,b){var c=a.mouse,d=a.constraint,e=a.body;if(0===c.button){if(d.bodyB)t.set(d.bodyB,!1),d.pointA=c.position;else for(var g=0;g1?1:0;h>16)+d,f=(c>>8&255)+d,g=(255&c)+d;return"#"+(16777216+65536*(255>e?1>e?0:e:255)+256*(255>f?1>f?0:f:255)+(255>g?1>g?0:g:255)).toString(16).slice(1)},o.shuffle=function(a){for(var b=a.length-1;b>0;b--){var c=Math.floor(o.random()*(b+1)),d=a[b];a[b]=a[c],a[c]=d}return a},o.choose=function(a){return a[Math.floor(o.random()*a.length)]},o.isElement=function(a){try{return a instanceof HTMLElement}catch(b){return"object"==typeof a&&1===a.nodeType&&"object"==typeof a.style&&"object"==typeof a.ownerDocument}},o.isArray=function(a){return"[object Array]"===Object.prototype.toString.call(a)},o.clamp=function(a,b,c){return b>a?b:a>c?c:a},o.sign=function(a){return 0>a?-1:1},o.now=function(){var a=window.performance||{};return a.now=function(){return a.now||a.webkitNow||a.msNow||a.oNow||a.mozNow||function(){return+new Date}}(),a.now()},o.random=function(b,c){return b="undefined"!=typeof b?b:0,c="undefined"!=typeof c?c:1,b+a()*(c-b)},o.colorToNumber=function(a){return a=a.replace("#",""),3==a.length&&(a=a.charAt(0)+a.charAt(0)+a.charAt(1)+a.charAt(1)+a.charAt(2)+a.charAt(2)),parseInt(a,16)},o.log=function(a,b){if(console&&console.log&&console.warn)switch(b){case"warn":console.warn("Matter.js:",a);break;case"error":console.log("Matter.js:",a)}},o.nextId=function(){return o._nextId++},o.indexOf=function(a,b){if(a.indexOf)return a.indexOf(b);for(var c=0;c0&&q.trigger(b,"collisionStart",{pairs:v.collisionStart}),k.preSolvePosition(v.list),h=0;h0&&q.trigger(b,"collisionActive",{pairs:v.collisionActive}),v.collisionEnd.length>0&&q.trigger(b,"collisionEnd",{pairs:v.collisionEnd}),a(r),j.isModified&&c.setModified(j,!1,!1,!0),q.trigger(b,"afterUpdate",p),b},p.merge=function(a,b){if(o.extend(a,b),b.world){a.world=b.world,p.clear(a);for(var d=c.allBodies(a.world),e=0;ea.deltaMax?a.deltaMax:d,f=d/a.delta,a.delta=d),0!==a.timeScalePrev&&(f*=e.timeScale/a.timeScalePrev),0===e.timeScale&&(f=0),a.timeScalePrev=e.timeScale,a.correction=f,a.frameCounter+=1,c-a.counterTimestamp>=1e3&&(a.fps=a.frameCounter*((c-a.counterTimestamp)/1e3),a.counterTimestamp=c,a.frameCounter=0),q.trigger(a,"tick",g),q.trigger(b,"tick",g),b.world.isModified&&b.render&&b.render.controller&&b.render.controller.clear&&b.render.controller.clear(b.render),q.trigger(a,"beforeUpdate",g),p.update(b,d,f),q.trigger(a,"afterUpdate",g),b.render&&(q.trigger(a,"beforeRender",g),q.trigger(b,"beforeRender",g),b.render.controller.world(b),q.trigger(a,"afterRender",g),q.trigger(b,"afterRender",g)),q.trigger(a,"afterTick",g),q.trigger(b,"afterTick",g)},s.stop=function(a){b(a.frameRequestId)}}}();var t={};!function(){t._motionWakeThreshold=.18,t._motionSleepThreshold=.08,t._minBias=.9,t.update=function(a,b){for(var c=b*b*b,d=0;d0&&e.motion=e.sleepThreshold&&t.set(e,!0)):e.sleepCounter>0&&(e.sleepCounter-=1)}else t.set(e,!1)}},t.afterCollisions=function(a,b){for(var c=b*b*b,d=0;dt._motionWakeThreshold*c&&t.set(i,!1)}}}},t.set=function(a,b){var c=a.isSleeping;b?(a.isSleeping=!0,a.sleepCounter=a.sleepThreshold,a.positionImpulse.x=0,a.positionImpulse.y=0,a.positionPrev.x=a.position.x,a.positionPrev.y=a.position.y,a.anglePrev=a.angle,a.speed=0,a.angularSpeed=0,a.motion=0,c||q.trigger(a,"sleepStart")):(a.isSleeping=!1,a.sleepCounter=0,c&&q.trigger(a,"sleepEnd"))}}();var u={};!function(){u.rectangle=function(a,c,d,e,f){f=f||{};var g={label:"Rectangle Body",position:{x:a,y:c},vertices:A.fromPath("L 0 0 L "+d+" 0 L "+d+" "+e+" L 0 "+e)};if(f.chamfer){var h=f.chamfer;g.vertices=A.chamfer(g.vertices,h.radius,h.quality,h.qualityMin,h.qualityMax),delete f.chamfer}return b.create(o.extend({},g,f))},u.trapezoid=function(a,c,d,e,f,g){g=g||{},f*=.5;var h=(1-2*f)*d,i=d*f,j=i+h,k=j+i,l={label:"Trapezoid Body",position:{x:a,y:c},vertices:A.fromPath("L 0 0 L "+i+" "+-e+" L "+j+" "+-e+" L "+k+" 0")};if(g.chamfer){var m=g.chamfer;l.vertices=A.chamfer(l.vertices,m.radius,m.quality,m.qualityMin,m.qualityMax),delete g.chamfer}return b.create(o.extend({},l,g))},u.circle=function(a,b,c,d,e){d=d||{},d.label="Circle Body",e=e||25;var f=Math.ceil(Math.max(10,Math.min(e,c)));return f%2===1&&(f+=1),d.circleRadius=c,u.polygon(a,b,f,c,d)},u.polygon=function(a,c,d,e,f){if(f=f||{},3>d)return u.circle(a,c,e,f);for(var g=2*Math.PI/d,h="",i=.5*g,j=0;d>j;j+=1){var k=i+j*g,l=Math.cos(k)*e,m=Math.sin(k)*e;h+="L "+l.toFixed(3)+" "+m.toFixed(3)+" "}var n={label:"Polygon Body",position:{x:a,y:c},vertices:A.fromPath(h)};if(f.chamfer){var p=f.chamfer;n.vertices=A.chamfer(n.vertices,p.radius,p.quality,p.qualityMin,p.qualityMax),delete f.chamfer}return b.create(o.extend({},n,f))},u.fromVertices=function(a,c,d,e,f,g,h){var i,j,k,l,m,n,p,q,r;for(e=e||{},j=[],f="undefined"!=typeof f?f:!1,g="undefined"!=typeof g?g:.01,h="undefined"!=typeof h?h:10,window.decomp||o.log("Bodies.fromVertices: poly-decomp.js required. Could not decompose vertices. Fallback to convex hull.","warn"),o.isArray(d[0])||(d=[d]),q=0;q0&&A.area(v)E&&w>F&&(C[p].isInternal=!0,D[r].isInternal=!0)}}}}}return j.length>1?(i=b.create(o.extend({parts:j.slice(0)},e)),b.setPosition(i,{x:a,y:c}),i):j[0]}}();var v={};!function(){v.stack=function(a,d,e,f,g,h,i){for(var j,k=c.create({label:"Stack"}),l=a,m=d,n=0,o=0;f>o;o++){for(var p=0,q=0;e>q;q++){var r=i(l,m,q,o,j,n);if(r){var s=r.bounds.max.y-r.bounds.min.y,t=r.bounds.max.x-r.bounds.min.x;s>p&&(p=s),b.translate(r,{x:.5*t,y:.5*s}),l=r.bounds.max.x+g,c.addBody(k,r),j=r,n+=1}else l+=g}m+=p+h,l=a}return k},v.chain=function(a,b,d,e,f,g){for(var h=a.bodies,i=1;ig;g++){for(h=1;b>h;h++)i=l[h-1+g*b],j=l[h+g*b],c.addConstraint(a,m.create(o.extend({bodyA:i,bodyB:j},f)));if(g>0)for(h=0;b>h;h++)i=l[h+(g-1)*b],j=l[h+g*b],c.addConstraint(a,m.create(o.extend({bodyA:i,bodyB:j},f))),e&&h>0&&(k=l[h-1+(g-1)*b],c.addConstraint(a,m.create(o.extend({bodyA:k,bodyB:j},f)))),e&&b-1>h&&(k=l[h+1+(g-1)*b],c.addConstraint(a,m.create(o.extend({bodyA:k,bodyB:j},f))))}return a.label+=" Mesh",a},v.pyramid=function(a,c,d,e,f,g,h){return v.stack(a,c,d,e,f,g,function(c,g,i,j,k,l){var m=Math.min(e,Math.ceil(d/2)),n=k?k.bounds.max.x-k.bounds.min.x:0;if(!(j>m)){j=m-j;var o=j,p=d-1-j;if(!(o>i||i>p)){1===l&&b.translate(k,{x:(i+(d%2===1?1:-1))*n,y:0});var q=k?i*n:0;return h(a+q+i*f,g,i,j,k,l)}}})},v.newtonsCradle=function(a,b,d,e,f){for(var g=c.create({label:"Newtons Cradle"}),h=0;d>h;h++){var i=1.9,j=u.circle(a+h*e*i,b+f,e,{inertia:99999,restitution:1,friction:0,frictionAir:1e-4,slop:.01}),k=m.create({pointA:{x:a+h*e*i,y:b},bodyB:j});c.addBody(g,j),c.addConstraint(g,k)}return g},v.car=function(a,d,e,f,g){var h=b.nextGroup(!0),i=-20,j=.5*-e+i,k=.5*e-i,l=0,n=c.create({label:"Car"}),o=u.trapezoid(a,d,e,f,.3,{collisionFilter:{group:h},friction:.01,chamfer:{radius:10}}),p=u.circle(a+j,d+l,g,{collisionFilter:{group:h},restitution:.5,friction:.9,frictionStatic:10,slop:.5,density:.01}),q=u.circle(a+k,d+l,g,{collisionFilter:{group:h},restitution:.5,friction:.9,frictionStatic:10,slop:.5,density:.01}),r=m.create({bodyA:o,pointA:{x:j,y:l},bodyB:p,stiffness:.5}),s=m.create({bodyA:o,pointA:{x:k,y:l},bodyB:q,stiffness:.5});return c.addBody(n,o),c.addBody(n,p),c.addBody(n,q),c.addConstraint(n,r),c.addConstraint(n,s),n},v.softBody=function(a,b,c,d,e,f,g,h,i,j){i=o.extend({inertia:1/0},i),j=o.extend({stiffness:.4},j);var k=v.stack(a,b,c,d,e,f,function(a,b){return u.circle(a,b,h,i)});return v.mesh(k,c,d,g,j),k.label="Soft Body",k}}();var w={};!function(){w.fromVertices=function(a){for(var b={},c=0;ca.max.x&&(a.max.x=e.x),e.xa.max.y&&(a.max.y=e.y),e.y0?a.max.x+=c.x:a.min.x+=c.x,c.y>0?a.max.y+=c.y:a.min.y+=c.y)},x.contains=function(a,b){return b.x>=a.min.x&&b.x<=a.max.x&&b.y>=a.min.y&&b.y<=a.max.y},x.overlaps=function(a,b){return a.min.x<=b.max.x&&a.max.x>=b.min.x&&a.max.y>=b.min.y&&a.min.y<=b.max.y},x.translate=function(a,b){a.min.x+=b.x,a.max.x+=b.x,a.min.y+=b.y,a.max.y+=b.y},x.shift=function(a,b){var c=a.max.x-a.min.x,d=a.max.y-a.min.y;a.min.x=b.x,a.max.x=b.x+c,a.min.y=b.y,a.max.y=b.y+d}}();var y={};!function(){y.pathToVertices=function(b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p=[],q=0,r=0,s=0;c=c||15;var t=function(a,b,c){var d=c%2===1&&c>1;if(!l||a!=l.x||b!=l.y){l&&d?(n=l.x,o=l.y):(n=0,o=0);var e={x:n+a,y:o+b};(d||!l)&&(l=e),p.push(e),r=n+a,s=o+b}},u=function(a){var b=a.pathSegTypeAsLetter.toUpperCase();if("Z"!==b){switch(b){case"M":case"L":case"T":case"C":case"S":case"Q":r=a.x,s=a.y;break;case"H":r=a.x;break;case"V":s=a.y}t(r,s,a.pathSegType)}};for(a(b),f=b.getTotalLength(),i=[],d=0;dq;){if(m=b.getPathSegAtLength(q),h=i[m],h!=k){for(;j.length&&j[0]!=h;)u(j.shift());k=h}switch(h.pathSegTypeAsLetter.toUpperCase()){case"C":case"T":case"S":case"Q":case"A":g=b.getPointAtLength(q),t(g.x,g.y,0)}q+=c}for(d=0,e=j.length;e>d;++d)u(j[d]);return p};var a=function(a){for(var b,c,d,e,f,g,h=a.pathSegList,i=0,j=0,k=h.numberOfItems,l=0;k>l;++l){var m=h.getItem(l),n=m.pathSegTypeAsLetter;if(/[MLHVCSQTA]/.test(n))"x"in m&&(i=m.x),"y"in m&&(j=m.y);else switch("x1"in m&&(d=i+m.x1),"x2"in m&&(f=i+m.x2),"y1"in m&&(e=j+m.y1),"y2"in m&&(g=j+m.y2),"x"in m&&(i+=m.x),"y"in m&&(j+=m.y),n){case"m":h.replaceItem(a.createSVGPathSegMovetoAbs(i,j),l);break;case"l":h.replaceItem(a.createSVGPathSegLinetoAbs(i,j),l);break;case"h":h.replaceItem(a.createSVGPathSegLinetoHorizontalAbs(i),l);break;case"v":h.replaceItem(a.createSVGPathSegLinetoVerticalAbs(j),l);break;case"c":h.replaceItem(a.createSVGPathSegCurvetoCubicAbs(i,j,d,e,f,g),l);break;case"s":h.replaceItem(a.createSVGPathSegCurvetoCubicSmoothAbs(i,j,f,g),l);break;case"q":h.replaceItem(a.createSVGPathSegCurvetoQuadraticAbs(i,j,d,e),l);break;case"t":h.replaceItem(a.createSVGPathSegCurvetoQuadraticSmoothAbs(i,j),l);break;case"a":h.replaceItem(a.createSVGPathSegArcAbs(i,j,m.r1,m.r2,m.angle,m.largeArcFlag,m.sweepFlag),l);break;case"z":case"Z":i=b,j=c}("M"==n||"m"==n)&&(b=i,c=j)}}}();var z={};!function(){z.create=function(a,b){return{x:a||0,y:b||0}},z.clone=function(a){return{x:a.x,y:a.y}},z.magnitude=function(a){return Math.sqrt(a.x*a.x+a.y*a.y)},z.magnitudeSquared=function(a){return a.x*a.x+a.y*a.y},z.rotate=function(a,b){var c=Math.cos(b),d=Math.sin(b);return{x:a.x*c-a.y*d,y:a.x*d+a.y*c}},z.rotateAbout=function(a,b,c,d){var e=Math.cos(b),f=Math.sin(b);d||(d={});var g=c.x+((a.x-c.x)*e-(a.y-c.y)*f);return d.y=c.y+((a.x-c.x)*f+(a.y-c.y)*e),d.x=g,d},z.normalise=function(a){var b=z.magnitude(a);return 0===b?{x:0,y:0}:{x:a.x/b,y:a.y/b}},z.dot=function(a,b){return a.x*b.x+a.y*b.y},z.cross=function(a,b){return a.x*b.y-a.y*b.x},z.cross3=function(a,b,c){return(b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x)},z.add=function(a,b,c){return c||(c={}),c.x=a.x+b.x,c.y=a.y+b.y,c},z.sub=function(a,b,c){return c||(c={}),c.x=a.x-b.x,c.y=a.y-b.y,c},z.mult=function(a,b){return{x:a.x*b,y:a.y*b}},z.div=function(a,b){return{x:a.x/b,y:a.y/b}},z.perp=function(a,b){return b=b===!0?-1:1,{x:b*-a.y,y:b*a.x}},z.neg=function(a){return{x:-a.x,y:-a.y}},z.angle=function(a,b){return Math.atan2(b.y-a.y,b.x-a.x)},z._temp=[z.create(),z.create(),z.create(),z.create(),z.create(),z.create()]}();var A={};!function(){A.create=function(a,b){for(var c=[],d=0;d0)return!1}return!0},A.scale=function(a,b,c,d){if(1===b&&1===c)return a;d=d||A.centre(a);for(var e,f,g=0;g=0?g-1:a.length-1],i=a[g],j=a[(g+1)%a.length],k=b[gv;v++)f.push(z.add(z.rotate(p,u*v),r))}else f.push(i)}return f},A.clockwiseSort=function(a){var b=A.mean(a);return a.sort(function(a,c){return z.angle(b,a)-z.angle(b,c)}),a},A.isConvex=function(a){var b,c,d,e,f=0,g=a.length;if(3>g)return null;for(b=0;g>b;b++)if(c=(b+1)%g,d=(b+2)%g,e=(a[c].x-a[b].x)*(a[d].y-a[c].y),e-=(a[c].y-a[b].y)*(a[d].x-a[c].x),0>e?f|=1:e>0&&(f|=2),3===f)return!1;return 0!==f?!0:null},A.hull=function(a){var b,c,d=[],e=[];for(a=a.slice(0),a.sort(function(a,b){var c=a.x-b.x;return 0!==c?c:a.y-b.y}),c=0;c=2&&z.cross3(e[e.length-2],e[e.length-1],b)<=0;)e.pop();e.push(b)}for(c=a.length-1;c>=0;c--){for(b=a[c];d.length>=2&&z.cross3(d[d.length-2],d[d.length-1],b)<=0;)d.pop();d.push(b)}return d.pop(),e.pop(),d.concat(e)}}();var B={};!function(){B.create=function(b){var c={controller:B,element:null,canvas:null,options:{width:800,height:600,pixelRatio:1,background:"#fafafa",wireframeBackground:"#222",hasBounds:!1,enabled:!0,wireframes:!0,showSleeping:!0,showDebug:!1,showBroadphase:!1,showBounds:!1,showVelocity:!1,showCollisions:!1,showSeparations:!1,showAxes:!1,showPositions:!1,showAngleIndicator:!1,showIds:!1,showShadows:!1,showVertexNumbers:!1,showConvexHulls:!1,showInternalEdges:!1}},d=o.extend(c,b);return d.canvas=d.canvas||a(d.options.width,d.options.height),d.context=d.canvas.getContext("2d"),d.textures={},d.bounds=d.bounds||{min:{x:0,y:0},max:{x:d.options.width,y:d.options.height}},1!==d.options.pixelRatio&&B.setPixelRatio(d,d.options.pixelRatio),o.isElement(d.element)?d.element.appendChild(d.canvas):o.log("Render.create: options.element was undefined, render.canvas was created but not appended","warn"),d},B.setPixelRatio=function(a,c){var d=a.options,e=a.canvas;"auto"===c&&(c=b(e)),d.pixelRatio=c,e.setAttribute("data-pixel-ratio",c),e.width=d.width*c,e.height=d.height*c,e.style.width=d.width+"px",e.style.height=d.height+"px",a.context.scale(c,c)},B.world=function(a){var b,d=a.render,f=a.world,h=d.canvas,i=d.context,j=d.options,k=c.allBodies(f),l=c.allConstraints(f),m=j.wireframes?j.wireframeBackground:j.background,n=[],o=[],p={timestamp:a.timing.timestamp};if(q.trigger(d,"beforeRender",p),d.currentBackground!==m&&e(d,m),i.globalCompositeOperation="source-in",i.fillStyle="transparent",i.fillRect(0,0,h.width,h.height),i.globalCompositeOperation="source-over",j.hasBounds){var r=d.bounds.max.x-d.bounds.min.x,s=d.bounds.max.y-d.bounds.min.y,t=r/j.width,u=s/j.height;for(b=0;b=500){var i="";i+="fps: "+Math.round(a.timing.fps)+h,f.debugString=i,f.debugTimestamp=a.timing.timestamp}if(f.debugString){d.font="12px Arial",d.fillStyle=g.wireframes?"rgba(255,255,255,0.5)":"rgba(0,0,0,0.5)";for(var j=f.debugString.split("\n"),k=0;k1?1:0;h1?1:0;h1?1:0;f1?1:0;j1?1:0;f1?1:0;f1?1:0;e0)){var l=d.activeContacts[0].vertex.x,m=d.activeContacts[0].vertex.y;2===d.activeContacts.length&&(l=(d.activeContacts[0].vertex.x+d.activeContacts[1].vertex.x)/2,m=(d.activeContacts[0].vertex.y+d.activeContacts[1].vertex.y)/2),e.bodyB===e.supports[0].body||e.bodyA.isStatic===!0?h.moveTo(l-8*e.normal.x,m-8*e.normal.y):h.moveTo(l+8*e.normal.x,m+8*e.normal.y),h.lineTo(l,m)}h.strokeStyle=i.wireframes?"rgba(255,165,0,0.7)":"orange",h.lineWidth=1,h.stroke()},B.separations=function(a,b,c){var d,e,f,g,h,i=c,j=a.render.options;for(i.beginPath(),h=0;h1?1:0;l