diff --git a/cocos2d/core/components/index.js b/cocos2d/core/components/index.js
index 35d462953b..e10ad7e1ec 100644
--- a/cocos2d/core/components/index.js
+++ b/cocos2d/core/components/index.js
@@ -44,8 +44,6 @@ var components = [
require('./CCSlider'),
require('./CCLayout'),
require('./editbox/CCEditBox'),
- require('./CCVideoPlayer'),
- require('./CCWebView'),
require('./CCLabelOutline'),
require('./CCRichText'),
require('./CCToggleContainer'),
diff --git a/cocos2d/core/renderer/assemblers/index.js b/cocos2d/core/renderer/assemblers/index.js
index cfdea2d662..daf5bea9fa 100644
--- a/cocos2d/core/renderer/assemblers/index.js
+++ b/cocos2d/core/renderer/assemblers/index.js
@@ -25,8 +25,5 @@
require('./sprite/sprite-assembler');
require('./mask-assembler');
-require('./particle-system-assembler');
-require('./motion-streak-assembler');
require('./graphics/graphics-assembler');
require('./label/label-assembler');
-require('./tmx-layer-assembler');
diff --git a/cocos2d/motion-streak/index.js b/cocos2d/motion-streak/index.js
new file mode 100644
index 0000000000..505944d9e3
--- /dev/null
+++ b/cocos2d/motion-streak/index.js
@@ -0,0 +1,27 @@
+/****************************************************************************
+ Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos.com
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+require('./CCMotionStreak');
+require('./motion-streak-assembler');
\ No newline at end of file
diff --git a/cocos2d/core/renderer/assemblers/motion-streak-assembler.js b/cocos2d/motion-streak/motion-streak-assembler.js
similarity index 96%
rename from cocos2d/core/renderer/assemblers/motion-streak-assembler.js
rename to cocos2d/motion-streak/motion-streak-assembler.js
index 5c144d9a45..184891f3a4 100644
--- a/cocos2d/core/renderer/assemblers/motion-streak-assembler.js
+++ b/cocos2d/motion-streak/motion-streak-assembler.js
@@ -23,10 +23,10 @@
THE SOFTWARE.
****************************************************************************/
-const js = require('../../platform/js');
-const assembler = require('./assembler');
-const MotionStreak = require('../../../motion-streak/CCMotionStreak');
-const renderEngine = require('../render-engine');
+const js = require('../core/platform/js');
+const assembler = require('../core/renderer/assemblers/assembler');
+const MotionStreak = require('./CCMotionStreak');
+const renderEngine = require('../core/renderer/render-engine');
function Point (point, dir) {
this.point = point || cc.v2();
diff --git a/cocos2d/particle/index.js b/cocos2d/particle/index.js
new file mode 100644
index 0000000000..4d0fd80e11
--- /dev/null
+++ b/cocos2d/particle/index.js
@@ -0,0 +1,27 @@
+/****************************************************************************
+ Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos.com
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+require('./CCParticleSystem');
+require('./particle-system-assembler');
\ No newline at end of file
diff --git a/cocos2d/core/renderer/assemblers/particle-system-assembler.js b/cocos2d/particle/particle-system-assembler.js
similarity index 94%
rename from cocos2d/core/renderer/assemblers/particle-system-assembler.js
rename to cocos2d/particle/particle-system-assembler.js
index 02c0ed4842..68a2e793bc 100644
--- a/cocos2d/core/renderer/assemblers/particle-system-assembler.js
+++ b/cocos2d/particle/particle-system-assembler.js
@@ -23,10 +23,10 @@
THE SOFTWARE.
****************************************************************************/
-const js = require('../../platform/js');
-const assembler = require('./assembler');
-const ParticleSystem = require('../../../particle/CCParticleSystem');
-const renderEngine = require('../render-engine');
+const js = require('../core/platform/js');
+const assembler = require('../core/renderer/assemblers/assembler');
+const ParticleSystem = require('./CCParticleSystem');
+const renderEngine = require('../core/renderer/render-engine');
var particleSystemAssembler = js.addon({
useModel: true,
diff --git a/cocos2d/tilemap/index.js b/cocos2d/tilemap/index.js
new file mode 100644
index 0000000000..cc3fc3d38c
--- /dev/null
+++ b/cocos2d/tilemap/index.js
@@ -0,0 +1,27 @@
+/****************************************************************************
+ Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos.com
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+require('./CCTiledMap');
+require('./tmx-layer-assembler');
\ No newline at end of file
diff --git a/cocos2d/core/renderer/assemblers/tmx-layer-assembler.js b/cocos2d/tilemap/tmx-layer-assembler.js
similarity index 98%
rename from cocos2d/core/renderer/assemblers/tmx-layer-assembler.js
rename to cocos2d/tilemap/tmx-layer-assembler.js
index e22787edfd..660d6f3564 100644
--- a/cocos2d/core/renderer/assemblers/tmx-layer-assembler.js
+++ b/cocos2d/tilemap/tmx-layer-assembler.js
@@ -23,12 +23,12 @@
THE SOFTWARE.
****************************************************************************/
-const TiledLayer = require('../../../tilemap/CCTiledLayer');
-const TiledMap = require('../../../tilemap/CCTiledMap');
+const TiledLayer = require('./CCTiledLayer');
+const TiledMap = require('./CCTiledMap');
-const js = require('../../platform/js');
-const assembler = require('./assembler');
-const renderEngine = require('../render-engine');
+const js = require('../core/platform/js');
+const assembler = require('../core/renderer/assemblers/assembler');
+const renderEngine = require('../core/renderer/render-engine');
const Orientation = TiledMap.Orientation;
const TileFlag = TiledMap.TileFlag;
diff --git a/cocos2d/core/components/CCVideoPlayer.js b/cocos2d/videoplayer/CCVideoPlayer.js
similarity index 99%
rename from cocos2d/core/components/CCVideoPlayer.js
rename to cocos2d/videoplayer/CCVideoPlayer.js
index 04240808a7..103816b596 100644
--- a/cocos2d/core/components/CCVideoPlayer.js
+++ b/cocos2d/videoplayer/CCVideoPlayer.js
@@ -19,7 +19,7 @@
THE SOFTWARE.
****************************************************************************/
-let VideoPlayerImpl = require('../videoplayer/video-player-impl');
+let VideoPlayerImpl = require('./video-player-impl');
/**
* !#en Video event type
diff --git a/cocos2d/core/videoplayer/video-player-impl.js b/cocos2d/videoplayer/video-player-impl.js
similarity index 99%
rename from cocos2d/core/videoplayer/video-player-impl.js
rename to cocos2d/videoplayer/video-player-impl.js
index df5716cbe2..b8d29ebf35 100644
--- a/cocos2d/core/videoplayer/video-player-impl.js
+++ b/cocos2d/videoplayer/video-player-impl.js
@@ -19,8 +19,8 @@
THE SOFTWARE.
****************************************************************************/
-const Utils = require('../platform/utils');
-const sys = require('../platform/CCSys');
+var Utils = require('../core/platform/utils');
+var sys = require('../core/platform/CCSys');
let VideoPlayerImpl = cc.Class({
name: 'VideoPlayerImpl',
diff --git a/cocos2d/webview/CCWebView.js b/cocos2d/webview/CCWebView.js
new file mode 100644
index 0000000000..ed303d30c6
--- /dev/null
+++ b/cocos2d/webview/CCWebView.js
@@ -0,0 +1,263 @@
+/*global _ccsg */
+
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ http://www.cocos.com
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+ The software or tools in this License Agreement are licensed, not sold.
+ Chukong Aipu reserves all rights not expressly granted to you.
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+var WebViewImpl = require('./webview-impl');
+
+/**
+ * !#en WebView event type
+ * !#zh 网页视图事件类型
+ * @enum WebView.EventType
+ */
+var EventType = WebViewImpl.EventType;
+
+
+/**
+ * !#en Web page Load completed.
+ * !#zh 网页加载完成
+ * @property {String} LOADED
+ */
+
+/**
+ * !#en Web page is loading.
+ * !#zh 网页加载中
+ * @property {String} LOADING
+ */
+
+/**
+ * !#en Web page error occurs when loading.
+ * !#zh 网页加载出错
+ * @property {String} ERROR
+ */
+
+//
+function emptyCallback () { }
+
+/**
+ * !#en cc.WebView is a component for display web pages in the game
+ * !#zh WebView 组件,用于在游戏中显示网页
+ * @class WebView
+ * @extends Component
+ */
+var WebView = cc.Class({
+ name: 'cc.WebView',
+ extends: cc.Component,
+
+ editor: CC_EDITOR && {
+ menu: 'i18n:MAIN_MENU.component.ui/WebView'
+ },
+
+ properties: {
+ _useOriginalSize: true,
+
+ _url: '',
+ /**
+ * !#en A given URL to be loaded by the WebView, it should have a http or https prefix.
+ * !#zh 指定 WebView 加载的网址,它应该是一个 http 或者 https 开头的字符串
+ * @property {String} url
+ */
+ url: {
+ type: String,
+ tooltip: CC_DEV && 'i18n:COMPONENT.webview.url',
+ get: function () {
+ return this._url;
+ },
+ set: function (url) {
+ this._url = url;
+ var impl = this._impl;
+ if (impl) {
+ impl.loadURL(url);
+ }
+ }
+ },
+
+ /**
+ * !#en The webview's event callback , it will be triggered when certain webview event occurs.
+ * !#zh WebView 的回调事件,当网页加载过程中,加载完成后或者加载出错时都会回调此函数
+ * @property {Component.EventHandler[]} webviewLoadedEvents
+ */
+ webviewEvents: {
+ default: [],
+ type: cc.Component.EventHandler,
+ },
+ },
+
+ statics: {
+ EventType: EventType,
+ },
+
+ ctor () {
+ this._impl = new WebViewImpl();
+ },
+
+ onEnable () {
+ if (!CC_EDITOR) {
+ var impl = this._impl;
+ this._impl.createDomElementIfNeeded(this.node.width, this.node.height);
+ this._impl.loadURL(this._url);
+ this._impl.setVisible(true);
+ impl.setEventListener(EventType.LOADED, this._onWebViewLoaded.bind(this));
+ impl.setEventListener(EventType.LOADING, this._onWebViewLoading.bind(this));
+ impl.setEventListener(EventType.ERROR, this._onWebViewLoadError.bind(this));
+ }
+ },
+
+ onDisable () {
+ if (!CC_EDITOR) {
+ var impl = this._impl;
+ this._impl.setVisible(false);
+ impl.setEventListener(EventType.LOADED, emptyCallback);
+ impl.setEventListener(EventType.LOADING, emptyCallback);
+ impl.setEventListener(EventType.ERROR, emptyCallback);
+ }
+ },
+
+ onDestroy () {
+ if (this._impl) {
+ this._impl.destroy();
+ this._impl = null;
+ }
+ },
+
+ update (dt) {
+ if (this._impl) {
+ this._impl.updateMatrix(this.node);
+ }
+ },
+
+ _onWebViewLoaded () {
+ cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADED);
+ this.node.emit('loaded', this);
+ },
+
+ _onWebViewLoading () {
+ cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADING);
+ this.node.emit('loading', this);
+ return true;
+ },
+
+ _onWebViewLoadError () {
+ cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.ERROR);
+ this.node.emit('error', this);
+ },
+
+ /**
+ * !#en
+ * Set javascript interface scheme (see also setOnJSCallback).
+ * Note: Supports only on the Android and iOS. For HTML5, please refer to the official documentation.
+ * Please refer to the official documentation for more details.
+ * !#zh
+ * 设置 JavaScript 接口方案(与 'setOnJSCallback' 配套使用)。
+ * 注意:只支持 Android 和 iOS ,Web 端用法请前往官方文档查看。
+ * 详情请参阅官方文档
+ * @method setJavascriptInterfaceScheme
+ * @param {String} scheme
+ */
+ setJavascriptInterfaceScheme (scheme) {
+ if (this._impl) {
+ this._impl.setJavascriptInterfaceScheme(scheme);
+ }
+ },
+
+ /**
+ * !#en
+ * This callback called when load URL that start with javascript
+ * interface scheme (see also setJavascriptInterfaceScheme).
+ * Note: Supports only on the Android and iOS. For HTML5, please refer to the official documentation.
+ * Please refer to the official documentation for more details.
+ * !#zh
+ * 当加载 URL 以 JavaScript 接口方案开始时调用这个回调函数。
+ * 注意:只支持 Android 和 iOS,Web 端用法请前往官方文档查看。
+ * 详情请参阅官方文档
+ * @method setOnJSCallback
+ * @param {Function} callback
+ */
+ setOnJSCallback (callback) {
+ if (this._impl) {
+ this._impl.setOnJSCallback(callback);
+ }
+ },
+
+ /**
+ * !#en
+ * Evaluates JavaScript in the context of the currently displayed page.
+ * Please refer to the official document for more details
+ * Note: Cross domain issues need to be resolved by yourself
+ * !#zh
+ * 执行 WebView 内部页面脚本(详情请参阅官方文档)
+ * 注意:需要自行解决跨域问题
+ * @method evaluateJS
+ * @param {String} str
+ */
+ evaluateJS (str) {
+ if (this._impl) {
+ this._impl.evaluateJS(str);
+ }
+ },
+
+});
+
+cc.WebView = module.exports = WebView;
+/**
+ * !#en
+ * Note: This event is emitted from the node to which the component belongs.
+ * !#zh
+ * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
+ * @event loaded
+ * @param {Event.EventCustom} event
+ * @param {WebView} event.detail - The WebView component.
+ */
+
+/**
+ * !#en
+ * Note: This event is emitted from the node to which the component belongs.
+ * !#zh
+ * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
+ * @event loading
+ * @param {Event.EventCustom} event
+ * @param {WebView} event.detail - The WebView component.
+ */
+
+/**
+ * !#en
+ * Note: This event is emitted from the node to which the component belongs.
+ * !#zh
+ * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
+ * @event error
+ * @param {Event.EventCustom} event
+ * @param {WebView} event.detail - The WebView component.
+ */
+
+/**
+ * !#en if you don't need the WebView and it isn't in any running Scene, you should
+ * call the destroy method on this component or the associated node explicitly.
+ * Otherwise, the created DOM element won't be removed from web page.
+ * !#zh
+ * 如果你不再使用 WebView,并且组件未添加到场景中,那么你必须手动对组件或所在节点调用 destroy。
+ * 这样才能移除网页上的 DOM 节点,避免 Web 平台内存泄露。
+ * @example
+ * webview.node.parent = null; // or webview.node.removeFromParent(false);
+ * // when you don't need webview anymore
+ * webview.node.destroy();
+ * @method destroy
+ * @return {Boolean} whether it is the first time the destroy being called
+ */
diff --git a/cocos2d/core/webview/webview-impl.js b/cocos2d/webview/webview-impl.js
similarity index 98%
rename from cocos2d/core/webview/webview-impl.js
rename to cocos2d/webview/webview-impl.js
index dcb0de0442..037ce84b99 100644
--- a/cocos2d/core/webview/webview-impl.js
+++ b/cocos2d/webview/webview-impl.js
@@ -18,9 +18,10 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
-var Utils = require('../platform/utils');
-var eventManager = require('../event-manager');
-var sys = require('../platform/CCSys');
+
+var Utils = require('../core/platform/');
+var eventManager = require('../core/event-manager');
+var sys = require('../core/platform/CCSys');
var WebViewImpl = cc.Class({
name: "WebViewImpl",
diff --git a/extends.js b/extends.js
index 4092d1b65c..ff0b554e5f 100644
--- a/extends.js
+++ b/extends.js
@@ -31,14 +31,15 @@ if (CC_EDITOR && Editor.isMainProcess) {
require('./cocos2d/tilemap/CCTiledMapAsset');
}
else {
- require('./cocos2d/particle/CCParticleSystem');
- require('./cocos2d/tilemap/CCTiledMap');
- require('./cocos2d/motion-streak/CCMotionStreak');
+ require('./cocos2d/particle');
+ require('./cocos2d/tilemap');
+ require('./cocos2d/videoplayer/CCVideoPlayer');
+ require('./cocos2d/webview/CCWebView');
+ require('./cocos2d/motion-streak');
require('./cocos2d/core/components/CCStudioComponent');
require('./extensions/ccpool/CCNodePool');
if (!CC_JSB) {
require('./cocos2d/actions');
- require('./external/chipmunk/chipmunk');
}
}
diff --git a/extensions/dragonbones/dragonblones-assembler.js b/extensions/dragonbones/dragonbones-assembler.js
similarity index 100%
rename from extensions/dragonbones/dragonblones-assembler.js
rename to extensions/dragonbones/dragonbones-assembler.js
diff --git a/extensions/dragonbones/index.js b/extensions/dragonbones/index.js
index f724dbb647..9f791170a3 100644
--- a/extensions/dragonbones/index.js
+++ b/extensions/dragonbones/index.js
@@ -134,9 +134,7 @@ if (!CC_EDITOR || !Editor.isMainProcess) {
require('./DragonBonesAtlasAsset');
require('./ArmatureDisplay')
- if (!CC_JSB) {
- require('./dragonblones-assembler');
- }
+ require('./dragonbones-assembler');
} else {
require('./DragonBonesAsset');
require('./DragonBonesAtlasAsset');
diff --git a/extensions/spine/index.js b/extensions/spine/index.js
index cc36ec5213..fd163998d3 100644
--- a/extensions/spine/index.js
+++ b/extensions/spine/index.js
@@ -105,7 +105,7 @@ if (!CC_EDITOR || !Editor.isMainProcess) {
require('./skeleton-texture');
require('./skeleton-data');
require('./skeleton');
- require('../../cocos2d/core/renderer/assemblers/spine-assembler');
+ require('./spine-assembler');
}
else {
require('./skeleton-data');
diff --git a/cocos2d/core/renderer/assemblers/spine-assembler.js b/extensions/spine/spine-assembler.js
similarity index 97%
rename from cocos2d/core/renderer/assemblers/spine-assembler.js
rename to extensions/spine/spine-assembler.js
index 3be861b815..834176c6ac 100644
--- a/cocos2d/core/renderer/assemblers/spine-assembler.js
+++ b/extensions/spine/spine-assembler.js
@@ -23,12 +23,12 @@
THE SOFTWARE.
****************************************************************************/
-const js = require('../../platform/js');
-const assembler = require('./assembler');
-const Skeleton = require('../../../../extensions/spine/skeleton');
-const spine = require('../../../../extensions/spine/lib/spine');
-const renderer = require('../');
-const renderEngine = require('../render-engine');
+const js = require('../../cocos2d/core/platform/js');
+const assembler = require('../../cocos2d/core/renderer/assemblers/assembler');
+const Skeleton = require('./skeleton');
+const spine = require('./lib/spine');
+const renderer = require('../../cocos2d/core/renderer');
+const renderEngine = renderer.renderEngine;
const gfx = renderEngine.gfx;
const SpriteMaterial = renderEngine.SpriteMaterial;
diff --git a/external/chipmunk/chipmunk.js b/external/chipmunk/chipmunk.js
deleted file mode 100644
index 0da684077d..0000000000
--- a/external/chipmunk/chipmunk.js
+++ /dev/null
@@ -1,6182 +0,0 @@
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-Object.create = Object.create || function(o) {
- function F() {}
- F.prototype = o;
- return new F();
-};
-
-//var VERSION = CP_VERSION_MAJOR + "." + CP_VERSION_MINOR + "." + CP_VERSION_RELEASE;
-
-var assert = function(value, message)
-{
- if (!value) {
- throw new Error('Assertion failed: ' + message);
- }
-};
-
-var assertSoft = function(value, message)
-{
- if(!value && console && console.warn) {
- console.warn("ASSERTION FAILED: " + message);
- if(console.trace) {
- console.trace();
- }
- }
-};
-
-var mymin = function(a, b)
-{
- return a < b ? a : b;
-};
-var mymax = function(a, b)
-{
- return a > b ? a : b;
-};
-
-var min, max;
-if (typeof window === 'object' && window.navigator.userAgent.indexOf('Firefox') > -1){
- // On firefox, Math.min and Math.max are really fast:
- // http://jsperf.com/math-vs-greater-than/8
- min = Math.min;
- max = Math.max;
-} else {
- // On chrome and safari, Math.min / max are slooow. The ternery operator above is faster
- // than the builtins because we only have to deal with 2 arguments that are always numbers.
- min = mymin;
- max = mymax;
-}
-
-/* The hashpair function takes two numbers and returns a hash code for them.
- * Required that hashPair(a, b) === hashPair(b, a).
- * Chipmunk's hashPair function is defined as:
- * #define CP_HASH_COEF (3344921057ul)
- * #define CP_HASH_PAIR(A, B) ((cpHashValue)(A)*CP_HASH_COEF ^ (cpHashValue)(B)*CP_HASH_COEF)
- * But thats not suitable in javascript because multiplying by a large number will make the number
- * a large float.
- *
- * The result of hashPair is used as the key in objects, so it returns a string.
- */
-var hashPair = function(a, b)
-{
- //assert(typeof(a) === 'number', "HashPair used on something not a number");
- return a < b ? a + ' ' + b : b + ' ' + a;
-};
-
-var deleteObjFromList = function(arr, obj)
-{
- for(var i=0; i> 1;
- for(var i=1; i maxx || (x == maxx && y > maxy)){
- maxx = x;
- maxy = y;
- end = i;
- }
- }
- return [start, end];
-};
-
-var SWAP = function(arr, idx1, idx2)
-{
- var tmp = arr[idx1*2];
- arr[idx1*2] = arr[idx2*2];
- arr[idx2*2] = tmp;
-
- tmp = arr[idx1*2+1];
- arr[idx1*2+1] = arr[idx2*2+1];
- arr[idx2*2+1] = tmp;
-};
-
-var QHullPartition = function(verts, offs, count, a, b, tol)
-{
- if(count === 0) return 0;
-
- var max = 0;
- var pivot = offs;
-
- var delta = vsub(b, a);
- var valueTol = tol * vlength(delta);
-
- var head = offs;
- for(var tail = offs+count-1; head <= tail;){
- var v = new Vect(verts[head * 2], verts[head * 2 + 1]);
- var value = vcross(delta, vsub(v, a));
- if(value > valueTol){
- if(value > max){
- max = value;
- pivot = head;
- }
-
- head++;
- } else {
- SWAP(verts, head, tail);
- tail--;
- }
- }
-
- // move the new pivot to the front if it's not already there.
- if(pivot != offs) SWAP(verts, offs, pivot);
- return head - offs;
-};
-
-var QHullReduce = function(tol, verts, offs, count, a, pivot, b, resultPos)
-{
- if(count < 0){
- return 0;
- } else if(count == 0) {
- verts[resultPos*2] = pivot.x;
- verts[resultPos*2+1] = pivot.y;
- return 1;
- } else {
- var left_count = QHullPartition(verts, offs, count, a, pivot, tol);
- var left = new Vect(verts[offs*2], verts[offs*2+1]);
- var index = QHullReduce(tol, verts, offs + 1, left_count - 1, a, left, pivot, resultPos);
-
- var pivotPos = resultPos + index++;
- verts[pivotPos*2] = pivot.x;
- verts[pivotPos*2+1] = pivot.y;
-
- var right_count = QHullPartition(verts, offs + left_count, count - left_count, pivot, b, tol);
- var right = new Vect(verts[(offs+left_count)*2], verts[(offs+left_count)*2+1]);
- return index + QHullReduce(tol, verts, offs + left_count + 1, right_count - 1, pivot, right, b, resultPos + index);
- }
-};
-
-// QuickHull seemed like a neat algorithm, and efficient-ish for large input sets.
-// My implementation performs an in place reduction using the result array as scratch space.
-//
-// Pass an Array into result to put the result of the calculation there. Otherwise, pass null
-// and the verts list will be edited in-place.
-//
-// Expects the verts to be described in the same way as cpPolyShape - which is to say, it should
-// be a list of [x1,y1,x2,y2,x3,y3,...].
-//
-// tolerance is in world coordinates. Eg, 2.
-cp.convexHull = function(verts, result, tolerance)
-{
- if(result){
- // Copy the line vertexes into the empty part of the result polyline to use as a scratch buffer.
- for (var i = 0; i < verts.length; i++){
- result[i] = verts[i];
- }
- } else {
- // If a result array was not specified, reduce the input instead.
- result = verts;
- }
-
- // Degenerate case, all points are the same.
- var indexes = loopIndexes(verts);
- var start = indexes[0], end = indexes[1];
- if(start == end){
- //if(first) (*first) = 0;
- result.length = 2;
- return result;
- }
-
- SWAP(result, 0, start);
- SWAP(result, 1, end == 0 ? start : end);
-
- var a = new Vect(result[0], result[1]);
- var b = new Vect(result[2], result[3]);
-
- var count = verts.length >> 1;
- //if(first) (*first) = start;
- var resultCount = QHullReduce(tolerance, result, 2, count - 2, a, b, a, 1) + 1;
- result.length = resultCount*2;
-
- assertSoft(polyValidate(result),
- "Internal error: cpConvexHull() and cpPolyValidate() did not agree." +
- "Please report this error with as much info as you can.");
- return result;
-};
-
-/// Clamp @c f to be between @c min and @c max.
-var clamp = function(f, minv, maxv)
-{
- return min(max(f, minv), maxv);
-};
-
-/// Clamp @c f to be between 0 and 1.
-var clamp01 = function(f)
-{
- return max(0, min(f, 1));
-};
-
-/// Linearly interpolate (or extrapolate) between @c f1 and @c f2 by @c t percent.
-var lerp = function(f1, f2, t)
-{
- return f1*(1 - t) + f2*t;
-};
-
-/// Linearly interpolate from @c f1 to @c f2 by no more than @c d.
-var lerpconst = function(f1, f2, d)
-{
- return f1 + clamp(f2 - f1, -d, d);
-};
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-// I'm using an array tuple here because (at time of writing) its about 3x faster
-// than an object on firefox, and the same speed on chrome.
-
-//var numVects = 0;
-
-var Vect = cp.Vect = function(x, y)
-{
- this.x = x;
- this.y = y;
- //numVects++;
-
-// var s = new Error().stack;
-// traces[s] = traces[s] ? traces[s]+1 : 1;
-};
-
-cp.v = function (x,y) { return new Vect(x, y) };
-
-var vzero = cp.vzero = new Vect(0,0);
-
-// The functions below *could* be rewritten to be instance methods on Vect. I don't
-// know how that would effect performance. For now, I'm keeping the JS similar to
-// the original C code.
-
-/// Vector dot product.
-var vdot = cp.v.dot = function(v1, v2)
-{
- return v1.x*v2.x + v1.y*v2.y;
-};
-
-var vdot2 = function(x1, y1, x2, y2)
-{
- return x1*x2 + y1*y2;
-};
-
-/// Returns the length of v.
-var vlength = cp.v.len = function(v)
-{
- return Math.sqrt(vdot(v, v));
-};
-
-var vlength2 = cp.v.len2 = function(x, y)
-{
- return Math.sqrt(x*x + y*y);
-};
-
-/// Check if two vectors are equal. (Be careful when comparing floating point numbers!)
-var veql = cp.v.eql = function(v1, v2)
-{
- return (v1.x === v2.x && v1.y === v2.y);
-};
-
-/// Add two vectors
-var vadd = cp.v.add = function(v1, v2)
-{
- return new Vect(v1.x + v2.x, v1.y + v2.y);
-};
-
-Vect.prototype.add = function(v2)
-{
- this.x += v2.x;
- this.y += v2.y;
- return this;
-};
-
-/// Subtract two vectors.
-var vsub = cp.v.sub = function(v1, v2)
-{
- return new Vect(v1.x - v2.x, v1.y - v2.y);
-};
-
-Vect.prototype.sub = function(v2)
-{
- this.x -= v2.x;
- this.y -= v2.y;
- return this;
-};
-
-/// Negate a vector.
-var vneg = cp.v.neg = function(v)
-{
- return new Vect(-v.x, -v.y);
-};
-
-Vect.prototype.neg = function()
-{
- this.x = -this.x;
- this.y = -this.y;
- return this;
-};
-
-/// Scalar multiplication.
-var vmult = cp.v.mult = function(v, s)
-{
- return new Vect(v.x*s, v.y*s);
-};
-
-Vect.prototype.mult = function(s)
-{
- this.x *= s;
- this.y *= s;
- return this;
-};
-
-/// 2D vector cross product analog.
-/// The cross product of 2D vectors results in a 3D vector with only a z component.
-/// This function returns the magnitude of the z value.
-var vcross = cp.v.cross = function(v1, v2)
-{
- return v1.x*v2.y - v1.y*v2.x;
-};
-
-var vcross2 = function(x1, y1, x2, y2)
-{
- return x1*y2 - y1*x2;
-};
-
-/// Returns a perpendicular vector. (90 degree rotation)
-var vperp = cp.v.perp = function(v)
-{
- return new Vect(-v.y, v.x);
-};
-
-/// Returns a perpendicular vector. (-90 degree rotation)
-var vpvrperp = cp.v.pvrperp = function(v)
-{
- return new Vect(v.y, -v.x);
-};
-
-/// Returns the vector projection of v1 onto v2.
-var vproject = cp.v.project = function(v1, v2)
-{
- return vmult(v2, vdot(v1, v2)/vlengthsq(v2));
-};
-
-Vect.prototype.project = function(v2)
-{
- this.mult(vdot(this, v2) / vlengthsq(v2));
- return this;
-};
-
-/// Uses complex number multiplication to rotate v1 by v2. Scaling will occur if v1 is not a unit vector.
-var vrotate = cp.v.rotate = function(v1, v2)
-{
- return new Vect(v1.x*v2.x - v1.y*v2.y, v1.x*v2.y + v1.y*v2.x);
-};
-
-Vect.prototype.rotate = function(v2)
-{
- this.x = this.x * v2.x - this.y * v2.y;
- this.y = this.x * v2.y + this.y * v2.x;
- return this;
-};
-
-/// Inverse of vrotate().
-var vunrotate = cp.v.unrotate = function(v1, v2)
-{
- return new Vect(v1.x*v2.x + v1.y*v2.y, v1.y*v2.x - v1.x*v2.y);
-};
-
-/// Returns the squared length of v. Faster than vlength() when you only need to compare lengths.
-var vlengthsq = cp.v.lengthsq = function(v)
-{
- return vdot(v, v);
-};
-
-var vlengthsq2 = cp.v.lengthsq2 = function(x, y)
-{
- return x*x + y*y;
-};
-
-/// Linearly interpolate between v1 and v2.
-var vlerp = cp.v.lerp = function(v1, v2, t)
-{
- return vadd(vmult(v1, 1 - t), vmult(v2, t));
-};
-
-/// Returns a normalized copy of v.
-var vnormalize = cp.v.normalize = function(v)
-{
- return vmult(v, 1/vlength(v));
-};
-
-/// Returns a normalized copy of v or vzero if v was already vzero. Protects against divide by zero errors.
-var vnormalize_safe = cp.v.normalize_safe = function(v)
-{
- return (v.x === 0 && v.y === 0 ? vzero : vnormalize(v));
-};
-
-/// Clamp v to length len.
-var vclamp = cp.v.clamp = function(v, len)
-{
- return (vdot(v,v) > len*len) ? vmult(vnormalize(v), len) : v;
-};
-
-/// Linearly interpolate between v1 towards v2 by distance d.
-var vlerpconst = cp.v.lerpconst = function(v1, v2, d)
-{
- return vadd(v1, vclamp(vsub(v2, v1), d));
-};
-
-/// Returns the distance between v1 and v2.
-var vdist = cp.v.dist = function(v1, v2)
-{
- return vlength(vsub(v1, v2));
-};
-
-/// Returns the squared distance between v1 and v2. Faster than vdist() when you only need to compare distances.
-var vdistsq = cp.v.distsq = function(v1, v2)
-{
- return vlengthsq(vsub(v1, v2));
-};
-
-/// Returns true if the distance between v1 and v2 is less than dist.
-var vnear = cp.v.near = function(v1, v2, dist)
-{
- return vdistsq(v1, v2) < dist*dist;
-};
-
-/// Spherical linearly interpolate between v1 and v2.
-var vslerp = cp.v.slerp = function(v1, v2, t)
-{
- var omega = Math.acos(vdot(v1, v2));
-
- if(omega) {
- var denom = 1/Math.sin(omega);
- return vadd(vmult(v1, Math.sin((1 - t)*omega)*denom), vmult(v2, Math.sin(t*omega)*denom));
- } else {
- return v1;
- }
-};
-
-/// Spherical linearly interpolate between v1 towards v2 by no more than angle a radians
-var vslerpconst = cp.v.slerpconst = function(v1, v2, a)
-{
- var angle = Math.acos(vdot(v1, v2));
- return vslerp(v1, v2, min(a, angle)/angle);
-};
-
-/// Returns the unit length vector for the given angle (in radians).
-var vforangle = cp.v.forangle = function(a)
-{
- return new Vect(Math.cos(a), Math.sin(a));
-};
-
-/// Returns the angular direction v is pointing in (in radians).
-var vtoangle = cp.v.toangle = function(v)
-{
- return Math.atan2(v.y, v.x);
-};
-
-/// Returns a string representation of v. Intended mostly for debugging purposes and not production use.
-var vstr = cp.v.str = function(v)
-{
- return "(" + v.x.toFixed(3) + ", " + v.y.toFixed(3) + ")";
-};
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-/// Chipmunk's axis-aligned 2D bounding box type along with a few handy routines.
-
-var numBB = 0;
-
-// Bounding boxes are JS objects with {l, b, r, t} = left, bottom, right, top, respectively.
-var BB = cp.BB = function(l, b, r, t)
-{
- this.l = l;
- this.b = b;
- this.r = r;
- this.t = t;
-
- numBB++;
-};
-
-cp.bb = function(l, b, r, t) { return new BB(l, b, r, t); };
-
-var bbNewForCircle = function(p, r)
-{
- return new BB(
- p.x - r,
- p.y - r,
- p.x + r,
- p.y + r
- );
-};
-
-/// Returns true if @c a and @c b intersect.
-var bbIntersects = function(a, b)
-{
- return (a.l <= b.r && b.l <= a.r && a.b <= b.t && b.b <= a.t);
-};
-var bbIntersects2 = function(bb, l, b, r, t)
-{
- return (bb.l <= r && l <= bb.r && bb.b <= t && b <= bb.t);
-};
-
-/// Returns true if @c other lies completely within @c bb.
-var bbContainsBB = function(bb, other)
-{
- return (bb.l <= other.l && bb.r >= other.r && bb.b <= other.b && bb.t >= other.t);
-};
-
-/// Returns true if @c bb contains @c v.
-var bbContainsVect = function(bb, v)
-{
- return (bb.l <= v.x && bb.r >= v.x && bb.b <= v.y && bb.t >= v.y);
-};
-var bbContainsVect2 = function(l, b, r, t, v)
-{
- return (l <= v.x && r >= v.x && b <= v.y && t >= v.y);
-};
-
-/// Returns a bounding box that holds both bounding boxes.
-var bbMerge = function(a, b){
- return new BB(
- min(a.l, b.l),
- min(a.b, b.b),
- max(a.r, b.r),
- max(a.t, b.t)
- );
-};
-
-/// Returns a bounding box that holds both @c bb and @c v.
-var bbExpand = function(bb, v){
- return new BB(
- min(bb.l, v.x),
- min(bb.b, v.y),
- max(bb.r, v.x),
- max(bb.t, v.y)
- );
-};
-
-/// Returns the area of the bounding box.
-var bbArea = function(bb)
-{
- return (bb.r - bb.l)*(bb.t - bb.b);
-};
-
-/// Merges @c a and @c b and returns the area of the merged bounding box.
-var bbMergedArea = function(a, b)
-{
- return (max(a.r, b.r) - min(a.l, b.l))*(max(a.t, b.t) - min(a.b, b.b));
-};
-
-var bbMergedArea2 = function(bb, l, b, r, t)
-{
- return (max(bb.r, r) - min(bb.l, l))*(max(bb.t, t) - min(bb.b, b));
-};
-
-/// Return true if the bounding box intersects the line segment with ends @c a and @c b.
-var bbIntersectsSegment = function(bb, a, b)
-{
- return (bbSegmentQuery(bb, a, b) != Infinity);
-};
-
-/// Clamp a vector to a bounding box.
-var bbClampVect = function(bb, v)
-{
- var x = min(max(bb.l, v.x), bb.r);
- var y = min(max(bb.b, v.y), bb.t);
- return new Vect(x, y);
-};
-
-// TODO edge case issue
-/// Wrap a vector to a bounding box.
-var bbWrapVect = function(bb, v)
-{
- var ix = Math.abs(bb.r - bb.l);
- var modx = (v.x - bb.l) % ix;
- var x = (modx > 0) ? modx : modx + ix;
-
- var iy = Math.abs(bb.t - bb.b);
- var mody = (v.y - bb.b) % iy;
- var y = (mody > 0) ? mody : mody + iy;
-
- return new Vect(x + bb.l, y + bb.b);
-};
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-/// Segment query info struct.
-/* These are created using literals where needed.
-typedef struct cpSegmentQueryInfo {
- /// The shape that was hit, null if no collision occured.
- cpShape *shape;
- /// The normalized distance along the query segment in the range [0, 1].
- cpFloat t;
- /// The normal of the surface hit.
- cpVect n;
-} cpSegmentQueryInfo;
-*/
-
-var shapeIDCounter = 0;
-
-var CP_NO_GROUP = cp.NO_GROUP = 0;
-var CP_ALL_LAYERS = cp.ALL_LAYERS = ~0;
-
-cp.resetShapeIdCounter = function()
-{
- shapeIDCounter = 0;
-};
-
-/// The cpShape struct defines the shape of a rigid body.
-//
-/// Opaque collision shape struct. Do not create directly - instead use
-/// PolyShape, CircleShape and SegmentShape.
-var Shape = cp.Shape = function(body) {
- /// The rigid body this collision shape is attached to.
- this.body = body;
-
- /// The current bounding box of the shape.
- this.bb_l = this.bb_b = this.bb_r = this.bb_t = 0;
-
- this.hashid = shapeIDCounter++;
-
- /// Sensor flag.
- /// Sensor shapes call collision callbacks but don't produce collisions.
- this.sensor = false;
-
- /// Coefficient of restitution. (elasticity)
- this.e = 0;
- /// Coefficient of friction.
- this.u = 0;
- /// Surface velocity used when solving for friction.
- this.surface_v = vzero;
-
- /// Collision type of this shape used when picking collision handlers.
- this.collision_type = 0;
- /// Group of this shape. Shapes in the same group don't collide.
- this.group = 0;
- // Layer bitmask for this shape. Shapes only collide if the bitwise and of their layers is non-zero.
- this.layers = CP_ALL_LAYERS;
-
- this.space = null;
-
- // Copy the collision code from the prototype into the actual object. This makes collision
- // function lookups slightly faster.
- this.collisionCode = this.collisionCode;
-};
-
-Shape.prototype.setElasticity = function(e) { this.e = e; };
-Shape.prototype.setFriction = function(u) { this.body.activate(); this.u = u; };
-Shape.prototype.setLayers = function(layers) { this.body.activate(); this.layers = layers; };
-Shape.prototype.setSensor = function(sensor) { this.body.activate(); this.sensor = sensor; };
-Shape.prototype.setCollisionType = function(collision_type) { this.body.activate(); this.collision_type = collision_type; };
-Shape.prototype.getBody = function() { return this.body; };
-
-Shape.prototype.active = function()
-{
-// return shape->prev || (shape->body && shape->body->shapeList == shape);
- return this.body && this.body.shapeList.indexOf(this) !== -1;
-};
-
-Shape.prototype.setBody = function(body)
-{
- assert(!this.active(), "You cannot change the body on an active shape. You must remove the shape from the space before changing the body.");
- this.body = body;
-};
-
-Shape.prototype.cacheBB = function()
-{
- return this.update(this.body.p, this.body.rot);
-};
-
-Shape.prototype.update = function(pos, rot)
-{
- assert(!isNaN(rot.x), 'Rotation is NaN');
- assert(!isNaN(pos.x), 'Position is NaN');
- this.cacheData(pos, rot);
-};
-
-Shape.prototype.pointQuery = function(p)
-{
- var info = this.nearestPointQuery(p);
- if (info.d < 0) return info;
-};
-
-Shape.prototype.getBB = function()
-{
- return new BB(this.bb_l, this.bb_b, this.bb_r, this.bb_t);
-};
-
-/* Not implemented - all these getters and setters. Just edit the object directly.
-CP_DefineShapeStructGetter(cpBody*, body, Body);
-void cpShapeSetBody(cpShape *shape, cpBody *body);
-
-CP_DefineShapeStructGetter(cpBB, bb, BB);
-CP_DefineShapeStructProperty(cpBool, sensor, Sensor, cpTrue);
-CP_DefineShapeStructProperty(cpFloat, e, Elasticity, cpFalse);
-CP_DefineShapeStructProperty(cpFloat, u, Friction, cpTrue);
-CP_DefineShapeStructProperty(cpVect, surface_v, SurfaceVelocity, cpTrue);
-CP_DefineShapeStructProperty(cpDataPointer, data, UserData, cpFalse);
-CP_DefineShapeStructProperty(cpCollisionType, collision_type, CollisionType, cpTrue);
-CP_DefineShapeStructProperty(cpGroup, group, Group, cpTrue);
-CP_DefineShapeStructProperty(cpLayers, layers, Layers, cpTrue);
-*/
-
-/// Extended point query info struct. Returned from calling pointQuery on a shape.
-var PointQueryExtendedInfo = function(shape)
-{
- /// Shape that was hit, NULL if no collision occurred.
- this.shape = shape;
- /// Depth of the point inside the shape.
- this.d = Infinity;
- /// Direction of minimum norm to the shape's surface.
- this.n = vzero;
-};
-
-var NearestPointQueryInfo = function(shape, p, d)
-{
- /// The nearest shape, NULL if no shape was within range.
- this.shape = shape;
- /// The closest point on the shape's surface. (in world space coordinates)
- this.p = p;
- /// The distance to the point. The distance is negative if the point is inside the shape.
- this.d = d;
-};
-
-var SegmentQueryInfo = function(shape, t, n)
-{
- /// The shape that was hit, NULL if no collision occured.
- this.shape = shape;
- /// The normalized distance along the query segment in the range [0, 1].
- this.t = t;
- /// The normal of the surface hit.
- this.n = n;
-};
-
-/// Get the hit point for a segment query.
-SegmentQueryInfo.prototype.hitPoint = function(start, end)
-{
- return vlerp(start, end, this.t);
-};
-
-/// Get the hit distance for a segment query.
-SegmentQueryInfo.prototype.hitDist = function(start, end)
-{
- return vdist(start, end) * this.t;
-};
-
-// Circles.
-
-var CircleShape = cp.CircleShape = function(body, radius, offset)
-{
- this.c = this.tc = offset;
- this.r = radius;
-
- this.type = 'circle';
-
- Shape.call(this, body);
-};
-
-CircleShape.prototype = Object.create(Shape.prototype);
-
-CircleShape.prototype.cacheData = function(p, rot)
-{
- //var c = this.tc = vadd(p, vrotate(this.c, rot));
- var c = this.tc = vrotate(this.c, rot).add(p);
- //this.bb = bbNewForCircle(c, this.r);
- var r = this.r;
- this.bb_l = c.x - r;
- this.bb_b = c.y - r;
- this.bb_r = c.x + r;
- this.bb_t = c.y + r;
-};
-
-/// Test if a point lies within a shape.
-/*CircleShape.prototype.pointQuery = function(p)
-{
- var delta = vsub(p, this.tc);
- var distsq = vlengthsq(delta);
- var r = this.r;
-
- if(distsq < r*r){
- var info = new PointQueryExtendedInfo(this);
-
- var dist = Math.sqrt(distsq);
- info.d = r - dist;
- info.n = vmult(delta, 1/dist);
- return info;
- }
-};*/
-
-CircleShape.prototype.nearestPointQuery = function(p)
-{
- var deltax = p.x - this.tc.x;
- var deltay = p.y - this.tc.y;
- var d = vlength2(deltax, deltay);
- var r = this.r;
-
- var nearestp = new Vect(this.tc.x + deltax * r/d, this.tc.y + deltay * r/d);
- return new NearestPointQueryInfo(this, nearestp, d - r);
-};
-
-var circleSegmentQuery = function(shape, center, r, a, b, info)
-{
- // offset the line to be relative to the circle
- a = vsub(a, center);
- b = vsub(b, center);
-
- var qa = vdot(a, a) - 2*vdot(a, b) + vdot(b, b);
- var qb = -2*vdot(a, a) + 2*vdot(a, b);
- var qc = vdot(a, a) - r*r;
-
- var det = qb*qb - 4*qa*qc;
-
- if(det >= 0)
- {
- var t = (-qb - Math.sqrt(det))/(2*qa);
- if(0 <= t && t <= 1){
- return new SegmentQueryInfo(shape, t, vnormalize(vlerp(a, b, t)));
- }
- }
-};
-
-CircleShape.prototype.segmentQuery = function(a, b)
-{
- return circleSegmentQuery(this, this.tc, this.r, a, b);
-};
-
-// The C API has these, and also getters. Its not idiomatic to
-// write getters and setters in JS.
-/*
-CircleShape.prototype.setRadius = function(radius)
-{
- this.r = radius;
-}
-
-CircleShape.prototype.setOffset = function(offset)
-{
- this.c = offset;
-}*/
-
-// Segment shape
-
-var SegmentShape = cp.SegmentShape = function(body, a, b, r)
-{
- this.a = a;
- this.b = b;
- this.n = vperp(vnormalize(vsub(b, a)));
-
- this.ta = this.tb = this.tn = null;
-
- this.r = r;
-
- this.a_tangent = vzero;
- this.b_tangent = vzero;
-
- this.type = 'segment';
- Shape.call(this, body);
-};
-
-SegmentShape.prototype = Object.create(Shape.prototype);
-
-SegmentShape.prototype.cacheData = function(p, rot)
-{
- this.ta = vadd(p, vrotate(this.a, rot));
- this.tb = vadd(p, vrotate(this.b, rot));
- this.tn = vrotate(this.n, rot);
-
- var l,r,b,t;
-
- if(this.ta.x < this.tb.x){
- l = this.ta.x;
- r = this.tb.x;
- } else {
- l = this.tb.x;
- r = this.ta.x;
- }
-
- if(this.ta.y < this.tb.y){
- b = this.ta.y;
- t = this.tb.y;
- } else {
- b = this.tb.y;
- t = this.ta.y;
- }
-
- var rad = this.r;
-
- this.bb_l = l - rad;
- this.bb_b = b - rad;
- this.bb_r = r + rad;
- this.bb_t = t + rad;
-};
-
-SegmentShape.prototype.nearestPointQuery = function(p)
-{
- var closest = closestPointOnSegment(p, this.ta, this.tb);
-
- var deltax = p.x - closest.x;
- var deltay = p.y - closest.y;
- var d = vlength2(deltax, deltay);
- var r = this.r;
-
- var nearestp = (d ? vadd(closest, vmult(new Vect(deltax, deltay), r/d)) : closest);
- return new NearestPointQueryInfo(this, nearestp, d - r);
-};
-
-SegmentShape.prototype.segmentQuery = function(a, b)
-{
- var n = this.tn;
- var d = vdot(vsub(this.ta, a), n);
- var r = this.r;
-
- var flipped_n = (d > 0 ? vneg(n) : n);
- var n_offset = vsub(vmult(flipped_n, r), a);
-
- var seg_a = vadd(this.ta, n_offset);
- var seg_b = vadd(this.tb, n_offset);
- var delta = vsub(b, a);
-
- if(vcross(delta, seg_a)*vcross(delta, seg_b) <= 0){
- var d_offset = d + (d > 0 ? -r : r);
- var ad = -d_offset;
- var bd = vdot(delta, n) - d_offset;
-
- if(ad*bd < 0){
- return new SegmentQueryInfo(this, ad/(ad - bd), flipped_n);
- }
- } else if(r !== 0){
- var info1 = circleSegmentQuery(this, this.ta, this.r, a, b);
- var info2 = circleSegmentQuery(this, this.tb, this.r, a, b);
-
- if (info1){
- return info2 && info2.t < info1.t ? info2 : info1;
- } else {
- return info2;
- }
- }
-};
-
-SegmentShape.prototype.setNeighbors = function(prev, next)
-{
- this.a_tangent = vsub(prev, this.a);
- this.b_tangent = vsub(next, this.b);
-};
-
-SegmentShape.prototype.setEndpoints = function(a, b)
-{
- this.a = a;
- this.b = b;
- this.n = vperp(vnormalize(vsub(b, a)));
-};
-
-/*
-cpSegmentShapeSetRadius(cpShape *shape, cpFloat radius)
-{
- this.r = radius;
-}*/
-
-/*
-CP_DeclareShapeGetter(cpSegmentShape, cpVect, A);
-CP_DeclareShapeGetter(cpSegmentShape, cpVect, B);
-CP_DeclareShapeGetter(cpSegmentShape, cpVect, Normal);
-CP_DeclareShapeGetter(cpSegmentShape, cpFloat, Radius);
-*/
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-/// Check that a set of vertexes is convex and has a clockwise winding.
-var polyValidate = function(verts)
-{
- var len = verts.length;
- for(var i=0; i 0){
- if(vcross2(bx - ax, by - ay, cx - bx, cy - by) > 0){
- return false;
- }
- }
-
- return true;
-};
-
-/// Initialize a polygon shape.
-/// The vertexes must be convex and have a clockwise winding.
-var PolyShape = cp.PolyShape = function(body, verts, offset)
-{
- this.setVerts(verts, offset);
- this.type = 'poly';
- Shape.call(this, body);
-};
-
-PolyShape.prototype = Object.create(Shape.prototype);
-
-var SplittingPlane = function(n, d)
-{
- this.n = n;
- this.d = d;
-};
-
-SplittingPlane.prototype.compare = function(v)
-{
- return vdot(this.n, v) - this.d;
-};
-
-PolyShape.prototype.setVerts = function(verts, offset)
-{
- assert(verts.length >= 4, "Polygons require some verts");
- assert(typeof(verts[0]) === 'number',
- 'Polygon verticies should be specified in a flattened list (eg [x1,y1,x2,y2,x3,y3,...])');
-
- // Fail if the user attempts to pass a concave poly, or a bad winding.
- assert(polyValidate(verts), "Polygon is concave or has a reversed winding. Consider using cpConvexHull()");
-
- var len = verts.length;
- var numVerts = len >> 1;
-
- // This a pretty bad way to do this in javascript. As a first pass, I want to keep
- // the code similar to the C.
- this.verts = new Array(len);
- this.tVerts = new Array(len);
- this.planes = new Array(numVerts);
- this.tPlanes = new Array(numVerts);
-
- for(var i=0; i>1] = new SplittingPlane(n, vdot2(n.x, n.y, ax, ay));
- this.tPlanes[i>>1] = new SplittingPlane(new Vect(0,0), 0);
- }
-};
-
-/// Initialize a box shaped polygon shape.
-var BoxShape = cp.BoxShape = function(body, width, height)
-{
- var hw = width/2;
- var hh = height/2;
-
- return BoxShape2(body, new BB(-hw, -hh, hw, hh));
-};
-
-/// Initialize an offset box shaped polygon shape.
-var BoxShape2 = cp.BoxShape2 = function(body, box)
-{
- var verts = [
- box.l, box.b,
- box.l, box.t,
- box.r, box.t,
- box.r, box.b
- ];
-
- return new PolyShape(body, verts, vzero);
-};
-
-PolyShape.prototype.transformVerts = function(p, rot)
-{
- var src = this.verts;
- var dst = this.tVerts;
-
- var l = Infinity, r = -Infinity;
- var b = Infinity, t = -Infinity;
-
- for(var i=0; i (' + vx + ',' + vy + ')');
-
- dst[i] = vx;
- dst[i+1] = vy;
-
- l = min(l, vx);
- r = max(r, vx);
- b = min(b, vy);
- t = max(t, vy);
- }
-
- this.bb_l = l;
- this.bb_b = b;
- this.bb_r = r;
- this.bb_t = t;
-};
-
-PolyShape.prototype.transformAxes = function(p, rot)
-{
- var src = this.planes;
- var dst = this.tPlanes;
-
- for(var i=0; i 0) outside = true;
-
- var v1x = verts[i*2];
- var v1y = verts[i*2 + 1];
- var closest = closestPointOnSegment2(p.x, p.y, v0x, v0y, v1x, v1y);
-
- var dist = vdist(p, closest);
- if(dist < minDist){
- minDist = dist;
- closestPoint = closest;
- }
-
- v0x = v1x;
- v0y = v1y;
- }
-
- return new NearestPointQueryInfo(this, closestPoint, (outside ? minDist : -minDist));
-};
-
-PolyShape.prototype.segmentQuery = function(a, b)
-{
- var axes = this.tPlanes;
- var verts = this.tVerts;
- var numVerts = axes.length;
- var len = numVerts * 2;
-
- for(var i=0; i an) continue;
-
- var bn = vdot(b, n);
- var t = (axes[i].d - an)/(bn - an);
- if(t < 0 || 1 < t) continue;
-
- var point = vlerp(a, b, t);
- var dt = -vcross(n, point);
- var dtMin = -vcross2(n.x, n.y, verts[i*2], verts[i*2+1]);
- var dtMax = -vcross2(n.x, n.y, verts[(i*2+2)%len], verts[(i*2+3)%len]);
-
- if(dtMin <= dt && dt <= dtMax){
- // josephg: In the original C code, this function keeps
- // looping through axes after finding a match. I *think*
- // this code is equivalent...
- return new SegmentQueryInfo(this, t, n);
- }
- }
-};
-
-PolyShape.prototype.valueOnAxis = function(n, d)
-{
- var verts = this.tVerts;
- var m = vdot2(n.x, n.y, verts[0], verts[1]);
-
- for(var i=2; i 0) return false;
- }
-
- return true;
-};
-
-PolyShape.prototype.containsVertPartial = function(vx, vy, n)
-{
- var planes = this.tPlanes;
-
- for(var i=0; i 0) return false;
- }
-
- return true;
-};
-
-// These methods are provided for API compatibility with Chipmunk. I recommend against using
-// them - just access the poly.verts list directly.
-PolyShape.prototype.getNumVerts = function() { return this.verts.length / 2; };
-PolyShape.prototype.getVert = function(i)
-{
- return new Vect(this.verts[i * 2], this.verts[i * 2 + 1]);
-};
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-/// @defgroup cpBody cpBody
-/// Chipmunk's rigid body type. Rigid bodies hold the physical properties of an object like
-/// it's mass, and position and velocity of it's center of gravity. They don't have an shape on their own.
-/// They are given a shape by creating collision shapes (cpShape) that point to the body.
-/// @{
-
-var Body = cp.Body = function(m, i) {
- /// Mass of the body.
- /// Must agree with cpBody.m_inv! Use body.setMass() when changing the mass for this reason.
- //this.m;
- /// Mass inverse.
- //this.m_inv;
-
- /// Moment of inertia of the body.
- /// Must agree with cpBody.i_inv! Use body.setMoment() when changing the moment for this reason.
- //this.i;
- /// Moment of inertia inverse.
- //this.i_inv;
-
- /// Position of the rigid body's center of gravity.
- this.p = new Vect(0,0);
- /// Velocity of the rigid body's center of gravity.
- this.vx = this.vy = 0;
- /// Force acting on the rigid body's center of gravity.
- this.f = new Vect(0,0);
-
- /// Rotation of the body around it's center of gravity in radians.
- /// Must agree with cpBody.rot! Use cpBodySetAngle() when changing the angle for this reason.
- //this.a;
- /// Angular velocity of the body around it's center of gravity in radians/second.
- this.w = 0;
- /// Torque applied to the body around it's center of gravity.
- this.t = 0;
-
- /// Cached unit length vector representing the angle of the body.
- /// Used for fast rotations using cpvrotate().
- //cpVect rot;
-
- /// Maximum velocity allowed when updating the velocity.
- this.v_limit = Infinity;
- /// Maximum rotational rate (in radians/second) allowed when updating the angular velocity.
- this.w_limit = Infinity;
-
- // This stuff is all private.
- this.v_biasx = this.v_biasy = 0;
- this.w_bias = 0;
-
- this.space = null;
-
- this.shapeList = [];
- this.arbiterList = null; // These are both wacky linked lists.
- this.constraintList = null;
-
- // This stuff is used to track information on the collision graph.
- this.nodeRoot = null;
- this.nodeNext = null;
- this.nodeIdleTime = 0;
-
- // Set this.m and this.m_inv
- this.setMass(m);
-
- // Set this.i and this.i_inv
- this.setMoment(i);
-
- // Set this.a and this.rot
- this.rot = new Vect(0,0);
- this.setAngle(0);
-};
-
-// I wonder if this should use the constructor style like Body...
-var createStaticBody = function()
-{
- var body = new Body(Infinity, Infinity);
- body.nodeIdleTime = Infinity;
-
- return body;
-};
- cp.StaticBody = createStaticBody;
-
-if (typeof DEBUG !== 'undefined' && DEBUG) {
- var v_assert_nan = function(v, message){assert(v.x == v.x && v.y == v.y, message); };
- var v_assert_infinite = function(v, message){assert(Math.abs(v.x) !== Infinity && Math.abs(v.y) !== Infinity, message);};
- var v_assert_sane = function(v, message){v_assert_nan(v, message); v_assert_infinite(v, message);};
-
- Body.prototype.sanityCheck = function()
- {
- assert(this.m === this.m && this.m_inv === this.m_inv, "Body's mass is invalid.");
- assert(this.i === this.i && this.i_inv === this.i_inv, "Body's moment is invalid.");
-
- v_assert_sane(this.p, "Body's position is invalid.");
- v_assert_sane(this.f, "Body's force is invalid.");
- assert(this.vx === this.vx && Math.abs(this.vx) !== Infinity, "Body's velocity is invalid.");
- assert(this.vy === this.vy && Math.abs(this.vy) !== Infinity, "Body's velocity is invalid.");
-
- assert(this.a === this.a && Math.abs(this.a) !== Infinity, "Body's angle is invalid.");
- assert(this.w === this.w && Math.abs(this.w) !== Infinity, "Body's angular velocity is invalid.");
- assert(this.t === this.t && Math.abs(this.t) !== Infinity, "Body's torque is invalid.");
-
- v_assert_sane(this.rot, "Body's rotation vector is invalid.");
-
- assert(this.v_limit === this.v_limit, "Body's velocity limit is invalid.");
- assert(this.w_limit === this.w_limit, "Body's angular velocity limit is invalid.");
- };
-} else {
- Body.prototype.sanityCheck = function(){};
-}
-
-Body.prototype.getPos = function() { return this.p; };
-Body.prototype.getVel = function() { return new Vect(this.vx, this.vy); };
-Body.prototype.getAngVel = function() { return this.w; };
-
-/// Returns true if the body is sleeping.
-Body.prototype.isSleeping = function()
-{
- return this.nodeRoot !== null;
-};
-
-/// Returns true if the body is static.
-Body.prototype.isStatic = function()
-{
- return this.nodeIdleTime === Infinity;
-};
-
-/// Returns true if the body has not been added to a space.
-Body.prototype.isRogue = function()
-{
- return this.space === null;
-};
-
-// It would be nicer to use defineProperty for this, but its about 30x slower:
-// http://jsperf.com/defineproperty-vs-setter
-Body.prototype.setMass = function(mass)
-{
- assert(mass > 0, "Mass must be positive and non-zero.");
-
- //activate is defined in cpSpaceComponent
- this.activate();
- this.m = mass;
- this.m_inv = 1/mass;
-};
-
-Body.prototype.setMoment = function(moment)
-{
- assert(moment > 0, "Moment of Inertia must be positive and non-zero.");
-
- this.activate();
- this.i = moment;
- this.i_inv = 1/moment;
-};
-
-Body.prototype.addShape = function(shape)
-{
- this.shapeList.push(shape);
-};
-
-Body.prototype.removeShape = function(shape)
-{
- // This implementation has a linear time complexity with the number of shapes.
- // The original implementation used linked lists instead, which might be faster if
- // you're constantly editing the shape of a body. I expect most bodies will never
- // have their shape edited, so I'm just going to use the simplest possible implemention.
- deleteObjFromList(this.shapeList, shape);
-};
-
-var filterConstraints = function(node, body, filter)
-{
- if(node === filter){
- return node.next(body);
- } else if(node.a === body){
- node.next_a = filterConstraints(node.next_a, body, filter);
- } else {
- node.next_b = filterConstraints(node.next_b, body, filter);
- }
-
- return node;
-};
-
-Body.prototype.removeConstraint = function(constraint)
-{
- // The constraint must be in the constraints list when this is called.
- this.constraintList = filterConstraints(this.constraintList, this, constraint);
-};
-
-Body.prototype.setPos = function(pos)
-{
- this.activate();
- this.sanityCheck();
- // If I allow the position to be set to vzero, vzero will get changed.
- if (pos === vzero) {
- pos = cp.v(0,0);
- }
- this.p = pos;
-};
-
-Body.prototype.setVel = function(velocity)
-{
- this.activate();
- this.vx = velocity.x;
- this.vy = velocity.y;
-};
-
-Body.prototype.setAngVel = function(w)
-{
- this.activate();
- this.w = w;
-};
-
-Body.prototype.setAngleInternal = function(angle)
-{
- assert(!isNaN(angle), "Internal Error: Attempting to set body's angle to NaN");
- this.a = angle;//fmod(a, (cpFloat)M_PI*2.0f);
-
- //this.rot = vforangle(angle);
- this.rot.x = Math.cos(angle);
- this.rot.y = Math.sin(angle);
-};
-
-Body.prototype.setAngle = function(angle)
-{
- this.activate();
- this.sanityCheck();
- this.setAngleInternal(angle);
-};
-
-Body.prototype.velocity_func = function(gravity, damping, dt)
-{
- //this.v = vclamp(vadd(vmult(this.v, damping), vmult(vadd(gravity, vmult(this.f, this.m_inv)), dt)), this.v_limit);
- var vx = this.vx * damping + (gravity.x + this.f.x * this.m_inv) * dt;
- var vy = this.vy * damping + (gravity.y + this.f.y * this.m_inv) * dt;
-
- //var v = vclamp(new Vect(vx, vy), this.v_limit);
- //this.vx = v.x; this.vy = v.y;
- var v_limit = this.v_limit;
- var lensq = vx * vx + vy * vy;
- var scale = (lensq > v_limit*v_limit) ? v_limit / Math.sqrt(lensq) : 1;
- this.vx = vx * scale;
- this.vy = vy * scale;
-
- var w_limit = this.w_limit;
- this.w = clamp(this.w*damping + this.t*this.i_inv*dt, -w_limit, w_limit);
-
- this.sanityCheck();
-};
-
-Body.prototype.position_func = function(dt)
-{
- //this.p = vadd(this.p, vmult(vadd(this.v, this.v_bias), dt));
-
- //this.p = this.p + (this.v + this.v_bias) * dt;
- this.p.x += (this.vx + this.v_biasx) * dt;
- this.p.y += (this.vy + this.v_biasy) * dt;
-
- this.setAngleInternal(this.a + (this.w + this.w_bias)*dt);
-
- this.v_biasx = this.v_biasy = 0;
- this.w_bias = 0;
-
- this.sanityCheck();
-};
-
-Body.prototype.resetForces = function()
-{
- this.activate();
- this.f = new Vect(0,0);
- this.t = 0;
-};
-
-Body.prototype.applyForce = function(force, r)
-{
- this.activate();
- this.f = vadd(this.f, force);
- this.t += vcross(r, force);
-};
-
-Body.prototype.applyImpulse = function(j, r)
-{
- this.activate();
- apply_impulse(this, j.x, j.y, r);
-};
-
-Body.prototype.getVelAtPoint = function(r)
-{
- return vadd(new Vect(this.vx, this.vy), vmult(vperp(r), this.w));
-};
-
-/// Get the velocity on a body (in world units) at a point on the body in world coordinates.
-Body.prototype.getVelAtWorldPoint = function(point)
-{
- return this.getVelAtPoint(vsub(point, this.p));
-};
-
-/// Get the velocity on a body (in world units) at a point on the body in local coordinates.
-Body.prototype.getVelAtLocalPoint = function(point)
-{
- return this.getVelAtPoint(vrotate(point, this.rot));
-};
-
-Body.prototype.eachShape = function(func)
-{
- for(var i = 0, len = this.shapeList.length; i < len; i++) {
- func(this.shapeList[i]);
- }
-};
-
-Body.prototype.eachConstraint = function(func)
-{
- var constraint = this.constraintList;
- while(constraint) {
- var next = constraint.next(this);
- func(constraint);
- constraint = next;
- }
-};
-
-Body.prototype.eachArbiter = function(func)
-{
- var arb = this.arbiterList;
- while(arb){
- var next = arb.next(this);
-
- arb.swappedColl = (this === arb.body_b);
- func(arb);
-
- arb = next;
- }
-};
-
-/// Convert body relative/local coordinates to absolute/world coordinates.
-Body.prototype.local2World = function(v)
-{
- return vadd(this.p, vrotate(v, this.rot));
-};
-
-/// Convert body absolute/world coordinates to relative/local coordinates.
-Body.prototype.world2Local = function(v)
-{
- return vunrotate(vsub(v, this.p), this.rot);
-};
-
-/// Get the kinetic energy of a body.
-Body.prototype.kineticEnergy = function()
-{
- // Need to do some fudging to avoid NaNs
- var vsq = this.vx*this.vx + this.vy*this.vy;
- var wsq = this.w * this.w;
- return (vsq ? vsq*this.m : 0) + (wsq ? wsq*this.i : 0);
-};
-
-/* Copyright (c) 2010 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-/**
- @defgroup cpSpatialIndex cpSpatialIndex
-
- Spatial indexes are data structures that are used to accelerate collision detection
- and spatial queries. Chipmunk provides a number of spatial index algorithms to pick from
- and they are programmed in a generic way so that you can use them for holding more than
- just Shapes.
-
- It works by using pointers to the objects you add and using a callback to ask your code
- for bounding boxes when it needs them. Several types of queries can be performed an index as well
- as reindexing and full collision information. All communication to the spatial indexes is performed
- through callback functions.
-
- Spatial indexes should be treated as opaque structs.
- This means you shouldn't be reading any of the fields directly.
-
- All spatial indexes define the following methods:
-
- // The number of objects in the spatial index.
- count = 0;
-
- // Iterate the objects in the spatial index. @c func will be called once for each object.
- each(func);
-
- // Returns true if the spatial index contains the given object.
- // Most spatial indexes use hashed storage, so you must provide a hash value too.
- contains(obj, hashid);
-
- // Add an object to a spatial index.
- insert(obj, hashid);
-
- // Remove an object from a spatial index.
- remove(obj, hashid);
-
- // Perform a full reindex of a spatial index.
- reindex();
-
- // Reindex a single object in the spatial index.
- reindexObject(obj, hashid);
-
- // Perform a point query against the spatial index, calling @c func for each potential match.
- // A pointer to the point will be passed as @c obj1 of @c func.
- // func(shape);
- pointQuery(point, func);
-
- // Perform a segment query against the spatial index, calling @c func for each potential match.
- // func(shape);
- segmentQuery(vect a, vect b, t_exit, func);
-
- // Perform a rectangle query against the spatial index, calling @c func for each potential match.
- // func(shape);
- query(bb, func);
-
- // Simultaneously reindex and find all colliding objects.
- // @c func will be called once for each potentially overlapping pair of objects found.
- // If the spatial index was initialized with a static index, it will collide it's objects against that as well.
- reindexQuery(func);
-*/
-
-var SpatialIndex = cp.SpatialIndex = function(staticIndex)
-{
- this.staticIndex = staticIndex;
-
-
- if(staticIndex){
- if(staticIndex.dynamicIndex){
- throw new Error("This static index is already associated with a dynamic index.");
- }
- staticIndex.dynamicIndex = this;
- }
-};
-
-// Collide the objects in an index against the objects in a staticIndex using the query callback function.
-SpatialIndex.prototype.collideStatic = function(staticIndex, func)
-{
- if(staticIndex.count > 0){
- var query = staticIndex.query;
-
- this.each(function(obj) {
- query(obj, new BB(obj.bb_l, obj.bb_b, obj.bb_r, obj.bb_t), func);
- });
- }
-};
-
-
-/* Copyright (c) 2009 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-// This file implements a modified AABB tree for collision detection.
-
-var BBTree = cp.BBTree = function(staticIndex)
-{
- SpatialIndex.call(this, staticIndex);
-
- this.velocityFunc = null;
-
- // This is a hash from object ID -> object for the objects stored in the BBTree.
- this.leaves = {};
- // A count of the number of leaves in the BBTree.
- this.count = 0;
-
- this.root = null;
-
- // A linked list containing an object pool of tree nodes and pairs.
- this.pooledNodes = null;
- this.pooledPairs = null;
-
- this.stamp = 0;
-};
-
-BBTree.prototype = Object.create(SpatialIndex.prototype);
-
-var numNodes = 0;
-
-var Node = function(tree, a, b)
-{
- this.obj = null;
- this.bb_l = min(a.bb_l, b.bb_l);
- this.bb_b = min(a.bb_b, b.bb_b);
- this.bb_r = max(a.bb_r, b.bb_r);
- this.bb_t = max(a.bb_t, b.bb_t);
- this.parent = null;
-
- this.setA(a);
- this.setB(b);
-};
-
-BBTree.prototype.makeNode = function(a, b)
-{
- var node = this.pooledNodes;
- if(node){
- this.pooledNodes = node.parent;
- node.constructor(this, a, b);
- return node;
- } else {
- numNodes++;
- return new Node(this, a, b);
- }
-};
-
-var numLeaves = 0;
-var Leaf = function(tree, obj)
-{
- this.obj = obj;
- tree.getBB(obj, this);
-
- this.parent = null;
-
- this.stamp = 1;
- this.pairs = null;
- numLeaves++;
-};
-
-// **** Misc Functions
-
-BBTree.prototype.getBB = function(obj, dest)
-{
- var velocityFunc = this.velocityFunc;
- if(velocityFunc){
- var coef = 0.1;
- var x = (obj.bb_r - obj.bb_l)*coef;
- var y = (obj.bb_t - obj.bb_b)*coef;
-
- var v = vmult(velocityFunc(obj), 0.1);
-
- dest.bb_l = obj.bb_l + min(-x, v.x);
- dest.bb_b = obj.bb_b + min(-y, v.y);
- dest.bb_r = obj.bb_r + max( x, v.x);
- dest.bb_t = obj.bb_t + max( y, v.y);
- } else {
- dest.bb_l = obj.bb_l;
- dest.bb_b = obj.bb_b;
- dest.bb_r = obj.bb_r;
- dest.bb_t = obj.bb_t;
- }
-};
-
-BBTree.prototype.getStamp = function()
-{
- var dynamic = this.dynamicIndex;
- return (dynamic && dynamic.stamp ? dynamic.stamp : this.stamp);
-};
-
-BBTree.prototype.incrementStamp = function()
-{
- if(this.dynamicIndex && this.dynamicIndex.stamp){
- this.dynamicIndex.stamp++;
- } else {
- this.stamp++;
- }
-}
-
-// **** Pair/Thread Functions
-
-var numPairs = 0;
-// Objects created with constructors are faster than object literals. :(
-var Pair = function(leafA, nextA, leafB, nextB)
-{
- this.prevA = null;
- this.leafA = leafA;
- this.nextA = nextA;
-
- this.prevB = null;
- this.leafB = leafB;
- this.nextB = nextB;
-};
-
-BBTree.prototype.makePair = function(leafA, nextA, leafB, nextB)
-{
- //return new Pair(leafA, nextA, leafB, nextB);
- var pair = this.pooledPairs;
- if (pair)
- {
- this.pooledPairs = pair.prevA;
-
- pair.prevA = null;
- pair.leafA = leafA;
- pair.nextA = nextA;
-
- pair.prevB = null;
- pair.leafB = leafB;
- pair.nextB = nextB;
-
- //pair.constructor(leafA, nextA, leafB, nextB);
- return pair;
- } else {
- numPairs++;
- return new Pair(leafA, nextA, leafB, nextB);
- }
-};
-
-Pair.prototype.recycle = function(tree)
-{
- this.prevA = tree.pooledPairs;
- tree.pooledPairs = this;
-};
-
-var unlinkThread = function(prev, leaf, next)
-{
- if(next){
- if(next.leafA === leaf) next.prevA = prev; else next.prevB = prev;
- }
-
- if(prev){
- if(prev.leafA === leaf) prev.nextA = next; else prev.nextB = next;
- } else {
- leaf.pairs = next;
- }
-};
-
-Leaf.prototype.clearPairs = function(tree)
-{
- var pair = this.pairs,
- next;
-
- this.pairs = null;
-
- while(pair){
- if(pair.leafA === this){
- next = pair.nextA;
- unlinkThread(pair.prevB, pair.leafB, pair.nextB);
- } else {
- next = pair.nextB;
- unlinkThread(pair.prevA, pair.leafA, pair.nextA);
- }
- pair.recycle(tree);
- pair = next;
- }
-};
-
-var pairInsert = function(a, b, tree)
-{
- var nextA = a.pairs, nextB = b.pairs;
- var pair = tree.makePair(a, nextA, b, nextB);
- a.pairs = b.pairs = pair;
-
- if(nextA){
- if(nextA.leafA === a) nextA.prevA = pair; else nextA.prevB = pair;
- }
-
- if(nextB){
- if(nextB.leafA === b) nextB.prevA = pair; else nextB.prevB = pair;
- }
-};
-
-// **** Node Functions
-
-Node.prototype.recycle = function(tree)
-{
- this.parent = tree.pooledNodes;
- tree.pooledNodes = this;
-};
-
-Leaf.prototype.recycle = function(tree)
-{
- // Its not worth the overhead to recycle leaves.
-};
-
-Node.prototype.setA = function(value)
-{
- this.A = value;
- value.parent = this;
-};
-
-Node.prototype.setB = function(value)
-{
- this.B = value;
- value.parent = this;
-};
-
-Leaf.prototype.isLeaf = true;
-Node.prototype.isLeaf = false;
-
-Node.prototype.otherChild = function(child)
-{
- return (this.A == child ? this.B : this.A);
-};
-
-Node.prototype.replaceChild = function(child, value, tree)
-{
- assertSoft(child == this.A || child == this.B, "Node is not a child of parent.");
-
- if(this.A == child){
- this.A.recycle(tree);
- this.setA(value);
- } else {
- this.B.recycle(tree);
- this.setB(value);
- }
-
- for(var node=this; node; node = node.parent){
- //node.bb = bbMerge(node.A.bb, node.B.bb);
- var a = node.A;
- var b = node.B;
- node.bb_l = min(a.bb_l, b.bb_l);
- node.bb_b = min(a.bb_b, b.bb_b);
- node.bb_r = max(a.bb_r, b.bb_r);
- node.bb_t = max(a.bb_t, b.bb_t);
- }
-};
-
-Node.prototype.bbArea = Leaf.prototype.bbArea = function()
-{
- return (this.bb_r - this.bb_l)*(this.bb_t - this.bb_b);
-};
-
-var bbTreeMergedArea = function(a, b)
-{
- return (max(a.bb_r, b.bb_r) - min(a.bb_l, b.bb_l))*(max(a.bb_t, b.bb_t) - min(a.bb_b, b.bb_b));
-};
-
-// **** Subtree Functions
-
-// Would it be better to make these functions instance methods on Node and Leaf?
-
-var bbProximity = function(a, b)
-{
- return Math.abs(a.bb_l + a.bb_r - b.bb_l - b.bb_r) + Math.abs(a.bb_b + a.bb_t - b.bb_b - b.bb_t);
-};
-
-var subtreeInsert = function(subtree, leaf, tree)
-{
-// var s = new Error().stack;
-// traces[s] = traces[s] ? traces[s]+1 : 1;
-
- if(subtree == null){
- return leaf;
- } else if(subtree.isLeaf){
- return tree.makeNode(leaf, subtree);
- } else {
- var cost_a = subtree.B.bbArea() + bbTreeMergedArea(subtree.A, leaf);
- var cost_b = subtree.A.bbArea() + bbTreeMergedArea(subtree.B, leaf);
-
- if(cost_a === cost_b){
- cost_a = bbProximity(subtree.A, leaf);
- cost_b = bbProximity(subtree.B, leaf);
- }
-
- if(cost_b < cost_a){
- subtree.setB(subtreeInsert(subtree.B, leaf, tree));
- } else {
- subtree.setA(subtreeInsert(subtree.A, leaf, tree));
- }
-
-// subtree.bb = bbMerge(subtree.bb, leaf.bb);
- subtree.bb_l = min(subtree.bb_l, leaf.bb_l);
- subtree.bb_b = min(subtree.bb_b, leaf.bb_b);
- subtree.bb_r = max(subtree.bb_r, leaf.bb_r);
- subtree.bb_t = max(subtree.bb_t, leaf.bb_t);
-
- return subtree;
- }
-};
-
-Node.prototype.intersectsBB = Leaf.prototype.intersectsBB = function(bb)
-{
- return (this.bb_l <= bb.r && bb.l <= this.bb_r && this.bb_b <= bb.t && bb.b <= this.bb_t);
-};
-
-var subtreeQuery = function(subtree, bb, func)
-{
- //if(bbIntersectsBB(subtree.bb, bb)){
- if(subtree.intersectsBB(bb)){
- if(subtree.isLeaf){
- func(subtree.obj);
- } else {
- subtreeQuery(subtree.A, bb, func);
- subtreeQuery(subtree.B, bb, func);
- }
- }
-};
-
-/// Returns the fraction along the segment query the node hits. Returns Infinity if it doesn't hit.
-var nodeSegmentQuery = function(node, a, b)
-{
- var idx = 1/(b.x - a.x);
- var tx1 = (node.bb_l == a.x ? -Infinity : (node.bb_l - a.x)*idx);
- var tx2 = (node.bb_r == a.x ? Infinity : (node.bb_r - a.x)*idx);
- var txmin = min(tx1, tx2);
- var txmax = max(tx1, tx2);
-
- var idy = 1/(b.y - a.y);
- var ty1 = (node.bb_b == a.y ? -Infinity : (node.bb_b - a.y)*idy);
- var ty2 = (node.bb_t == a.y ? Infinity : (node.bb_t - a.y)*idy);
- var tymin = min(ty1, ty2);
- var tymax = max(ty1, ty2);
-
- if(tymin <= txmax && txmin <= tymax){
- var min_ = max(txmin, tymin);
- var max_ = min(txmax, tymax);
-
- if(0.0 <= max_ && min_ <= 1.0) return max(min_, 0.0);
- }
-
- return Infinity;
-};
-
-var subtreeSegmentQuery = function(subtree, a, b, t_exit, func)
-{
- if(subtree.isLeaf){
- return func(subtree.obj);
- } else {
- var t_a = nodeSegmentQuery(subtree.A, a, b);
- var t_b = nodeSegmentQuery(subtree.B, a, b);
-
- if(t_a < t_b){
- if(t_a < t_exit) t_exit = min(t_exit, subtreeSegmentQuery(subtree.A, a, b, t_exit, func));
- if(t_b < t_exit) t_exit = min(t_exit, subtreeSegmentQuery(subtree.B, a, b, t_exit, func));
- } else {
- if(t_b < t_exit) t_exit = min(t_exit, subtreeSegmentQuery(subtree.B, a, b, t_exit, func));
- if(t_a < t_exit) t_exit = min(t_exit, subtreeSegmentQuery(subtree.A, a, b, t_exit, func));
- }
-
- return t_exit;
- }
-};
-
-BBTree.prototype.subtreeRecycle = function(node)
-{
- if(node.isLeaf){
- this.subtreeRecycle(node.A);
- this.subtreeRecycle(node.B);
- node.recycle(this);
- }
-};
-
-var subtreeRemove = function(subtree, leaf, tree)
-{
- if(leaf == subtree){
- return null;
- } else {
- var parent = leaf.parent;
- if(parent == subtree){
- var other = subtree.otherChild(leaf);
- other.parent = subtree.parent;
- subtree.recycle(tree);
- return other;
- } else {
- parent.parent.replaceChild(parent, parent.otherChild(leaf), tree);
- return subtree;
- }
- }
-};
-
-// **** Marking Functions
-
-/*
-typedef struct MarkContext {
- bbTree *tree;
- Node *staticRoot;
- cpSpatialIndexQueryFunc func;
-} MarkContext;
-*/
-
-var bbTreeIntersectsNode = function(a, b)
-{
- return (a.bb_l <= b.bb_r && b.bb_l <= a.bb_r && a.bb_b <= b.bb_t && b.bb_b <= a.bb_t);
-};
-
-Leaf.prototype.markLeafQuery = function(leaf, left, tree, func)
-{
- if(bbTreeIntersectsNode(leaf, this)){
- if(left){
- pairInsert(leaf, this, tree);
- } else {
- if(this.stamp < leaf.stamp) pairInsert(this, leaf, tree);
- if(func) func(leaf.obj, this.obj);
- }
- }
-};
-
-Node.prototype.markLeafQuery = function(leaf, left, tree, func)
-{
- if(bbTreeIntersectsNode(leaf, this)){
- this.A.markLeafQuery(leaf, left, tree, func);
- this.B.markLeafQuery(leaf, left, tree, func);
- }
-};
-
-Leaf.prototype.markSubtree = function(tree, staticRoot, func)
-{
- if(this.stamp == tree.getStamp()){
- if(staticRoot) staticRoot.markLeafQuery(this, false, tree, func);
-
- for(var node = this; node.parent; node = node.parent){
- if(node == node.parent.A){
- node.parent.B.markLeafQuery(this, true, tree, func);
- } else {
- node.parent.A.markLeafQuery(this, false, tree, func);
- }
- }
- } else {
- var pair = this.pairs;
- while(pair){
- if(this === pair.leafB){
- if(func) func(pair.leafA.obj, this.obj);
- pair = pair.nextB;
- } else {
- pair = pair.nextA;
- }
- }
- }
-};
-
-Node.prototype.markSubtree = function(tree, staticRoot, func)
-{
- this.A.markSubtree(tree, staticRoot, func);
- this.B.markSubtree(tree, staticRoot, func);
-};
-
-// **** Leaf Functions
-
-Leaf.prototype.containsObj = function(obj)
-{
- return (this.bb_l <= obj.bb_l && this.bb_r >= obj.bb_r && this.bb_b <= obj.bb_b && this.bb_t >= obj.bb_t);
-};
-
-Leaf.prototype.update = function(tree)
-{
- var root = tree.root;
- var obj = this.obj;
-
- //if(!bbContainsBB(this.bb, bb)){
- if(!this.containsObj(obj)){
- tree.getBB(this.obj, this);
-
- root = subtreeRemove(root, this, tree);
- tree.root = subtreeInsert(root, this, tree);
-
- this.clearPairs(tree);
- this.stamp = tree.getStamp();
-
- return true;
- }
-
- return false;
-};
-
-Leaf.prototype.addPairs = function(tree)
-{
- var dynamicIndex = tree.dynamicIndex;
- if(dynamicIndex){
- var dynamicRoot = dynamicIndex.root;
- if(dynamicRoot){
- dynamicRoot.markLeafQuery(this, true, dynamicIndex, null);
- }
- } else {
- var staticRoot = tree.staticIndex.root;
- this.markSubtree(tree, staticRoot, null);
- }
-};
-
-// **** Insert/Remove
-
-BBTree.prototype.insert = function(obj, hashid)
-{
- var leaf = new Leaf(this, obj);
-
- this.leaves[hashid] = leaf;
- this.root = subtreeInsert(this.root, leaf, this);
- this.count++;
-
- leaf.stamp = this.getStamp();
- leaf.addPairs(this);
- this.incrementStamp();
-};
-
-BBTree.prototype.remove = function(obj, hashid)
-{
- var leaf = this.leaves[hashid];
-
- delete this.leaves[hashid];
- this.root = subtreeRemove(this.root, leaf, this);
- this.count--;
-
- leaf.clearPairs(this);
- leaf.recycle(this);
-};
-
-BBTree.prototype.contains = function(obj, hashid)
-{
- return this.leaves[hashid] != null;
-};
-
-// **** Reindex
-var voidQueryFunc = function(obj1, obj2){};
-
-BBTree.prototype.reindexQuery = function(func)
-{
- if(!this.root) return;
-
- // LeafUpdate() may modify this.root. Don't cache it.
- var hashid,
- leaves = this.leaves;
- for (hashid in leaves)
- {
- leaves[hashid].update(this);
- }
-
- var staticIndex = this.staticIndex;
- var staticRoot = staticIndex && staticIndex.root;
-
- this.root.markSubtree(this, staticRoot, func);
- if(staticIndex && !staticRoot) this.collideStatic(this, staticIndex, func);
-
- this.incrementStamp();
-};
-
-BBTree.prototype.reindex = function()
-{
- this.reindexQuery(voidQueryFunc);
-};
-
-BBTree.prototype.reindexObject = function(obj, hashid)
-{
- var leaf = this.leaves[hashid];
- if(leaf){
- if(leaf.update(this)) leaf.addPairs(this);
- this.incrementStamp();
- }
-};
-
-// **** Query
-
-// This has since been removed from upstream Chipmunk - which recommends you just use query() below
-// directly.
-BBTree.prototype.pointQuery = function(point, func)
-{
- this.query(new BB(point.x, point.y, point.x, point.y), func);
-};
-
-BBTree.prototype.segmentQuery = function(a, b, t_exit, func)
-{
- if(this.root) subtreeSegmentQuery(this.root, a, b, t_exit, func);
-};
-
-BBTree.prototype.query = function(bb, func)
-{
- if(this.root) subtreeQuery(this.root, bb, func);
-};
-
-// **** Misc
-
-BBTree.prototype.count = function()
-{
- return this.count;
-};
-
-BBTree.prototype.each = function(func)
-{
- var hashid;
- for(hashid in this.leaves)
- {
- func(this.leaves[hashid].obj);
- }
-};
-
-// **** Tree Optimization
-
-var bbTreeMergedArea2 = function(node, l, b, r, t)
-{
- return (max(node.bb_r, r) - min(node.bb_l, l))*(max(node.bb_t, t) - min(node.bb_b, b));
-};
-
-var partitionNodes = function(tree, nodes, offset, count)
-{
- if(count == 1){
- return nodes[offset];
- } else if(count == 2) {
- return tree.makeNode(nodes[offset], nodes[offset + 1]);
- }
-
- // Find the AABB for these nodes
- //var bb = nodes[offset].bb;
- var node = nodes[offset];
- var bb_l = node.bb_l,
- bb_b = node.bb_b,
- bb_r = node.bb_r,
- bb_t = node.bb_t;
-
- var end = offset + count;
- for(var i=offset + 1; i bb_t - bb_b);
-
- // Sort the bounds and use the median as the splitting point
- var bounds = new Array(count*2);
- if(splitWidth){
- for(var i=offset; inext = next;
- if(prev.body_a === body) {
- prev.thread_a_next = next;
- } else {
- prev.thread_b_next = next;
- }
- } else {
- body.arbiterList = next;
- }
-
- if(next){
- // cpArbiterThreadForBody(next, body)->prev = prev;
- if(next.body_a === body){
- next.thread_a_prev = prev;
- } else {
- next.thread_b_prev = prev;
- }
- }
-};
-
-Arbiter.prototype.unthread = function()
-{
- unthreadHelper(this, this.body_a, this.thread_a_prev, this.thread_a_next);
- unthreadHelper(this, this.body_b, this.thread_b_prev, this.thread_b_next);
- this.thread_a_prev = this.thread_a_next = null;
- this.thread_b_prev = this.thread_b_next = null;
-};
-
-//cpFloat
-//cpContactsEstimateCrushingImpulse(cpContact *contacts, int numContacts)
-//{
-// cpFloat fsum = 0;
-// cpVect vsum = vzero;
-//
-// for(int i=0; i= mindist*mindist) return;
-
- var dist = Math.sqrt(distsq);
-
- // Allocate and initialize the contact.
- return new Contact(
- vadd(p1, vmult(delta, 0.5 + (r1 - 0.5*mindist)/(dist ? dist : Infinity))),
- (dist ? vmult(delta, 1/dist) : new Vect(1, 0)),
- dist - mindist,
- 0
- );
-};
-
-// Collide circle shapes.
-var circle2circle = function(circ1, circ2)
-{
- var contact = circle2circleQuery(circ1.tc, circ2.tc, circ1.r, circ2.r);
- return contact ? [contact] : NONE;
-};
-
-var circle2segment = function(circleShape, segmentShape)
-{
- var seg_a = segmentShape.ta;
- var seg_b = segmentShape.tb;
- var center = circleShape.tc;
-
- var seg_delta = vsub(seg_b, seg_a);
- var closest_t = clamp01(vdot(seg_delta, vsub(center, seg_a))/vlengthsq(seg_delta));
- var closest = vadd(seg_a, vmult(seg_delta, closest_t));
-
- var contact = circle2circleQuery(center, closest, circleShape.r, segmentShape.r);
- if(contact){
- var n = contact.n;
-
- // Reject endcap collisions if tangents are provided.
- return (
- (closest_t === 0 && vdot(n, segmentShape.a_tangent) < 0) ||
- (closest_t === 1 && vdot(n, segmentShape.b_tangent) < 0)
- ) ? NONE : [contact];
- } else {
- return NONE;
- }
-}
-
-// Find the minimum separating axis for the given poly and axis list.
-//
-// This function needs to return two values - the index of the min. separating axis and
-// the value itself. Short of inlining MSA, returning values through a global like this
-// is the fastest implementation.
-//
-// See: http://jsperf.com/return-two-values-from-function/2
-var last_MSA_min = 0;
-var findMSA = function(poly, planes)
-{
- var min_index = 0;
- var min = poly.valueOnAxis(planes[0].n, planes[0].d);
- if(min > 0) return -1;
-
- for(var i=1; i 0) {
- return -1;
- } else if(dist > min){
- min = dist;
- min_index = i;
- }
- }
-
- last_MSA_min = min;
- return min_index;
-};
-
-// Add contacts for probably penetrating vertexes.
-// This handles the degenerate case where an overlap was detected, but no vertexes fall inside
-// the opposing polygon. (like a star of david)
-var findVertsFallback = function(poly1, poly2, n, dist)
-{
- var arr = [];
-
- var verts1 = poly1.tVerts;
- for(var i=0; i>1)));
- }
- }
-
- var verts2 = poly2.tVerts;
- for(var i=0; i>1)));
- }
- }
-
- return (arr.length ? arr : findVertsFallback(poly1, poly2, n, dist));
-};
-
-// Collide poly shapes together.
-var poly2poly = function(poly1, poly2)
-{
- var mini1 = findMSA(poly2, poly1.tPlanes);
- if(mini1 == -1) return NONE;
- var min1 = last_MSA_min;
-
- var mini2 = findMSA(poly1, poly2.tPlanes);
- if(mini2 == -1) return NONE;
- var min2 = last_MSA_min;
-
- // There is overlap, find the penetrating verts
- if(min1 > min2)
- return findVerts(poly1, poly2, poly1.tPlanes[mini1].n, min1);
- else
- return findVerts(poly1, poly2, vneg(poly2.tPlanes[mini2].n), min2);
-};
-
-// Like cpPolyValueOnAxis(), but for segments.
-var segValueOnAxis = function(seg, n, d)
-{
- var a = vdot(n, seg.ta) - seg.r;
- var b = vdot(n, seg.tb) - seg.r;
- return min(a, b) - d;
-};
-
-// Identify vertexes that have penetrated the segment.
-var findPointsBehindSeg = function(arr, seg, poly, pDist, coef)
-{
- var dta = vcross(seg.tn, seg.ta);
- var dtb = vcross(seg.tn, seg.tb);
- var n = vmult(seg.tn, coef);
-
- var verts = poly.tVerts;
- for(var i=0; i= dt && dt >= dtb){
- arr.push(new Contact(new Vect(vx, vy), n, pDist, hashPair(poly.hashid, i)));
- }
- }
- }
-};
-
-// This one is complicated and gross. Just don't go there...
-// TODO: Comment me!
-var seg2poly = function(seg, poly)
-{
- var arr = [];
-
- var planes = poly.tPlanes;
- var numVerts = planes.length;
-
- var segD = vdot(seg.tn, seg.ta);
- var minNorm = poly.valueOnAxis(seg.tn, segD) - seg.r;
- var minNeg = poly.valueOnAxis(vneg(seg.tn), -segD) - seg.r;
- if(minNeg > 0 || minNorm > 0) return NONE;
-
- var mini = 0;
- var poly_min = segValueOnAxis(seg, planes[0].n, planes[0].d);
- if(poly_min > 0) return NONE;
- for(var i=0; i 0){
- return NONE;
- } else if(dist > poly_min){
- poly_min = dist;
- mini = i;
- }
- }
-
- var poly_n = vneg(planes[mini].n);
-
- var va = vadd(seg.ta, vmult(poly_n, seg.r));
- var vb = vadd(seg.tb, vmult(poly_n, seg.r));
- if(poly.containsVert(va.x, va.y))
- arr.push(new Contact(va, poly_n, poly_min, hashPair(seg.hashid, 0)));
- if(poly.containsVert(vb.x, vb.y))
- arr.push(new Contact(vb, poly_n, poly_min, hashPair(seg.hashid, 1)));
-
- // Floating point precision problems here.
- // This will have to do for now.
-// poly_min -= cp_collision_slop; // TODO is this needed anymore?
-
- if(minNorm >= poly_min || minNeg >= poly_min) {
- if(minNorm > minNeg)
- findPointsBehindSeg(arr, seg, poly, minNorm, 1);
- else
- findPointsBehindSeg(arr, seg, poly, minNeg, -1);
- }
-
- // If no other collision points are found, try colliding endpoints.
- if(arr.length === 0){
- var mini2 = mini * 2;
- var verts = poly.tVerts;
-
- var poly_a = new Vect(verts[mini2], verts[mini2+1]);
-
- var con;
- if((con = circle2circleQuery(seg.ta, poly_a, seg.r, 0, arr))) return [con];
- if((con = circle2circleQuery(seg.tb, poly_a, seg.r, 0, arr))) return [con];
-
- var len = numVerts * 2;
- var poly_b = new Vect(verts[(mini2+2)%len], verts[(mini2+3)%len]);
- if((con = circle2circleQuery(seg.ta, poly_b, seg.r, 0, arr))) return [con];
- if((con = circle2circleQuery(seg.tb, poly_b, seg.r, 0, arr))) return [con];
- }
-
-// console.log(poly.tVerts, poly.tPlanes);
-// console.log('seg2poly', arr);
- return arr;
-};
-
-// This one is less gross, but still gross.
-// TODO: Comment me!
-var circle2poly = function(circ, poly)
-{
- var planes = poly.tPlanes;
-
- var mini = 0;
- var min = vdot(planes[0].n, circ.tc) - planes[0].d - circ.r;
- for(var i=0; i 0){
- return NONE;
- } else if(dist > min) {
- min = dist;
- mini = i;
- }
- }
-
- var n = planes[mini].n;
-
- var verts = poly.tVerts;
- var len = verts.length;
- var mini2 = mini<<1;
-
- //var a = poly.tVerts[mini];
- //var b = poly.tVerts[(mini + 1)%poly.tVerts.length];
- var ax = verts[mini2];
- var ay = verts[mini2+1];
- var bx = verts[(mini2+2)%len];
- var by = verts[(mini2+3)%len];
-
- var dta = vcross2(n.x, n.y, ax, ay);
- var dtb = vcross2(n.x, n.y, bx, by);
- var dt = vcross(n, circ.tc);
-
- if(dt < dtb){
- var con = circle2circleQuery(circ.tc, new Vect(bx, by), circ.r, 0, con);
- return con ? [con] : NONE;
- } else if(dt < dta) {
- return [new Contact(
- vsub(circ.tc, vmult(n, circ.r + min/2)),
- vneg(n),
- min,
- 0
- )];
- } else {
- var con = circle2circleQuery(circ.tc, new Vect(ax, ay), circ.r, 0, con);
- return con ? [con] : NONE;
- }
-};
-
-// The javascripty way to do this would be either nested object or methods on the prototypes.
-//
-// However, the *fastest* way is the method below.
-// See: http://jsperf.com/dispatch
-
-// These are copied from the prototypes into the actual objects in the Shape constructor.
-CircleShape.prototype.collisionCode = 0;
-SegmentShape.prototype.collisionCode = 1;
-PolyShape.prototype.collisionCode = 2;
-
-CircleShape.prototype.collisionTable = [
- circle2circle,
- circle2segment,
- circle2poly
-];
-
-SegmentShape.prototype.collisionTable = [
- null,
- function(segA, segB) { return NONE; }, // seg2seg
- seg2poly
-];
-
-PolyShape.prototype.collisionTable = [
- null,
- null,
- poly2poly
-];
-
-var collideShapes = cp.collideShapes = function(a, b)
-{
- assert(a.collisionCode <= b.collisionCode, 'Collided shapes must be sorted by type');
- return a.collisionTable[b.collisionCode](a, b);
-};
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-var defaultCollisionHandler = new CollisionHandler();
-
-/// Basic Unit of Simulation in Chipmunk
-var Space = cp.Space = function() {
- this.stamp = 0;
- this.curr_dt = 0;
-
- this.bodies = [];
- this.rousedBodies = [];
- this.sleepingComponents = [];
-
- this.staticShapes = new BBTree(null);
- this.activeShapes = new BBTree(this.staticShapes);
-
- this.arbiters = [];
- this.contactBuffersHead = null;
- this.cachedArbiters = {};
- //this.pooledArbiters = [];
-
- this.constraints = [];
-
- this.locked = 0;
-
- this.collisionHandlers = {};
- this.defaultHandler = defaultCollisionHandler;
-
- this.postStepCallbacks = [];
-
- /// Number of iterations to use in the impulse solver to solve contacts.
- this.iterations = 10;
-
- /// Gravity to pass to rigid bodies when integrating velocity.
- this.gravity = vzero;
-
- /// Damping rate expressed as the fraction of velocity bodies retain each second.
- /// A value of 0.9 would mean that each body's velocity will drop 10% per second.
- /// The default value is 1.0, meaning no damping is applied.
- /// @note This damping value is different than those of cpDampedSpring and cpDampedRotarySpring.
- this.damping = 1;
-
- /// Speed threshold for a body to be considered idle.
- /// The default value of 0 means to let the space guess a good threshold based on gravity.
- this.idleSpeedThreshold = 0;
-
- /// Time a group of bodies must remain idle in order to fall asleep.
- /// Enabling sleeping also implicitly enables the the contact graph.
- /// The default value of Infinity disables the sleeping algorithm.
- this.sleepTimeThreshold = Infinity;
-
- /// Amount of encouraged penetration between colliding shapes..
- /// Used to reduce oscillating contacts and keep the collision cache warm.
- /// Defaults to 0.1. If you have poor simulation quality,
- /// increase this number as much as possible without allowing visible amounts of overlap.
- this.collisionSlop = 0.1;
-
- /// Determines how fast overlapping shapes are pushed apart.
- /// Expressed as a fraction of the error remaining after each second.
- /// Defaults to pow(1.0 - 0.1, 60.0) meaning that Chipmunk fixes 10% of overlap each frame at 60Hz.
- this.collisionBias = Math.pow(1 - 0.1, 60);
-
- /// Number of frames that contact information should persist.
- /// Defaults to 3. There is probably never a reason to change this value.
- this.collisionPersistence = 3;
-
- /// Rebuild the contact graph during each step. Must be enabled to use the cpBodyEachArbiter() function.
- /// Disabled by default for a small performance boost. Enabled implicitly when the sleeping feature is enabled.
- this.enableContactGraph = false;
-
- /// The designated static body for this space.
- /// You can modify this body, or replace it with your own static body.
- /// By default it points to a statically allocated cpBody in the cpSpace struct.
- this.staticBody = new Body(Infinity, Infinity);
- this.staticBody.nodeIdleTime = Infinity;
-
- // Cache the collideShapes callback function for the space.
- this.collideShapes = this.makeCollideShapes();
-};
-
-Space.prototype.getCurrentTimeStep = function() { return this.curr_dt; };
-
-Space.prototype.setIterations = function(iter) { this.iterations = iter; };
-
-/// returns true from inside a callback and objects cannot be added/removed.
-Space.prototype.isLocked = function()
-{
- return this.locked;
-};
-
-var assertSpaceUnlocked = function(space)
-{
- assert(!space.locked, "This addition/removal cannot be done safely during a call to cpSpaceStep() \
- or during a query. Put these calls into a post-step callback.");
-};
-
-// **** Collision handler function management
-
-/// Set a collision handler to be used whenever the two shapes with the given collision types collide.
-/// You can pass null for any function you don't want to implement.
-Space.prototype.addCollisionHandler = function(a, b, begin, preSolve, postSolve, separate)
-{
- assertSpaceUnlocked(this);
-
- // Remove any old function so the new one will get added.
- this.removeCollisionHandler(a, b);
-
- var handler = new CollisionHandler();
- handler.a = a;
- handler.b = b;
- if(begin) handler.begin = begin;
- if(preSolve) handler.preSolve = preSolve;
- if(postSolve) handler.postSolve = postSolve;
- if(separate) handler.separate = separate;
-
- this.collisionHandlers[hashPair(a, b)] = handler;
-};
-
-/// Unset a collision handler.
-Space.prototype.removeCollisionHandler = function(a, b)
-{
- assertSpaceUnlocked(this);
-
- delete this.collisionHandlers[hashPair(a, b)];
-};
-
-/// Set a default collision handler for this space.
-/// The default collision handler is invoked for each colliding pair of shapes
-/// that isn't explicitly handled by a specific collision handler.
-/// You can pass null for any function you don't want to implement.
-Space.prototype.setDefaultCollisionHandler = function(begin, preSolve, postSolve, separate)
-{
- assertSpaceUnlocked(this);
-
- var handler = new CollisionHandler();
- if(begin) handler.begin = begin;
- if(preSolve) handler.preSolve = preSolve;
- if(postSolve) handler.postSolve = postSolve;
- if(separate) handler.separate = separate;
-
- this.defaultHandler = handler;
-};
-
-Space.prototype.lookupHandler = function(a, b)
-{
- return this.collisionHandlers[hashPair(a, b)] || this.defaultHandler;
-};
-
-// **** Body, Shape, and Joint Management
-
-/// Add a collision shape to the simulation.
-/// If the shape is attached to a static body, it will be added as a static shape.
-Space.prototype.addShape = function(shape)
-{
- var body = shape.body;
- if(body.isStatic()) return this.addStaticShape(shape);
-
- assert(!shape.space, "This shape is already added to a space and cannot be added to another.");
- assertSpaceUnlocked(this);
-
- body.activate();
- body.addShape(shape);
-
- shape.update(body.p, body.rot);
- this.activeShapes.insert(shape, shape.hashid);
- shape.space = this;
-
- return shape;
-};
-
-/// Explicity add a shape as a static shape to the simulation.
-Space.prototype.addStaticShape = function(shape)
-{
- assert(!shape.space, "This shape is already added to a space and cannot be added to another.");
- assertSpaceUnlocked(this);
-
- var body = shape.body;
- body.addShape(shape);
-
- shape.update(body.p, body.rot);
- this.staticShapes.insert(shape, shape.hashid);
- shape.space = this;
-
- return shape;
-};
-
-/// Add a rigid body to the simulation.
-Space.prototype.addBody = function(body)
-{
- assert(!body.isStatic(), "Static bodies cannot be added to a space as they are not meant to be simulated.");
- assert(!body.space, "This body is already added to a space and cannot be added to another.");
- assertSpaceUnlocked(this);
-
- this.bodies.push(body);
- body.space = this;
-
- return body;
-};
-
-/// Add a constraint to the simulation.
-Space.prototype.addConstraint = function(constraint)
-{
- assert(!constraint.space, "This shape is already added to a space and cannot be added to another.");
- assertSpaceUnlocked(this);
-
- var a = constraint.a, b = constraint.b;
-
- a.activate();
- b.activate();
- this.constraints.push(constraint);
-
- // Push onto the heads of the bodies' constraint lists
- constraint.next_a = a.constraintList; a.constraintList = constraint;
- constraint.next_b = b.constraintList; b.constraintList = constraint;
- constraint.space = this;
-
- return constraint;
-};
-
-Space.prototype.filterArbiters = function(body, filter)
-{
- for (var hash in this.cachedArbiters)
- {
- var arb = this.cachedArbiters[hash];
-
- // Match on the filter shape, or if it's null the filter body
- if(
- (body === arb.body_a && (filter === arb.a || filter === null)) ||
- (body === arb.body_b && (filter === arb.b || filter === null))
- ){
- // Call separate when removing shapes.
- if(filter && arb.state !== 'cached') arb.callSeparate(this);
-
- arb.unthread();
-
- deleteObjFromList(this.arbiters, arb);
- //this.pooledArbiters.push(arb);
-
- delete this.cachedArbiters[hash];
- }
- }
-};
-
-/// Remove a collision shape from the simulation.
-Space.prototype.removeShape = function(shape)
-{
- var body = shape.body;
- if(body.isStatic()){
- this.removeStaticShape(shape);
- } else {
- assert(this.containsShape(shape),
- "Cannot remove a shape that was not added to the space. (Removed twice maybe?)");
- assertSpaceUnlocked(this);
-
- body.activate();
- body.removeShape(shape);
- this.filterArbiters(body, shape);
- this.activeShapes.remove(shape, shape.hashid);
- shape.space = null;
- }
-};
-
-/// Remove a collision shape added using addStaticShape() from the simulation.
-Space.prototype.removeStaticShape = function(shape)
-{
- assert(this.containsShape(shape),
- "Cannot remove a static or sleeping shape that was not added to the space. (Removed twice maybe?)");
- assertSpaceUnlocked(this);
-
- var body = shape.body;
- if(body.isStatic()) body.activateStatic(shape);
- body.removeShape(shape);
- this.filterArbiters(body, shape);
- this.staticShapes.remove(shape, shape.hashid);
- shape.space = null;
-};
-
-/// Remove a rigid body from the simulation.
-Space.prototype.removeBody = function(body)
-{
- assert(this.containsBody(body),
- "Cannot remove a body that was not added to the space. (Removed twice maybe?)");
- assertSpaceUnlocked(this);
-
- body.activate();
-// this.filterArbiters(body, null);
- deleteObjFromList(this.bodies, body);
- body.space = null;
-};
-
-/// Remove a constraint from the simulation.
-Space.prototype.removeConstraint = function(constraint)
-{
- assert(this.containsConstraint(constraint),
- "Cannot remove a constraint that was not added to the space. (Removed twice maybe?)");
- assertSpaceUnlocked(this);
-
- constraint.a.activate();
- constraint.b.activate();
- deleteObjFromList(this.constraints, constraint);
-
- constraint.a.removeConstraint(constraint);
- constraint.b.removeConstraint(constraint);
- constraint.space = null;
-};
-
-/// Test if a collision shape has been added to the space.
-Space.prototype.containsShape = function(shape)
-{
- return (shape.space === this);
-};
-
-/// Test if a rigid body has been added to the space.
-Space.prototype.containsBody = function(body)
-{
- return (body.space == this);
-};
-
-/// Test if a constraint has been added to the space.
-Space.prototype.containsConstraint = function(constraint)
-{
- return (constraint.space == this);
-};
-
-Space.prototype.uncacheArbiter = function(arb)
-{
- delete this.cachedArbiters[hashPair(arb.a.hashid, arb.b.hashid)];
- deleteObjFromList(this.arbiters, arb);
-};
-
-
-// **** Iteration
-
-/// Call @c func for each body in the space.
-Space.prototype.eachBody = function(func)
-{
- this.lock(); {
- var bodies = this.bodies;
-
- for(var i=0; i keThreshold ? 0 : body.nodeIdleTime + dt);
- }
- }
-
- // Awaken any sleeping bodies found and then push arbiters to the bodies' lists.
- var arbiters = this.arbiters;
- for(var i=0, count=arbiters.length; i= 0, "Internal Error: Space lock underflow.");
-
- if(this.locked === 0 && runPostStep){
- var waking = this.rousedBodies;
- for(var i=0; i this.collisionPersistence){
- // The tail buffer is available, rotate the ring
- var tail = head.next;
- tail.stamp = stamp;
- tail.contacts.length = 0;
- this.contactBuffersHead = tail;
- } else {
- // Allocate a new buffer and push it into the ring
- var buffer = new ContactBuffer(stamp, head);
- this.contactBuffersHead = head.next = buffer;
- }
-};
-
-cpContact *
-cpContactBufferGetArray(cpSpace *space)
-{
- if(space.contactBuffersHead.numContacts + CP_MAX_CONTACTS_PER_ARBITER > CP_CONTACTS_BUFFER_SIZE){
- // contact buffer could overflow on the next collision, push a fresh one.
- space.pushFreshContactBuffer();
- }
-
- cpContactBufferHeader *head = space.contactBuffersHead;
- return ((cpContactBuffer *)head)->contacts + head.numContacts;
-}
-
-void
-cpSpacePushContacts(cpSpace *space, int count)
-{
- cpAssertHard(count <= CP_MAX_CONTACTS_PER_ARBITER, "Internal Error: Contact buffer overflow!");
- space.contactBuffersHead.numContacts += count;
-}
-
-static void
-cpSpacePopContacts(cpSpace *space, int count){
- space.contactBuffersHead.numContacts -= count;
-}
-*/
-
-// **** Collision Detection Functions
-
-/* Use this to re-enable object pools.
-static void *
-cpSpaceArbiterSetTrans(cpShape **shapes, cpSpace *space)
-{
- if(space.pooledArbiters.num == 0){
- // arbiter pool is exhausted, make more
- int count = CP_BUFFER_BYTES/sizeof(cpArbiter);
- cpAssertHard(count, "Internal Error: Buffer size too small.");
-
- cpArbiter *buffer = (cpArbiter *)cpcalloc(1, CP_BUFFER_BYTES);
- cpArrayPush(space.allocatedBuffers, buffer);
-
- for(int i=0; i b.collisionCode){
- var temp = a;
- a = b;
- b = temp;
- }
-
- // Narrow-phase collision detection.
- //cpContact *contacts = cpContactBufferGetArray(space);
- //int numContacts = cpCollideShapes(a, b, contacts);
- var contacts = collideShapes(a, b);
- if(contacts.length === 0) return; // Shapes are not colliding.
- //cpSpacePushContacts(space, numContacts);
-
- // Get an arbiter from space.arbiterSet for the two shapes.
- // This is where the persistant contact magic comes from.
- var arbHash = hashPair(a.hashid, b.hashid);
- var arb = space.cachedArbiters[arbHash];
- if (!arb){
- arb = space.cachedArbiters[arbHash] = new Arbiter(a, b);
- }
-
- arb.update(contacts, handler, a, b);
-
- // Call the begin function first if it's the first step
- if(arb.state == 'first coll' && !handler.begin(arb, space)){
- arb.ignore(); // permanently ignore the collision until separation
- }
-
- if(
- // Ignore the arbiter if it has been flagged
- (arb.state !== 'ignore') &&
- // Call preSolve
- handler.preSolve(arb, space) &&
- // Process, but don't add collisions for sensors.
- !sensor
- ){
- space.arbiters.push(arb);
- } else {
- //cpSpacePopContacts(space, numContacts);
-
- arb.contacts = null;
-
- // Normally arbiters are set as used after calling the post-solve callback.
- // However, post-solve callbacks are not called for sensors or arbiters rejected from pre-solve.
- if(arb.state !== 'ignore') arb.state = 'normal';
- }
-
- // Time stamp the arbiter so we know it was used recently.
- arb.stamp = space.stamp;
- };
-};
-
-// Hashset filter func to throw away old arbiters.
-Space.prototype.arbiterSetFilter = function(arb)
-{
- var ticks = this.stamp - arb.stamp;
-
- var a = arb.body_a, b = arb.body_b;
-
- // TODO should make an arbiter state for this so it doesn't require filtering arbiters for
- // dangling body pointers on body removal.
- // Preserve arbiters on sensors and rejected arbiters for sleeping objects.
- // This prevents errant separate callbacks from happenening.
- if(
- (a.isStatic() || a.isSleeping()) &&
- (b.isStatic() || b.isSleeping())
- ){
- return true;
- }
-
- // Arbiter was used last frame, but not this one
- if(ticks >= 1 && arb.state != 'cached'){
- arb.callSeparate(this);
- arb.state = 'cached';
- }
-
- if(ticks >= this.collisionPersistence){
- arb.contacts = null;
-
- //cpArrayPush(this.pooledArbiters, arb);
- return false;
- }
-
- return true;
-};
-
-// **** All Important cpSpaceStep() Function
-
-var updateFunc = function(shape)
-{
- var body = shape.body;
- shape.update(body.p, body.rot);
-};
-
-/// Step the space forward in time by @c dt.
-Space.prototype.step = function(dt)
-{
- // don't step if the timestep is 0!
- if(dt === 0) return;
-
- assert(vzero.x === 0 && vzero.y === 0, "vzero is invalid");
-
- this.stamp++;
-
- var prev_dt = this.curr_dt;
- this.curr_dt = dt;
-
- var i;
- var j;
- var hash;
- var bodies = this.bodies;
- var constraints = this.constraints;
- var arbiters = this.arbiters;
-
- // Reset and empty the arbiter lists.
- for(i=0; imaxForce*(dt))
-
-// a and b are bodies.
-var relative_velocity = function(a, b, r1, r2){
- //var v1_sum = vadd(a.v, vmult(vperp(r1), a.w));
- var v1_sumx = a.vx + (-r1.y) * a.w;
- var v1_sumy = a.vy + ( r1.x) * a.w;
-
- //var v2_sum = vadd(b.v, vmult(vperp(r2), b.w));
- var v2_sumx = b.vx + (-r2.y) * b.w;
- var v2_sumy = b.vy + ( r2.x) * b.w;
-
-// return vsub(v2_sum, v1_sum);
- return new Vect(v2_sumx - v1_sumx, v2_sumy - v1_sumy);
-};
-
-var normal_relative_velocity = function(a, b, r1, r2, n){
- //return vdot(relative_velocity(a, b, r1, r2), n);
- var v1_sumx = a.vx + (-r1.y) * a.w;
- var v1_sumy = a.vy + ( r1.x) * a.w;
- var v2_sumx = b.vx + (-r2.y) * b.w;
- var v2_sumy = b.vy + ( r2.x) * b.w;
-
- return vdot2(v2_sumx - v1_sumx, v2_sumy - v1_sumy, n.x, n.y);
-};
-
-/*
-var apply_impulse = function(body, j, r){
- body.v = vadd(body.v, vmult(j, body.m_inv));
- body.w += body.i_inv*vcross(r, j);
-};
-
-var apply_impulses = function(a, b, r1, r2, j)
-{
- apply_impulse(a, vneg(j), r1);
- apply_impulse(b, j, r2);
-};
-*/
-
-var apply_impulse = function(body, jx, jy, r){
-// body.v = body.v.add(vmult(j, body.m_inv));
- body.vx += jx * body.m_inv;
- body.vy += jy * body.m_inv;
-// body.w += body.i_inv*vcross(r, j);
- body.w += body.i_inv*(r.x*jy - r.y*jx);
-};
-
-var apply_impulses = function(a, b, r1, r2, jx, jy)
-{
- apply_impulse(a, -jx, -jy, r1);
- apply_impulse(b, jx, jy, r2);
-};
-
-var apply_bias_impulse = function(body, jx, jy, r)
-{
- //body.v_bias = vadd(body.v_bias, vmult(j, body.m_inv));
- body.v_biasx += jx * body.m_inv;
- body.v_biasy += jy * body.m_inv;
- body.w_bias += body.i_inv*vcross2(r.x, r.y, jx, jy);
-};
-
-/*
-var apply_bias_impulses = function(a, b, r1, r2, j)
-{
- apply_bias_impulse(a, vneg(j), r1);
- apply_bias_impulse(b, j, r2);
-};*/
-
-var k_scalar_body = function(body, r, n)
-{
- var rcn = vcross(r, n);
- return body.m_inv + body.i_inv*rcn*rcn;
-};
-
-var k_scalar = function(a, b, r1, r2, n)
-{
- var value = k_scalar_body(a, r1, n) + k_scalar_body(b, r2, n);
- assertSoft(value !== 0, "Unsolvable collision or constraint.");
-
- return value;
-};
-
-// k1 and k2 are modified by the function to contain the outputs.
-var k_tensor = function(a, b, r1, r2, k1, k2)
-{
- // calculate mass matrix
- // If I wasn't lazy and wrote a proper matrix class, this wouldn't be so gross...
- var k11, k12, k21, k22;
- var m_sum = a.m_inv + b.m_inv;
-
- // start with I*m_sum
- k11 = m_sum; k12 = 0;
- k21 = 0; k22 = m_sum;
-
- // add the influence from r1
- var a_i_inv = a.i_inv;
- var r1xsq = r1.x * r1.x * a_i_inv;
- var r1ysq = r1.y * r1.y * a_i_inv;
- var r1nxy = -r1.x * r1.y * a_i_inv;
- k11 += r1ysq; k12 += r1nxy;
- k21 += r1nxy; k22 += r1xsq;
-
- // add the influnce from r2
- var b_i_inv = b.i_inv;
- var r2xsq = r2.x * r2.x * b_i_inv;
- var r2ysq = r2.y * r2.y * b_i_inv;
- var r2nxy = -r2.x * r2.y * b_i_inv;
- k11 += r2ysq; k12 += r2nxy;
- k21 += r2nxy; k22 += r2xsq;
-
- // invert
- var determinant = k11*k22 - k12*k21;
- assertSoft(determinant !== 0, "Unsolvable constraint.");
-
- var det_inv = 1/determinant;
-
- k1.x = k22*det_inv; k1.y = -k12*det_inv;
- k2.x = -k21*det_inv; k2.y = k11*det_inv;
-};
-
-var mult_k = function(vr, k1, k2)
-{
- return new Vect(vdot(vr, k1), vdot(vr, k2));
-};
-
-var bias_coef = function(errorBias, dt)
-{
- return 1 - Math.pow(errorBias, dt);
-};
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-// TODO: Comment me!
-
-// a and b are bodies that the constraint applies to.
-var Constraint = cp.Constraint = function(a, b)
-{
- /// The first body connected to this constraint.
- this.a = a;
- /// The second body connected to this constraint.
- this.b = b;
-
- this.space = null;
-
- this.next_a = null;
- this.next_b = null;
-
- /// The maximum force that this constraint is allowed to use.
- this.maxForce = Infinity;
- /// The rate at which joint error is corrected.
- /// Defaults to pow(1 - 0.1, 60) meaning that it will
- /// correct 10% of the error every 1/60th of a second.
- this.errorBias = Math.pow(1 - 0.1, 60);
- /// The maximum rate at which joint error is corrected.
- this.maxBias = Infinity;
-};
-
-Constraint.prototype.activateBodies = function()
-{
- if(this.a) this.a.activate();
- if(this.b) this.b.activate();
-};
-
-/// These methods are overridden by the constraint itself.
-Constraint.prototype.preStep = function(dt) {};
-Constraint.prototype.applyCachedImpulse = function(dt_coef) {};
-Constraint.prototype.applyImpulse = function() {};
-Constraint.prototype.getImpulse = function() { return 0; };
-
-/// Function called before the solver runs. This can be overridden by the user
-/// to customize the constraint.
-/// Animate your joint anchors, update your motor torque, etc.
-Constraint.prototype.preSolve = function(space) {};
-
-/// Function called after the solver runs. This can be overridden by the user
-/// to customize the constraint.
-/// Use the applied impulse to perform effects like breakable joints.
-Constraint.prototype.postSolve = function(space) {};
-
-Constraint.prototype.next = function(body)
-{
- return (this.a === body ? this.next_a : this.next_b);
-};
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-var PinJoint = cp.PinJoint = function(a, b, anchr1, anchr2)
-{
- Constraint.call(this, a, b);
-
- this.anchr1 = anchr1;
- this.anchr2 = anchr2;
-
- // STATIC_BODY_CHECK
- var p1 = (a ? vadd(a.p, vrotate(anchr1, a.rot)) : anchr1);
- var p2 = (b ? vadd(b.p, vrotate(anchr2, b.rot)) : anchr2);
- this.dist = vlength(vsub(p2, p1));
-
- assertSoft(this.dist > 0, "You created a 0 length pin joint. A pivot joint will be much more stable.");
-
- this.r1 = this.r2 = null;
- this.n = null;
- this.nMass = 0;
-
- this.jnAcc = this.jnMax = 0;
- this.bias = 0;
-};
-
-PinJoint.prototype = Object.create(Constraint.prototype);
-
-PinJoint.prototype.preStep = function(dt)
-{
- var a = this.a;
- var b = this.b;
-
- this.r1 = vrotate(this.anchr1, a.rot);
- this.r2 = vrotate(this.anchr2, b.rot);
-
- var delta = vsub(vadd(b.p, this.r2), vadd(a.p, this.r1));
- var dist = vlength(delta);
- this.n = vmult(delta, 1/(dist ? dist : Infinity));
-
- // calculate mass normal
- this.nMass = 1/k_scalar(a, b, this.r1, this.r2, this.n);
-
- // calculate bias velocity
- var maxBias = this.maxBias;
- this.bias = clamp(-bias_coef(this.errorBias, dt)*(dist - this.dist)/dt, -maxBias, maxBias);
-
- // compute max impulse
- this.jnMax = this.maxForce * dt;
-};
-
-PinJoint.prototype.applyCachedImpulse = function(dt_coef)
-{
- var j = vmult(this.n, this.jnAcc*dt_coef);
- apply_impulses(this.a, this.b, this.r1, this.r2, j.x, j.y);
-};
-
-PinJoint.prototype.applyImpulse = function()
-{
- var a = this.a;
- var b = this.b;
- var n = this.n;
-
- // compute relative velocity
- var vrn = normal_relative_velocity(a, b, this.r1, this.r2, n);
-
- // compute normal impulse
- var jn = (this.bias - vrn)*this.nMass;
- var jnOld = this.jnAcc;
- this.jnAcc = clamp(jnOld + jn, -this.jnMax, this.jnMax);
- jn = this.jnAcc - jnOld;
-
- // apply impulse
- apply_impulses(a, b, this.r1, this.r2, n.x*jn, n.y*jn);
-};
-
-PinJoint.prototype.getImpulse = function()
-{
- return Math.abs(this.jnAcc);
-};
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-var SlideJoint = cp.SlideJoint = function(a, b, anchr1, anchr2, min, max)
-{
- Constraint.call(this, a, b);
-
- this.anchr1 = anchr1;
- this.anchr2 = anchr2;
- this.min = min;
- this.max = max;
-
- this.r1 = this.r2 = this.n = null;
- this.nMass = 0;
-
- this.jnAcc = this.jnMax = 0;
- this.bias = 0;
-};
-
-SlideJoint.prototype = Object.create(Constraint.prototype);
-
-SlideJoint.prototype.preStep = function(dt)
-{
- var a = this.a;
- var b = this.b;
-
- this.r1 = vrotate(this.anchr1, a.rot);
- this.r2 = vrotate(this.anchr2, b.rot);
-
- var delta = vsub(vadd(b.p, this.r2), vadd(a.p, this.r1));
- var dist = vlength(delta);
- var pdist = 0;
- if(dist > this.max) {
- pdist = dist - this.max;
- this.n = vnormalize_safe(delta);
- } else if(dist < this.min) {
- pdist = this.min - dist;
- this.n = vneg(vnormalize_safe(delta));
- } else {
- this.n = vzero;
- this.jnAcc = 0;
- }
-
- // calculate mass normal
- this.nMass = 1/k_scalar(a, b, this.r1, this.r2, this.n);
-
- // calculate bias velocity
- var maxBias = this.maxBias;
- this.bias = clamp(-bias_coef(this.errorBias, dt)*pdist/dt, -maxBias, maxBias);
-
- // compute max impulse
- this.jnMax = this.maxForce * dt;
-};
-
-SlideJoint.prototype.applyCachedImpulse = function(dt_coef)
-{
- var jn = this.jnAcc * dt_coef;
- apply_impulses(this.a, this.b, this.r1, this.r2, this.n.x * jn, this.n.y * jn);
-};
-
-SlideJoint.prototype.applyImpulse = function()
-{
- if(this.n.x === 0 && this.n.y === 0) return; // early exit
-
- var a = this.a;
- var b = this.b;
-
- var n = this.n;
- var r1 = this.r1;
- var r2 = this.r2;
-
- // compute relative velocity
- var vr = relative_velocity(a, b, r1, r2);
- var vrn = vdot(vr, n);
-
- // compute normal impulse
- var jn = (this.bias - vrn)*this.nMass;
- var jnOld = this.jnAcc;
- this.jnAcc = clamp(jnOld + jn, -this.jnMax, 0);
- jn = this.jnAcc - jnOld;
-
- // apply impulse
- apply_impulses(a, b, this.r1, this.r2, n.x * jn, n.y * jn);
-};
-
-SlideJoint.prototype.getImpulse = function()
-{
- return Math.abs(this.jnAcc);
-};
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-// Pivot joints can also be created with (a, b, pivot);
-var PivotJoint = cp.PivotJoint = function(a, b, anchr1, anchr2)
-{
- Constraint.call(this, a, b);
-
- if(typeof anchr2 === 'undefined') {
- var pivot = anchr1;
-
- anchr1 = (a ? a.world2Local(pivot) : pivot);
- anchr2 = (b ? b.world2Local(pivot) : pivot);
- }
-
- this.anchr1 = anchr1;
- this.anchr2 = anchr2;
-
- this.r1 = this.r2 = vzero;
-
- this.k1 = new Vect(0,0); this.k2 = new Vect(0,0);
-
- this.jAcc = vzero;
-
- this.jMaxLen = 0;
- this.bias = vzero;
-};
-
-PivotJoint.prototype = Object.create(Constraint.prototype);
-
-PivotJoint.prototype.preStep = function(dt)
-{
- var a = this.a;
- var b = this.b;
-
- this.r1 = vrotate(this.anchr1, a.rot);
- this.r2 = vrotate(this.anchr2, b.rot);
-
- // Calculate mass tensor. Result is stored into this.k1 & this.k2.
- k_tensor(a, b, this.r1, this.r2, this.k1, this.k2);
-
- // compute max impulse
- this.jMaxLen = this.maxForce * dt;
-
- // calculate bias velocity
- var delta = vsub(vadd(b.p, this.r2), vadd(a.p, this.r1));
- this.bias = vclamp(vmult(delta, -bias_coef(this.errorBias, dt)/dt), this.maxBias);
-};
-
-PivotJoint.prototype.applyCachedImpulse = function(dt_coef)
-{
- apply_impulses(this.a, this.b, this.r1, this.r2, this.jAcc.x * dt_coef, this.jAcc.y * dt_coef);
-};
-
-PivotJoint.prototype.applyImpulse = function()
-{
- var a = this.a;
- var b = this.b;
-
- var r1 = this.r1;
- var r2 = this.r2;
-
- // compute relative velocity
- var vr = relative_velocity(a, b, r1, r2);
-
- // compute normal impulse
- var j = mult_k(vsub(this.bias, vr), this.k1, this.k2);
- var jOld = this.jAcc;
- this.jAcc = vclamp(vadd(this.jAcc, j), this.jMaxLen);
-
- // apply impulse
- apply_impulses(a, b, this.r1, this.r2, this.jAcc.x - jOld.x, this.jAcc.y - jOld.y);
-};
-
-PivotJoint.prototype.getImpulse = function()
-{
- return vlength(this.jAcc);
-};
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-var GrooveJoint = cp.GrooveJoint = function(a, b, groove_a, groove_b, anchr2)
-{
- Constraint.call(this, a, b);
-
- this.grv_a = groove_a;
- this.grv_b = groove_b;
- this.grv_n = vperp(vnormalize(vsub(groove_b, groove_a)));
- this.anchr2 = anchr2;
-
- this.grv_tn = null;
- this.clamp = 0;
- this.r1 = this.r2 = null;
-
- this.k1 = new Vect(0,0);
- this.k2 = new Vect(0,0);
-
- this.jAcc = vzero;
- this.jMaxLen = 0;
- this.bias = null;
-};
-
-GrooveJoint.prototype = Object.create(Constraint.prototype);
-
-GrooveJoint.prototype.preStep = function(dt)
-{
- var a = this.a;
- var b = this.b;
-
- // calculate endpoints in worldspace
- var ta = a.local2World(this.grv_a);
- var tb = a.local2World(this.grv_b);
-
- // calculate axis
- var n = vrotate(this.grv_n, a.rot);
- var d = vdot(ta, n);
-
- this.grv_tn = n;
- this.r2 = vrotate(this.anchr2, b.rot);
-
- // calculate tangential distance along the axis of r2
- var td = vcross(vadd(b.p, this.r2), n);
- // calculate clamping factor and r2
- if(td <= vcross(ta, n)){
- this.clamp = 1;
- this.r1 = vsub(ta, a.p);
- } else if(td >= vcross(tb, n)){
- this.clamp = -1;
- this.r1 = vsub(tb, a.p);
- } else {
- this.clamp = 0;
- this.r1 = vsub(vadd(vmult(vperp(n), -td), vmult(n, d)), a.p);
- }
-
- // Calculate mass tensor
- k_tensor(a, b, this.r1, this.r2, this.k1, this.k2);
-
- // compute max impulse
- this.jMaxLen = this.maxForce * dt;
-
- // calculate bias velocity
- var delta = vsub(vadd(b.p, this.r2), vadd(a.p, this.r1));
- this.bias = vclamp(vmult(delta, -bias_coef(this.errorBias, dt)/dt), this.maxBias);
-};
-
-GrooveJoint.prototype.applyCachedImpulse = function(dt_coef)
-{
- apply_impulses(this.a, this.b, this.r1, this.r2, this.jAcc.x * dt_coef, this.jAcc.y * dt_coef);
-};
-
-GrooveJoint.prototype.grooveConstrain = function(j){
- var n = this.grv_tn;
- var jClamp = (this.clamp*vcross(j, n) > 0) ? j : vproject(j, n);
- return vclamp(jClamp, this.jMaxLen);
-};
-
-GrooveJoint.prototype.applyImpulse = function()
-{
- var a = this.a;
- var b = this.b;
-
- var r1 = this.r1;
- var r2 = this.r2;
-
- // compute impulse
- var vr = relative_velocity(a, b, r1, r2);
-
- var j = mult_k(vsub(this.bias, vr), this.k1, this.k2);
- var jOld = this.jAcc;
- this.jAcc = this.grooveConstrain(vadd(jOld, j));
-
- // apply impulse
- apply_impulses(a, b, this.r1, this.r2, this.jAcc.x - jOld.x, this.jAcc.y - jOld.y);
-};
-
-GrooveJoint.prototype.getImpulse = function()
-{
- return vlength(this.jAcc);
-};
-
-GrooveJoint.prototype.setGrooveA = function(value)
-{
- this.grv_a = value;
- this.grv_n = vperp(vnormalize(vsub(this.grv_b, value)));
-
- this.activateBodies();
-};
-
-GrooveJoint.prototype.setGrooveB = function(value)
-{
- this.grv_b = value;
- this.grv_n = vperp(vnormalize(vsub(value, this.grv_a)));
-
- this.activateBodies();
-};
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-var defaultSpringForce = function(spring, dist){
- return (spring.restLength - dist)*spring.stiffness;
-};
-
-var DampedSpring = cp.DampedSpring = function(a, b, anchr1, anchr2, restLength, stiffness, damping)
-{
- Constraint.call(this, a, b);
-
- this.anchr1 = anchr1;
- this.anchr2 = anchr2;
-
- this.restLength = restLength;
- this.stiffness = stiffness;
- this.damping = damping;
- this.springForceFunc = defaultSpringForce;
-
- this.target_vrn = this.v_coef = 0;
-
- this.r1 = this.r2 = null;
- this.nMass = 0;
- this.n = null;
-};
-
-DampedSpring.prototype = Object.create(Constraint.prototype);
-
-DampedSpring.prototype.preStep = function(dt)
-{
- var a = this.a;
- var b = this.b;
-
- this.r1 = vrotate(this.anchr1, a.rot);
- this.r2 = vrotate(this.anchr2, b.rot);
-
- var delta = vsub(vadd(b.p, this.r2), vadd(a.p, this.r1));
- var dist = vlength(delta);
- this.n = vmult(delta, 1/(dist ? dist : Infinity));
-
- var k = k_scalar(a, b, this.r1, this.r2, this.n);
- assertSoft(k !== 0, "Unsolvable this.");
- this.nMass = 1/k;
-
- this.target_vrn = 0;
- this.v_coef = 1 - Math.exp(-this.damping*dt*k);
-
- // apply this force
- var f_spring = this.springForceFunc(this, dist);
- apply_impulses(a, b, this.r1, this.r2, this.n.x * f_spring * dt, this.n.y * f_spring * dt);
-};
-
-DampedSpring.prototype.applyCachedImpulse = function(dt_coef){};
-
-DampedSpring.prototype.applyImpulse = function()
-{
- var a = this.a;
- var b = this.b;
-
- var n = this.n;
- var r1 = this.r1;
- var r2 = this.r2;
-
- // compute relative velocity
- var vrn = normal_relative_velocity(a, b, r1, r2, n);
-
- // compute velocity loss from drag
- var v_damp = (this.target_vrn - vrn)*this.v_coef;
- this.target_vrn = vrn + v_damp;
-
- v_damp *= this.nMass;
- apply_impulses(a, b, this.r1, this.r2, this.n.x * v_damp, this.n.y * v_damp);
-};
-
-DampedSpring.prototype.getImpulse = function()
-{
- return 0;
-};
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-var defaultSpringTorque = function(spring, relativeAngle){
- return (relativeAngle - spring.restAngle)*spring.stiffness;
-}
-
-var DampedRotarySpring = cp.DampedRotarySpring = function(a, b, restAngle, stiffness, damping)
-{
- Constraint.call(this, a, b);
-
- this.restAngle = restAngle;
- this.stiffness = stiffness;
- this.damping = damping;
- this.springTorqueFunc = defaultSpringTorque;
-
- this.target_wrn = 0;
- this.w_coef = 0;
- this.iSum = 0;
-};
-
-DampedRotarySpring.prototype = Object.create(Constraint.prototype);
-
-DampedRotarySpring.prototype.preStep = function(dt)
-{
- var a = this.a;
- var b = this.b;
-
- var moment = a.i_inv + b.i_inv;
- assertSoft(moment !== 0, "Unsolvable spring.");
- this.iSum = 1/moment;
-
- this.w_coef = 1 - Math.exp(-this.damping*dt*moment);
- this.target_wrn = 0;
-
- // apply this torque
- var j_spring = this.springTorqueFunc(this, a.a - b.a)*dt;
- a.w -= j_spring*a.i_inv;
- b.w += j_spring*b.i_inv;
-};
-
-// DampedRotarySpring.prototype.applyCachedImpulse = function(dt_coef){};
-
-DampedRotarySpring.prototype.applyImpulse = function()
-{
- var a = this.a;
- var b = this.b;
-
- // compute relative velocity
- var wrn = a.w - b.w;//normal_relative_velocity(a, b, r1, r2, n) - this.target_vrn;
-
- // compute velocity loss from drag
- // not 100% certain spring is derived correctly, though it makes sense
- var w_damp = (this.target_wrn - wrn)*this.w_coef;
- this.target_wrn = wrn + w_damp;
-
- //apply_impulses(a, b, this.r1, this.r2, vmult(this.n, v_damp*this.nMass));
- var j_damp = w_damp*this.iSum;
- a.w += j_damp*a.i_inv;
- b.w -= j_damp*b.i_inv;
-};
-
-// DampedRotarySpring.prototype.getImpulse = function(){ return 0; };
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-var RotaryLimitJoint = cp.RotaryLimitJoint = function(a, b, min, max)
-{
- Constraint.call(this, a, b);
-
- this.min = min;
- this.max = max;
-
- this.jAcc = 0;
-
- this.iSum = this.bias = this.jMax = 0;
-};
-
-RotaryLimitJoint.prototype = Object.create(Constraint.prototype);
-
-RotaryLimitJoint.prototype.preStep = function(dt)
-{
- var a = this.a;
- var b = this.b;
-
- var dist = b.a - a.a;
- var pdist = 0;
- if(dist > this.max) {
- pdist = this.max - dist;
- } else if(dist < this.min) {
- pdist = this.min - dist;
- }
-
- // calculate moment of inertia coefficient.
- this.iSum = 1/(1/a.i + 1/b.i);
-
- // calculate bias velocity
- var maxBias = this.maxBias;
- this.bias = clamp(-bias_coef(this.errorBias, dt)*pdist/dt, -maxBias, maxBias);
-
- // compute max impulse
- this.jMax = this.maxForce * dt;
-
- // If the bias is 0, the joint is not at a limit. Reset the impulse.
- if(!this.bias) this.jAcc = 0;
-};
-
-RotaryLimitJoint.prototype.applyCachedImpulse = function(dt_coef)
-{
- var a = this.a;
- var b = this.b;
-
- var j = this.jAcc*dt_coef;
- a.w -= j*a.i_inv;
- b.w += j*b.i_inv;
-};
-
-RotaryLimitJoint.prototype.applyImpulse = function()
-{
- if(!this.bias) return; // early exit
-
- var a = this.a;
- var b = this.b;
-
- // compute relative rotational velocity
- var wr = b.w - a.w;
-
- // compute normal impulse
- var j = -(this.bias + wr)*this.iSum;
- var jOld = this.jAcc;
- if(this.bias < 0){
- this.jAcc = clamp(jOld + j, 0, this.jMax);
- } else {
- this.jAcc = clamp(jOld + j, -this.jMax, 0);
- }
- j = this.jAcc - jOld;
-
- // apply impulse
- a.w -= j*a.i_inv;
- b.w += j*b.i_inv;
-};
-
-RotaryLimitJoint.prototype.getImpulse = function()
-{
- return Math.abs(joint.jAcc);
-};
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-var RatchetJoint = cp.RatchetJoint = function(a, b, phase, ratchet)
-{
- Constraint.call(this, a, b);
-
- this.angle = 0;
- this.phase = phase;
- this.ratchet = ratchet;
-
- // STATIC_BODY_CHECK
- this.angle = (b ? b.a : 0) - (a ? a.a : 0);
-
- this.iSum = this.bias = this.jAcc = this.jMax = 0;
-};
-
-RatchetJoint.prototype = Object.create(Constraint.prototype);
-
-RatchetJoint.prototype.preStep = function(dt)
-{
- var a = this.a;
- var b = this.b;
-
- var angle = this.angle;
- var phase = this.phase;
- var ratchet = this.ratchet;
-
- var delta = b.a - a.a;
- var diff = angle - delta;
- var pdist = 0;
-
- if(diff*ratchet > 0){
- pdist = diff;
- } else {
- this.angle = Math.floor((delta - phase)/ratchet)*ratchet + phase;
- }
-
- // calculate moment of inertia coefficient.
- this.iSum = 1/(a.i_inv + b.i_inv);
-
- // calculate bias velocity
- var maxBias = this.maxBias;
- this.bias = clamp(-bias_coef(this.errorBias, dt)*pdist/dt, -maxBias, maxBias);
-
- // compute max impulse
- this.jMax = this.maxForce * dt;
-
- // If the bias is 0, the joint is not at a limit. Reset the impulse.
- if(!this.bias) this.jAcc = 0;
-};
-
-RatchetJoint.prototype.applyCachedImpulse = function(dt_coef)
-{
- var a = this.a;
- var b = this.b;
-
- var j = this.jAcc*dt_coef;
- a.w -= j*a.i_inv;
- b.w += j*b.i_inv;
-};
-
-RatchetJoint.prototype.applyImpulse = function()
-{
- if(!this.bias) return; // early exit
-
- var a = this.a;
- var b = this.b;
-
- // compute relative rotational velocity
- var wr = b.w - a.w;
- var ratchet = this.ratchet;
-
- // compute normal impulse
- var j = -(this.bias + wr)*this.iSum;
- var jOld = this.jAcc;
- this.jAcc = clamp((jOld + j)*ratchet, 0, this.jMax*Math.abs(ratchet))/ratchet;
- j = this.jAcc - jOld;
-
- // apply impulse
- a.w -= j*a.i_inv;
- b.w += j*b.i_inv;
-};
-
-RatchetJoint.prototype.getImpulse = function(joint)
-{
- return Math.abs(joint.jAcc);
-};
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-var GearJoint = cp.GearJoint = function(a, b, phase, ratio)
-{
- Constraint.call(this, a, b);
-
- this.phase = phase;
- this.ratio = ratio;
- this.ratio_inv = 1/ratio;
-
- this.jAcc = 0;
-
- this.iSum = this.bias = this.jMax = 0;
-};
-
-GearJoint.prototype = Object.create(Constraint.prototype);
-
-GearJoint.prototype.preStep = function(dt)
-{
- var a = this.a;
- var b = this.b;
-
- // calculate moment of inertia coefficient.
- this.iSum = 1/(a.i_inv*this.ratio_inv + this.ratio*b.i_inv);
-
- // calculate bias velocity
- var maxBias = this.maxBias;
- this.bias = clamp(-bias_coef(this.errorBias, dt)*(b.a*this.ratio - a.a - this.phase)/dt, -maxBias, maxBias);
-
- // compute max impulse
- this.jMax = this.maxForce * dt;
-};
-
-GearJoint.prototype.applyCachedImpulse = function(dt_coef)
-{
- var a = this.a;
- var b = this.b;
-
- var j = this.jAcc*dt_coef;
- a.w -= j*a.i_inv*this.ratio_inv;
- b.w += j*b.i_inv;
-};
-
-GearJoint.prototype.applyImpulse = function()
-{
- var a = this.a;
- var b = this.b;
-
- // compute relative rotational velocity
- var wr = b.w*this.ratio - a.w;
-
- // compute normal impulse
- var j = (this.bias - wr)*this.iSum;
- var jOld = this.jAcc;
- this.jAcc = clamp(jOld + j, -this.jMax, this.jMax);
- j = this.jAcc - jOld;
-
- // apply impulse
- a.w -= j*a.i_inv*this.ratio_inv;
- b.w += j*b.i_inv;
-};
-
-GearJoint.prototype.getImpulse = function()
-{
- return Math.abs(this.jAcc);
-};
-
-GearJoint.prototype.setRatio = function(value)
-{
- this.ratio = value;
- this.ratio_inv = 1/value;
- this.activateBodies();
-};
-
-/* Copyright (c) 2007 Scott Lembcke
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-var SimpleMotor = cp.SimpleMotor = function(a, b, rate)
-{
- Constraint.call(this, a, b);
-
- this.rate = rate;
-
- this.jAcc = 0;
-
- this.iSum = this.jMax = 0;
-};
-
-SimpleMotor.prototype = Object.create(Constraint.prototype);
-
-SimpleMotor.prototype.preStep = function(dt)
-{
- // calculate moment of inertia coefficient.
- this.iSum = 1/(this.a.i_inv + this.b.i_inv);
-
- // compute max impulse
- this.jMax = this.maxForce * dt;
-};
-
-SimpleMotor.prototype.applyCachedImpulse = function(dt_coef)
-{
- var a = this.a;
- var b = this.b;
-
- var j = this.jAcc*dt_coef;
- a.w -= j*a.i_inv;
- b.w += j*b.i_inv;
-};
-
-SimpleMotor.prototype.applyImpulse = function()
-{
- var a = this.a;
- var b = this.b;
-
- // compute relative rotational velocity
- var wr = b.w - a.w + this.rate;
-
- // compute normal impulse
- var j = -wr*this.iSum;
- var jOld = this.jAcc;
- this.jAcc = clamp(jOld + j, -this.jMax, this.jMax);
- j = this.jAcc - jOld;
-
- // apply impulse
- a.w -= j*a.i_inv;
- b.w += j*b.i_inv;
-};
-
-SimpleMotor.prototype.getImpulse = function()
-{
- return Math.abs(this.jAcc);
-};
diff --git a/gulp/tasks/engine.js b/gulp/tasks/engine.js
index 369203e81c..f0340aba9f 100644
--- a/gulp/tasks/engine.js
+++ b/gulp/tasks/engine.js
@@ -43,20 +43,11 @@ var jsbSkipModules = [
// '../../cocos2d/core/textures/CCTexture2D',
// '../../cocos2d/core/sprites/CCSpriteFrame',
'../../cocos2d/core/load-pipeline/audio-downloader',
- '../../cocos2d/core/physics/platform/CCPhysicsDebugDraw.js',
- '../../cocos2d/core/physics/platform/CCPhysicsUtils.js',
- '../../cocos2d/core/physics/platform/CCPhysicsContactListner.js',
- '../../cocos2d/core/physics/platform/CCPhysicsAABBQueryCallback.js',
- '../../cocos2d/core/physics/platform/CCPhysicsRayCastCallback.js',
'../../cocos2d/core/platform/CCInputManager.js',
'../../cocos2d/core/platform/CCVisibleRect.js',
'../../cocos2d/core/graphics/helper.js',
- '../../cocos2d/actions/index.js',
'../../cocos2d/audio/CCAudio',
- '../../extensions/spine/lib/spine',
- '../../extensions/dragonbones/lib/dragonBones',
'../../external/box2d/box2d.js',
- '../../external/chipmunk/chipmunk.js',
];
exports.buildCocosJs = function (sourceFile, outputFile, excludes, opt_macroFlags, callback) {
diff --git a/index.js b/index.js
index b4ba4e59b9..0920b95e2e 100644
--- a/index.js
+++ b/index.js
@@ -146,9 +146,6 @@ defineMacro('CC_SUPPORT_JIT', !CC_WECHATGAME);
*/
_global.cc = {};
-// The namespace for original nodes rendering in scene graph.
-_global._ccsg = {};
-
if (CC_DEV) {
/**
* contains internal apis for unit tests
@@ -170,9 +167,6 @@ if (!(CC_EDITOR && Editor.isMainProcess)) {
require('./cocos2d/core/predefine');
-_global.ccs = {};
-_global.cp = {};
-
// LOAD COCOS2D ENGINE CODE
if (!(CC_EDITOR && Editor.isMainProcess)) {
@@ -190,4 +184,4 @@ if (CC_EDITOR) {
}
}
-module.exports = cc;
+module.exports = cc;
\ No newline at end of file
diff --git a/modules.json b/modules.json
index 1d2f383732..2334307d03 100644
--- a/modules.json
+++ b/modules.json
@@ -15,7 +15,8 @@
"name": "Sprite",
"locked": true,
"entries": [
- "./cocos2d/core/components/CCSprite.js"
+ "./cocos2d/core/components/CCSprite.js",
+ "./cocos2d/core/renderer/assemblers/sprite/sprite-assembler.js"
]
},
{
@@ -27,13 +28,15 @@
{
"name": "Label",
"entries": [
- "./cocos2d/core/components/CCLabel.js"
+ "./cocos2d/core/components/CCLabel.js",
+ "./cocos2d/core/renderer/assemblers/label/label-assembler.js"
]
},
{
"name": "Mask",
"entries": [
- "./cocos2d/core/components/CCMask.js"
+ "./cocos2d/core/components/CCMask.js",
+ "./cocos2d/core/renderer/assemblers/mask-assembler.js"
]
},
{
@@ -45,14 +48,14 @@
{
"name": "ParticleSystem",
"entries": [
- "./cocos2d/particle/CCParticleSystem.js",
+ "./cocos2d/particle/index.js",
"./cocos2d/particle/CCParticleAsset.js"
]
},
{
"name": "TiledMap",
"entries": [
- "./cocos2d/tilemap/CCTiledMap.js",
+ "./cocos2d/tilemap/index.js",
"./cocos2d/tilemap/CCTiledMapAsset.js"
]
},
@@ -126,7 +129,7 @@
]
},
{
- "name": "EditorBox",
+ "name": "EditBox",
"entries": [
"./cocos2d/core/components/CCEditBox.js",
"./jsb/jsb-editbox.js"
@@ -135,14 +138,14 @@
{
"name": "VideoPlayer",
"entries": [
- "./cocos2d/core/components/CCVideoPlayer.js",
+ "./cocos2d/videoplayer/CCVideoPlayer.js",
"./jsb/jsb-videoplayer.js"
]
},
{
"name": "WebView",
"entries": [
- "./cocos2d/core/components/CCWebView.js",
+ "./cocos2d/webview/CCWebView.js",
"./jsb/jsb-webview.js"
]
},
@@ -169,7 +172,7 @@
{
"name": "MotionStreak",
"entries": [
- "./cocos2d/motion-streak/CCMotionStreak.js"
+ "./cocos2d/motion-streak/index.js"
]
},
{
@@ -217,20 +220,6 @@
"./cocos2d/core/components/CCStudioComponent.js"
]
},
- {
- "name": "RenderTexture",
- "entries": [
- "./cocos2d/render-texture/CCRenderTexture.js",
- "./cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js",
- "./cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js"
- ]
- },
- {
- "name": "Chipmunk",
- "entries": [
- "./external/chipmunk/chipmunk.js"
- ]
- },
{
"name": "Camera",
"entries": [