code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
var RELANG = {};
RELANG['cs'] = {
html: 'HTML',
video: 'Video',
image: 'Obrázek',
table: 'Tabulka',
link: 'Odkaz',
link_insert: 'Vložit odkaz ...',
unlink: 'Odstranit odkaz',
formatting: 'Styly',
paragraph: 'Odstavec',
quote: 'Citace',
code: 'Kód',
header1: 'Nadpis 1',
header2: 'Nadpis 2',
header3: 'Nadpis 3',
header4: 'Nadpis 4',
format: 'Formát',
bold: 'Tučné',
italic: 'Kurzíva',
superscript: 'Horní index',
strikethrough: 'Přeškrtnuté',
fontcolor: 'Barva písma',
backcolor: 'Barva pozadí',
removeformat: 'Odstranit formátování',
cleanformatting: 'Odstranit styly',
lists: 'Seznamy',
unorderedlist: 'Seznam s odrážkami',
orderedlist: 'Číslovaný seznam',
outdent: 'Zmenšit odsazení',
indent: 'Zvětšit odsazení',
redo: 'Vpřed',
undo: 'Zpět',
cut: 'Vyjmout',
cancel: 'Zrušit',
insert: 'Vložit',
save: 'Uložit',
_delete: 'Smazat',
insert_table: 'Vložit tabulku',
insert_row_above: 'Přidat řádek nahoru',
insert_row_below: 'Přidat řádek dolu',
insert_column_left: 'Přidat sloupec vlevo',
insert_column_right: 'Přidat sloupec vpravo',
delete_column: 'Smazat sloupec',
delete_row: 'Smazat řádek',
delete_table: 'Smazat tabulku',
Rows: 'Řádky',
Columns: 'Sloupce',
add_head: 'Přidat záhlaví',
delete_head: 'Smazat záhlaví',
title: 'Titulek',
image_view: 'Zobrazit obrázek',
image_position: 'Pozice',
none: 'žádný',
left: 'vlevo',
right: 'vpravo',
image_web_link: 'Odkaz na obrázek',
text: 'Text',
mailto: 'Email',
web: 'URL',
video_html_code: 'Kód pro vložení videa na stránku',
file: 'Soubor',
upload: 'Nahrát',
download: 'Stáhnout',
choose: 'Vybrat',
or_choose: 'nebo',
drop_file_here: 'Přetáhněte soubor zde',
align_left: 'Zarovnat vlevo',
align_center: 'Zarovnat na střed',
align_right: 'Zarovnat vpravo',
align_justify: 'Zarovnat do bloku',
horizontalrule: 'Vodorovná čára',
fullscreen: 'Celá obrazovka',
deleted: 'Přeškrtnuté',
none: 'Žádná',
anchor: 'Záložka'
};
| JavaScript |
var RELANG = {};
RELANG['fi'] = {
html: 'HTML',
video: 'Video',
image: 'Kuva',
table: 'Taulukko',
link: 'Linkki',
link_insert: 'Lisää linkki...',
unlink: 'Poista linkki',
formatting: 'Tyylit',
paragraph: 'Normaaliteksti',
quote: 'Lainaus',
code: 'Koodi',
header1: 'Otsikko 1',
header2: 'Otsikko 2',
header3: 'Otsikko 3',
header4: 'Otsikko 4',
bold: 'Lihavointi',
italic: 'Kursivointi',
fontcolor: 'Tekstin väri',
backcolor: 'Taustaväri',
unorderedlist: 'Luettelo luettelomerkein',
orderedlist: 'Numeroitu luettelo',
outdent: 'Vähennä sisennystä',
indent: 'Lisää sisennystä',
redo: 'Tee uudelleen',
undo: 'Kumoa',
cut: 'Leikkaa',
cancel: 'Peru',
insert: 'Lisää',
save: 'Tallenna',
_delete: 'Poista',
insert_table: 'Lisää taulukko',
insert_row_above: 'Lisää rivi ylle',
insert_row_below: 'Lisää rivi alle',
insert_column_left: 'Lisää sarake vasemmalle',
insert_column_right: 'Lisää sarake oikealle',
delete_column: 'Poista sarake',
delete_row: 'Poista rivi',
delete_table: 'Poista taulukko',
rows: 'Rivit',
columns: 'Sarakkeet',
add_head: 'Lisää otsikkorivi',
delete_head: 'Poista otsikkorivi',
title: 'Kuvateksti',
image_position: 'Kuvan sijainti',
none: 'oletus',
left: 'vasen',
right: 'oikea',
image_web_link: 'Kuvan URL-osoite',
text: 'Teksti',
mailto: 'Sähköposti',
web: 'URL-osoite',
video_html_code: 'Videon upotuskoodi',
file: 'Tiedosto',
upload: 'Lähetä',
download: 'Lataa',
choose: 'Valitse',
or_choose: 'tai valitse',
drop_file_here: 'Vedä ja pudota kuva tähän',
align_left: 'Tasaa vasemmalle',
align_center: 'Keskitä',
align_right: 'Tasaa oikealle',
align_justify: 'Tasaa molemmat reunat',
horizontalrule: 'Vaakaviiva',
fullscreen: 'Koko näyttö',
deleted: 'Poistettu',
anchor: 'Ankkuri'
};
| JavaScript |
var RELANG = {};
RELANG['ja'] = {
html: 'HTML',
video: 'ビデオ',
image: 'イメージ',
table: 'テーブル',
link: 'リンク',
link_insert: 'リンクの挿入 ...',
unlink: 'リンクを外す',
formatting: 'スタイル',
paragraph: '段落',
quote: '引用',
code: 'コード',
header1: 'ヘッダー 1',
header2: 'ヘッダー 2',
header3: 'ヘッダー 3',
header4: 'ヘッダー 4',
bold: '太字',
italic: 'イタリック',
fontcolor: 'フォント色',
backcolor: '背景色',
unorderedlist: '番号なしリスト',
orderedlist: '番号つきリスト',
outdent: '字上げ(逆インデント)',
indent: '字下げ(インデント)',
cancel: 'キャンセル',
insert: '挿入',
save: '保存',
_delete: '削除',
insert_table: 'テーブルの挿入',
insert_row_above: '列を上に追加',
insert_row_below: '列を下に追加',
insert_column_left: '行を左に追加',
insert_column_right: '行を右に追加',
delete_column: '行を削除',
delete_row: '列を削除',
delete_table: 'テーブルを削除',
rows: '列',
columns: '行',
add_head: 'テーブルヘッダの追加',
delete_head: 'テーブルヘッダの削除',
title: 'タイトル',
image_position: 'イメージの位置',
none: '無し',
left: '左',
right: '右',
image_web_link: 'イメージへのリンク',
text: 'テキスト',
mailto: 'メール',
web: 'URL',
video_html_code: 'ビデオ埋め込みコード',
file: 'ファイル',
upload: 'アップロード',
download: 'ダウンロード',
choose: '選択',
or_choose: 'または選択',
drop_file_here: 'ファイルをここにドロップ',
align_left: '左揃え',
align_center: '中央揃え',
align_right: '右揃え',
align_justify: '均等割り付け',
horizontalrule: '水平線',
fullscreen: '全画面',
deleted: '打消し',
anchor: 'アンカー'
}; | JavaScript |
var RELANG = {};
RELANG['bg'] = {
html: 'HTML',
video: 'Видео',
image: 'Изображение',
table: 'Таблица',
link: 'Връзка',
link_insert: 'Вкарай връзка ...',
unlink: 'Премахни връзка',
formatting: 'Стилове',
paragraph: 'Параграф',
quote: 'Цитат',
code: 'Код',
header1: 'Заглавие 1',
header2: 'Заглавие 2',
header3: 'Заглавие 3',
header4: 'Заглавие 4',
bold: 'Удебели',
italic: 'Наклони',
fontcolor: 'Цвят на текста',
backcolor: 'Цвят на фона',
unorderedlist: 'Неподреден списък',
orderedlist: 'Подреден списък',
outdent: 'Вкарай навътре',
indent: 'Изкарай навън',
cancel: 'Отказ',
insert: 'Вкарай',
save: 'Запази',
_delete: 'Премахни',
insert_table: 'Вкарай таблица',
insert_row_above: 'Добави ред отгоре',
insert_row_below: 'Добави ред отдолу',
insert_column_left: 'Добави колона отляво',
insert_column_right: 'Добави колона отдясно',
delete_column: 'Премахни колоната',
delete_row: 'Премахни реда',
delete_table: 'Премахни таблицата',
rows: 'Редове',
columns: 'Колони',
add_head: 'Добави заглавен ред',
delete_head: 'Премахни заглавен ред',
title: 'Заглавие',
image_view: 'Виж изображението',
image_position: 'Позиция',
left: 'Ляво',
right: 'Дясно',
image_web_link: 'Уеб връзка',
text: 'Текст',
mailto: 'Имейл',
web: 'Адрес',
video_html_code: 'Код за вграждане на видео',
file: 'Файл',
upload: 'Качи',
download: 'Свали',
choose: 'Избор',
or_choose: 'Или избери',
drop_file_here: 'Провлачете файлове тук',
align_left: 'Подравни в ляво',
align_center: 'Центрирай',
align_right: 'Подравни в дясно',
align_justify: 'Подравни двустранно',
horizontalrule: 'Хоризонтална линия',
fullscreen: 'Цял екран',
deleted: 'Зачеркни',
none: 'Няма',
anchor: 'Връзка'
};
| JavaScript |
var RELANG = {};
RELANG['hu'] = {
html: 'HTML',
video: 'Videó',
image: 'Kép',
table: 'Tábla',
link: 'Link',
link_insert: 'Link beszúrás ...',
unlink: 'Link megszüntetés',
formatting: 'Stílusok',
paragraph: 'Bekezdés',
quote: 'Idézet',
code: 'Kód',
header1: 'Címsor 1',
header2: 'Címsor 2',
header3: 'Címsor 3',
header4: 'Címsor 4',
bold: 'Félkövér',
italic: 'Dőlt',
fontcolor: 'Szöveg szine',
backcolor: 'Szöveg hátterének szine',
unorderedlist: 'Nem számozott lista',
orderedlist: 'Számozott lista',
outdent: 'Outdent',
indent: 'Indent',
cancel: 'Mégsem',
insert: 'Beszurás',
save: 'Mentés',
_delete: 'Törlés',
insert_table: 'Táblázat beszúrása',
insert_row_above: 'Sor beszúrása az aktuális sor fölé',
insert_row_below: 'Sor beszúrása ez alá',
insert_column_left: 'Oszlop beszúrása ettöl balra',
insert_column_right: 'Oszlop hozzáadása ettöl jobbra',
delete_column: 'Oszlop törlése',
delete_row: 'Sor törlése',
delete_table: 'Táblázat törlése',
rows: 'Sorok',
columns: 'Oszlopok',
add_head: 'Fejrész hozzáadása',
delete_head: 'Fejrész törlése',
title: 'Felira',
image_view: 'Kép megnézése',
image_position: 'Pozició',
none: 'nincs',
left: 'bal',
right: 'jobb',
image_web_link: 'Link a képre',
text: 'Szöveg',
mailto: 'Email',
web: 'URL',
video_html_code: 'Videó embed code',
file: 'File',
upload: 'Feltöltés',
download: 'Letöltés',
choose: 'Válassz',
or_choose: 'Vagy válassz',
drop_file_here: 'Ide dobd a file-t',
align_left: 'Balra igazítás',
align_center: 'Középre igazítás',
align_right: 'Jobbra igazítás',
align_justify: 'Sorkizárt',
horizontalrule: 'Horizontális vonal',
fullscreen: 'Teljes képernyős',
deleted: 'Törölt',
anchor: 'Horgony'
};
| JavaScript |
var RELANG = {};
RELANG['en'] = {
html: 'HTML',
video: 'Insert Video...',
image: 'Insert Image...',
table: 'Table',
link: 'Link',
link_insert: 'Insert Link ...',
unlink: 'Unlink',
formatting: 'Formatting',
paragraph: 'Paragraph',
quote: 'Quote',
code: 'Code',
header1: 'Header 1',
header2: 'Header 2',
header3: 'Header 3',
header4: 'Header 4',
bold: 'Bold',
italic: 'Italic',
fontcolor: 'Font Color',
backcolor: 'Back Color',
unorderedlist: 'Unordered List',
orderedlist: 'Ordered List',
outdent: 'Outdent',
indent: 'Indent',
cancel: 'Cancel',
insert: 'Insert',
save: 'Save',
_delete: 'Delete',
insert_table: 'Insert Table...',
insert_row_above: 'Add Row Above',
insert_row_below: 'Add Row Below',
insert_column_left: 'Add Column Left',
insert_column_right: 'Add Column Right',
delete_column: 'Delete Column',
delete_row: 'Delete Row',
delete_table: 'Delete Table',
rows: 'Rows',
columns: 'Columns',
add_head: 'Add Head',
delete_head: 'Delete Head',
title: 'Title',
image_position: 'Position',
none: 'None',
left: 'Left',
right: 'Right',
image_web_link: 'Image Web Link',
text: 'Text',
mailto: 'Email',
web: 'URL',
video_html_code: 'Video Embed Code',
file: 'Insert File...',
upload: 'Upload',
download: 'Download',
choose: 'Choose',
or_choose: 'Or choose',
drop_file_here: 'Drop file here',
align_left: 'Align Left',
align_center: 'Align Center',
align_right: 'Align Right',
align_justify: 'Justify',
horizontalrule: 'Insert Horizontal Rule',
fullscreen: 'Fullscreen',
deleted: 'Deleted',
anchor: 'Anchor'
};
| JavaScript |
/**
* Class Item
* This class manipulate html created from template and element created by tag for item
* Example:
* var item = new Item({name: "text"}, "template-id", "li");
* or
* var item = new Item(); // -> is empty "li" element
* item.setTag("div"); // -> now we change to "div" element
* item.setTemplate("template-id");
* item.setData({name: "test"}); // -> generaget html form template
* //and data is appended to this "div" element
* item.setOnClickListener(function(){
* //this -> item instance
* });
*/
Item = (function(_super) {
__extends(Item, _super);
/**
* Item constructor
* @param [data] {Object} data for item
* @param [templateid] {String} template or template id for this item
* @param [tag] {String} html tag fot this item "li" by default
* @constructor
*/
function Item(data, templateid, tag) {
Item.__super__.constructor.call(this);
this.setTag(tag);
this.setTemplate(templateid);
this.setData(data);
}
/**
* Set Tag name and create content view
* @param [tag] {String} html tag fot this item "li" by default
*/
Item.prototype.setTag = function(tag){
this.tag = "li" || tag;
this.setContentView(document.createElement(this.tag));
};
/**
* Set Javascript Template for item
* @param [templateid] {String} template or template id for this item
*/
Item.prototype.setTemplate = function(templateid){
this.templateID = templateid;
};
/**
* Set Date and create html with template
* @param data {Object} item data
*/
Item.prototype.setData = function(data) {
this.data = data;
if(!this.templateID) return;
this.template = new Template(this.templateID, data);
this.view.html(this.template.getHTML());
this.loadImages(this.view.selectAll('.image', true));
};
/**
* Load Images crate Background image if we have image in template
* (image is div or other element with css class "image")
* @param images {[HTMLElement]} collection of HTMLElements
*/
Item.prototype.loadImages = function(images){
var _i, _image;
if(!images || images.length == 0) return;
for(_i = 0; _i < images.length; _i++){
_image = new BackgroundImage(images[_i]);
}
};
/**
* Remove html item form html
*/
Item.prototype.remove = function(){
this.view.remove();
};
return Item;
})(Base); | JavaScript |
/**
* Class Intent
* This class is used to create intent the show/hide Page/Fragment
* Example
* var intent = new Intent("pageName");
* intent.setExtras("key": "value");
* intent.setAnimation("animation_name");
* //or
* intent.setAnimation(new Animation("animation_name", 100))
*/
Intent = (function(){
/**
* Intent constructor
* @param name {String} Page or Fragment name
* @constructor
*/
function Intent(name){
this.setName(name);
this.extras = {};
}
/**
* Set name of Page or Fragment class
* @param name {String} Page/Fragment name
*/
Intent.prototype.setName = function(name){
this.name = name;
};
/**
* Get name of Page or Fragment that we set before
* @returns {String}
*/
Intent.prototype.getName = function(){
return this.name;
};
/**
* Set Extra data that is used in Page or Fragment if we want to
* send data from one Page/Fragment to other
* @param key {String} Name of property
* @param value {*} Data that we save
* @returns {Intent} this intent
*/
Intent.prototype.setExtras = function(key, value){
this.extras[key] = value;
return this;
};
/**
* Get Extra data form intent
* @param key {String} Name of data
* @returns {*} data that we save in intent
*/
Intent.prototype.getExtras = function(key){
return this.extras[key];
};
/**
* Set Animation that we want to show or hide Page/Fragment
* @param animation {String|Animation} Animation name or Animation object
* @returns {Intent} this intent
*/
Intent.prototype.setAnimation = function(animation){
this.animation = animation;
return this;
};
/**
* Get Animation form intent
* @returns {String|Animation} animation in this intent
*/
Intent.prototype.getAnimation = function(){
return this.animation;
};
return Intent;
})(); | JavaScript |
/**
* Class TitleBar
* This class manipulate the html used for title
* Example:
* //html for title
* //<div id="title-id" class="title-bar">
* // <div class="button-holder">
* // <div class="button">
* // <span></span>
* // </div>
* // </div>
* // <div class="text-holder">
* // <h1></h1>
* // </div>
* // <div class="button-holder">
* // <div class="button">
* // <span></span>
* // </div>
* // </div>
* //</div>
* var title = new TitleBar("title-id");
* title.setText("Title");
* title.buttons -> array of Button
*/
TitleBar = (function(_super) {
__extends(TitleBar, _super);
/**
* TitleBar constructor
* @param view {String|View|HTMLElement} id, view or html element
* @constructor
*/
function TitleBar(view) {
var button, _i, _len, _ref;
TitleBar.__super__.constructor.call(this);
this.setContentView(view);
this._text = this.view.select("h1");
this._buttons = this.view.selectAll(".button-holder", true);
this.buttons = [];
_ref = this._buttons;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
button = _ref[_i];
this.buttons.push(new Button(button));
}
}
/**
* Set title text
* @param text {String} title text
*/
TitleBar.prototype.setText = function(text) {
if (!text) return;
this._text.html(this.text = text);
};
return TitleBar;
})(Base);
| JavaScript |
/**
* Class Local
* this class is used to save data to localstorage
*/
Local = (function() {
/**
* Local constructor
* @param name {String} key for this data
* @constructor
*/
function Local(name) {
this.name = name;
}
/**
* Set and save data
* @param data {*} saved data
* @param ttl {Number} time to live for this data in minutes
* @returns {*}
*/
Local.prototype.set = function(data, ttl) {
this.data = this.data || {};
this.data.ttl = Date.now() + ((ttl || 10) * 1000 * 60);
this.data.data = data || this.data.data;
return localStorage.setItem(this.name, JSON.stringify(this.data));
};
/**
* Get data form
* @returns {*}
*/
Local.prototype.getData = function(){
var _data = this.data || {};
_data.data = _data.data || {};
return _data.data;
};
/**
* Get data form localstorage
* @returns {*} data
*/
Local.prototype.get = function() {
this.data = JSON.parse(localStorage.getItem(this.name));
if (this.data) {
return this.data.data;
}
return void 0;
};
return Local;
})();
| JavaScript |
/**
* Class Bootstrap
* is used to load scripts and image assets
*/
Bootstrap = (function() {
/**
* Bootstrap constructor
* @constructor
*/
function Bootstrap() {
this.local = new Local('bootstrap');
this.head = new View(document.head);
this.counter = 0;
this.scriptsCounter = 0;
this.assetsCounter = 0;
}
/**
* Start loading scripts and assets from bootstrap.json file or form saved in localstorage
* @param [update] {Boolean} to get files form json file or form localstorage
*/
Bootstrap.prototype.load = function(update) {
var _this = this;
this.data = this.local.get();
if (update || !this.data) {
this.ajax = new Ajax();
this.ajax.setOnSuccessListener(function(data) {
if (data.status === "success") {
_this.local.set(_this.data = data.data);
}
_this.loadScripts();
_this.loadAssets();
});
this.ajax.open("bootstrap.json");
this.ajax.send();
} else {
this.loadScripts();
this.loadAssets();
}
};
/**
* Load Scripts files
*/
Bootstrap.prototype.loadScripts = function() {
var script,
_this = this;
script = new View(document.createElement('script'));
script.element.onload = function(e) {
_this.scriptsCounter++;
_this.update();
if (_this.scriptsCounter < _this.data.scripts.length) {
_this.loadScripts();
} else {
if (_this.assetsCounter === _this.data.assets.length) {
_this.ready();
}
}
};
script.attr({
type: "text/javascript"
});
if (this.data.scripts[this.scriptsCounter]) {
script.element.src = this.data.scripts[this.scriptsCounter].src;
}
this.head.append(script);
};
/**
* Load image assets
*/
Bootstrap.prototype.loadAssets = function() {
var asset, image, _i, _len, _ref,
_this = this;
if (this.data.assets.length === 0 && this.scriptsCounter === this.data.scripts.length) {
this.ready();
}
_ref = this.data.assets;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
asset = _ref[_i];
image = new Image();
image.onload = function() {
_this.assetsCounter++;
_this.update();
if (_this.assetsCounter === _this.data.assets.length && _this.scriptsCounter === _this.data.scripts.length) {
return _this.ready();
}
};
image.src = asset;
}
};
/**
* Update counter
*/
Bootstrap.prototype.update = function() {
this.counter++;
if(this.updateListener)
this.updateListener.call(this);
};
/**
* This method is called when all scripts and assets are loaded
*/
Bootstrap.prototype.ready = function() {
if(this.readyListener)
this.readyListener.call(this);
};
/**
* Set on update listener
* @param listener {Function} update listener
*/
Bootstrap.prototype.setOnUpdateListener = function(listener){
if(!(listener instanceof Function)) throw "listener is not a Function";
this.updateListener = listener;
};
/**
* Set on ready listener
* @param listener {Function} ready listener
*/
Bootstrap.prototype.setOnReadyListener = function(listener) {
if(!(listener instanceof Function)) throw "listener is not a Function";
this.readyListener = listener;
};
return Bootstrap;
})();
| JavaScript |
/**
* Class Config
* is used to parse he config data form config.json or form localstorage
*/
Config = (function() {
/**
* Config constructor
* @constructor
*/
function Config() {
this.local = new Local('config');
}
/**
* Load config from config.json or localstorage
* @param [update] {Boolean} update form ajax or not
*/
Config.prototype.load = function(update) {
var _this = this;
this.data = this.local.get();
if (update || !this.data) {
this.ajax = new Ajax();
this.ajax.setOnSuccessListener(function(data) {
if (data.status === "success") {
_this.local.set(_this.data = data.data);
}
if(_this.loadListener) _this.loadListener.call(this);
});
this.ajax.open("config.json");
this.ajax.send();
} else {
if(_this.loadListener) _this.loadListener.call(this);
}
};
/**
* Set On load listener
* @param listener {Function} load listener
*/
Config.prototype.setOnLoadListener = function(listener) {
if(!(listener instanceof Function)) throw "listener is not a Function";
this.loadListener = listener;
};
return Config;
})();
| JavaScript |
/**
* Class Button
* This class manipulate the html used for button
* Example:
* //html for button
* //<div class="button-holder">
* // <div class="button">
* // <span></span>
* // </div>
* //</div>
* var button = new Button("button-id");
* button.setText("Button");
* button.setType("back");
* button.setAction(function(e){
* //this -> button instance
* //e -> event
* });
*/
Button = (function(_super) {
__extends(Button, _super);
/**
* Button constructor
* @param view {View|String|HTMLElement} id, htmlelement or View
* @constructor
*/
function Button(view) {
Button.__super__.constructor.call(this);
this.setContentView(view);
this._text = this.view.select("span");
this.button = this.view.select(".button");
}
/**
* Overwrite set content view and create if we have no view
* @param view {View|String|HTMLElement}
*/
Button.prototype.setContentView = function(view){
Button.__super__.setContentView.call(this, view || this.create());
};
/**
* Create view and html structure for this button class
* @returns {View}
*/
Button.prototype.create = function(){
var view = new View(document.createElement("div"));
view.addClass("button-holder activatable");
view.html('<div class="button"><span></span></div>');
return view;
};
/**
* Set Button text if button have this._text object
* @param text {String} Button text
*/
Button.prototype.setText = function(text) {
if (!text) return;
this._text.html(this.text = text);
};
/**
* Set Button type add css class to this.button object
* @param type {String}
*/
Button.prototype.setType = function(type) {
if (!type) return;
this.button.addClass(this.type = type);
};
return Button;
})(Base);
| JavaScript |
/**
* Class List
* This class create a list and add items from data array
* Example:
* var list = new List("list-id", "template-id");
* list.setOnItemSelectedListener(function(е, index){
* //this -> clicked item
* //index -> index of clicked item
* });
*
* list.setOnItemCreatedListener(function(e, item){
* //this -> list instance
* //item -> created item
* });
*
* list.setItems(dataArray);
* //add extra item with different template
* list.addItem(data, "template-id", "li");
*/
List = (function(_super) {
__extends(List, _super);
/**
* List constructor
* @param view {View|String|HTMLElement} view, string id or html element
* @param [template] {String} id of template
* @param [itemtag] {String} html tag for item
* @constructor
*/
function List(view, template, itemtag) {
List.__super__.constructor.call(this);
this.setContentView(view || document.createElement("ul"));
this.setTemplate(template);
this.setItemTag(itemtag);
this.items = [];
}
/**
* Set html tag for list item
* @param tag {String} html tag
*/
List.prototype.setItemTag = function(tag){
this.itemTag = tag;
};
/**
* Set Template id
* @param template {String} template id
*/
List.prototype.setTemplate = function(template){
this.templateID = template;
};
/**
* Add one extra or external item
* @param data {*} item data
* @param [template] {String} template id
* @param [tag] {String} html tag
*/
List.prototype.addItem = function(data, template, tag){
var item = new Item(data, template || this.templateID, tag || this.itemTag);
if(this.listener) item.setOnClickListener(this.listener, this.items.length);
this.items.push(item);
if(this.itemCreatedListener) this.itemCreatedListener.call(this, item);
this.view.append(item.view);
};
/**
* Set items form array
* @param data {Array} array of item data
*/
List.prototype.setItems = function(data) {
var _i, _data,
_this = this;
this.data = data;
this.removeItems();
for (_i = 0; _i < data.length; _i++) {
_data = data[_i];
_this.addItem(_data);
}
};
/**
* Remove items and html
*/
List.prototype.removeItems = function(){
this.items.length = 0;
this.view.html("");
};
/**
* Remove only one item by index
* @param index {Number} item index
*/
List.prototype.removeItem = function(index){
var _item = this.items.splice(index, 1);
_item.remove();
};
/**
* Set On Item Created Listener
* @param listener {Function} item created listener
*/
List.prototype.setOnItemCreatedListener = function(listener){
if(!(listener instanceof Function)) throw "listener is not a Function";
this.itemCreatedListener = listener;
};
/**
* Set on item selected listener
* @param listener {Function} item selected listner
*/
List.prototype.setOnItemSelectedListener = function(listener){
if(!(listener instanceof Function)) throw "listener is not a Function";
this.listener = listener;
};
return List;
})(Base);
| JavaScript |
/**
* Class TabBar
* mange tabs and tabbars
*/
TabBar = (function(_super){
__extends(TabBar, _super);
/**
* TabBar constructor
* @param view {String|View|HTMLElement} id, view or html element
* @constructor
*/
function TabBar(view){
var _button, _i, _len, _ref;
TabBar.__super__.constructor.call(this);
this.setContentView(view);
this._buttons = this.view.selectAll(".button-holder", true);
this._active = null;
this.buttons = [];
_ref = this._buttons;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
_button = new Button(_ref[_i]);
this.buttons.push(_button);
}
}
/**
* Get active tab
* @returns {Button} active tab
*/
TabBar.prototype.getActive = function(){
return this.buttons[this._active];
};
/**
* Set active tab by index
* @param index {Number} index of button that we want to make active
*/
TabBar.prototype.setActive = function(index){
this._active = index;
this.buttons[index].addClass('active');
};
/**
* Remove active by index
* @param index {Number} index of button
*/
TabBar.prototype.removeActive = function(index){
this._active = null;
this.buttons[index].removeClass('active');
};
/**
* Set on tab selected listener
* @param listener {Function} tab selected listener
*/
TabBar.prototype.setOnTabSelectedListener = function(listener){
this.tabSelectedListener = listener;
this.setOnClickListeners();
};
/**
* Set click listener for all buttons
*/
TabBar.prototype.setOnClickListeners = function(){
var _i, _len;
for(_i = 0, _len = this.buttons.length; _i < _len; _i++){
if(this.tabSelectedListener) this.buttons[_i].setOnClickListener(this.tabSelectedListener, _i);
}
};
return TabBar;
})(Base); | JavaScript |
/**
* Class BackgroundImage create and load image
* Example:
* form HTML ->
* <div id="image" class="image" data-src="image.png"></div>
* var image = new Image("image");
* load without data-src ->
* image.setSource("image.png");
* create without HTML ->
* var image = new Image();
* image.setSource("image.png");
*/
BackgroundImage = (function (_super) {
__extends(BackgroundImage, _super);
/**
* BackgroundImage constructor
* @param [view] {String|HTMLElement} id or html element
* @constructor
*/
function BackgroundImage(view) {
BackgroundImage.__super__.constructor.call(this);
this.setContentView(view);
this.setSource(this.view.attr("data-src"));
}
/**
* Overwrite the setContentView and create the HTMLElement if we have not view
* @param [view] {String|HTMLElement} id or html element
*/
BackgroundImage.prototype.setContentView = function(view){
var view = view ? view :
document.createElement("div");
BackgroundImage.__super__.setContentView.call(this, view);
};
/**
* Set Image Source set from data-src if we have
* @param src {String} Image src
*/
BackgroundImage.prototype.setSource = function(src){
if(!src) return;
this.source = src;
this.view.addClass('image loading');
if(this.source) this.load();
};
/**
* Load image than set image source to background
*/
BackgroundImage.prototype.load = function(){
var _this = this,
_image = new Image();
_image.onload = function(){
_this.view.style({"background-image": "url("+_this.source+")"});
_this.view.removeClass("loading");
if(_this.loadListener) _this.loadListener.call(_this);
};
_image.src = this.source;
};
/**
* Set on image load listener
* @param listener {Function}
*/
BackgroundImage.prototype.setOnLoadListener = function(listener){
if(!(listener instanceof Function)) throw "listener is not a Function";
this.loadListener = listener;
};
return BackgroundImage;
})(Base); | JavaScript |
/**
* Class Base
* the class that used form other components for base
*/
Base = (function() {
/**
* Base constructor
* @param [context] {Applicaiton|Page}
* @constructor
*/
function Base(context) {
this.context = context;
this.style = new Style();
}
/**
* Set content view (this.view) from id or htmlelenent or View
* @param view {String|View|HTMLElement} content view element
*/
Base.prototype.setContentView = function(view){
if(!view) return;
if(view instanceof View){
this.view = view;
}else{
this.view = new View(view);
}
};
/**
* Set On click listener
* @param callback {Function} click listener
* @param [data] {*} extra data
*/
Base.prototype.setOnClickListener = function(callback, data) {
var _this = this;
if(!(callback instanceof Function)) throw "callback is not a Function";
this.view.bind("click", function(e){
e.stopPropagation();
callback.call(_this, e, data);
});
};
/**
* Set On touchstart listener
* @param callback {Function} touchstart listener
* @param [data] {*} extra data
*/
Base.prototype.setOnTouchStartListener = function(callback, data) {
var _this = this;
if(!(callback instanceof Function)) throw "callback is not a Function";
this.view.bind("touchstart", function(e){
e.stopPropagation();
callback.call(_this, e, data);
});
};
/**
* Set On touchmove listener
* @param callback {Function} touchmove listener
* @param [data] {*} extra data
*/
Base.prototype.setOnTouchMoveListener = function(callback, data) {
var _this = this;
if(!(callback instanceof Function)) throw "callback is not a Function";
this.view.bind("touchmove", function(e){
e.stopPropagation();
callback.call(_this, e, data);
});
};
/**
* Set On touchend listener
* @param callback {Function} touchend listener
* @param [data] {*} extra data
*/
Base.prototype.setOnTouchEndListener = function(callback, data) {
var _this = this;
if(!(callback instanceof Function)) throw "callback is not a Function";
this.view.bind("touchend", function(e){
e.stopPropagation();
callback.call(_this, e, data);
});
};
/**
* On Show method call when this is showed
* @param [intent] {Intent} intent that we show this element
*/
Base.prototype.onShow = function(intent) {};
/**
* Before Show method call before this is showed
* @param [intent] {Intent} intent that we show this element
*/
Base.prototype.beforeShow = function(intent) {};
/**
* On Hide method call when this is hided
* @param [intent] {Intent} intent that we hide this element
*/
Base.prototype.onHide = function(intent) {
this.view.removeClass("current");
};
/**
* Before Hide method call before this is hided
* @param [intent] {Intent} intent that we hide this element
*/
Base.prototype.beforeHide = function(intent) {};
/**
* Method that show this content view with or without animation
* @param [intent] {Intent} intent that we show this element
*/
Base.prototype.show = function(intent) {
this.beforeShow(intent);
if (this.animation){
this.setOnAnimationEndListener(function(){
this.onShow(intent);
});
this.startAnimation();
}else{
this.onShow(intent);
}
this.view.addClass("current");
};
/**
* Method that hide this content view with or without animation
* @param [intent] {Intent} intent that we hide this element
*/
Base.prototype.hide = function(intent) {
this.beforeHide(intent);
if(this.animation){
this.setOnAnimationEndListener(function(){
this.onHide(intent);
});
this.startAnimation();
}else{
this.onHide(intent);
}
};
/**
* @deprecated use setAnimation(name)
* @param name
*/
Base.prototype.setTranslation = function(name){
this.setAnimation(name);
};
/**
* @deprecated user startAnimation()
* @param listener
*/
Base.prototype.startTranslation = function(listener){
this.setOnAnimationEndListener(listener);
this.startAnimation();
};
/**
* Set On Transition End Listener
* @param listener {Function} transition end listener
*/
Base.prototype.setOnTransitionEndListener = function(listener){
var _this = this;
if(!(listener instanceof Function)) throw "listener is not a Function";
this.transitionEndCallback = function() {
if(_this.transitionEndListener) _this.transitionEndListener.call(_this);
};
this.transitionEndListener = listener;
this.view.addEvent("webkitTransitionEnd", this.transitionEndCallback);
};
/**
* Remove transition end listener
*/
Base.prototype.removeOnTransitionEndListener = function(){
this.transitionEndListener = void 0;
this.view.removeEvent("webkitTransitionEnd", this.transitionEndCallback);
};
/**
* Set animation with name or Animation object
* @param animation {String|Animation} animation name or animation object
*/
Base.prototype.setAnimation = function(animation){
if(!animation) return;
if(typeof animation === "string"){
this.animation = animation;
return;
}
if(!(animation instanceof Animation)) return;
this.animation = animation.name;
};
/**
* Set on animation end listener
* @param listener {Function} animation end listener
*/
Base.prototype.setOnAnimationEndListener = function(listener){
if(!(listener instanceof Function)) throw "listener is not a Function";
this.аnimationEndListener = listener;
};
/**
* Start Animation if we have one
*/
Base.prototype.startAnimation = function(){
var callback,
_this = this;
if(!this.animation){
this.animation = "";
this.view.removeEvent("webkitAnimationEnd", callback);
if(this.аnimationEndListener) this.аnimationEndListener.call(this);
this.аnimationEndListener = void 0;
return;
}
this.view.addEvent("webkitAnimationEnd", callback = function(e) {
_this.view.removeClass(_this.animation);
if(_this.аnimationEndListener) _this.аnimationEndListener.call(_this);
_this.аnimationEndListener = void 0;
_this.animation = "";
_this.view.removeEvent("webkitAnimationEnd", callback);
});
this.view.addClass(this.animation || "");
};
return Base;
})();
| JavaScript |
/**
* Created by JetBrains WebStorm.
* User: hp-stuff
* Date: 13-4-20
* Time: 11:33
* To change this template use File | Settings | File Templates.
*/
DB = (function () {
function DB() {
this.db = null;
}
DB.getInstance = function(){
if(this._instance){
return this._instance;
}
return this._instance = new DB();
};
DB.prototype.setOnOpenListener = function(listener){
this.openListener = listener;
};
DB.prototype.setOnUpgradeListener = function(listener){
this.upgradeListener = listener;
};
DB.prototype.setOnErrorListener = function(listener){
this.errorListener = listener;
};
DB.prototype.open = function(name, version){
var request, _this = this;
this.version = version || 0;
this.name = name;
request = indexedDB.open(this.name, this.version);
request.onupgradeneeded = function(e) {
var db = e.target.result;
if(_this.upgradeListener) _this.upgradeListener.call(_this, e);
};
request.onsuccess = function(e){
_this.db = e.target.result;
if(_this.openListener) _this.openListener.call(_this, e);
};
request.onerror = function(e){
if(_this.errorListener) _this.errorListener.call(_this, e);
}
};
DB.prototype.addItem = function(store, item){
var trans = this.db.transaction([store], "readwrite");
var store = trans.objectStore(store);
var request = store.put(item);
};
DB.prototype.removeItem = function(id){
var trans = this.db.transaction([store], "readwrite");
var store = trans.objectStore(store);
var request = store.delete(id);
};
DB.prototype.getStore = function(store){
};
return DB;
})(); | JavaScript |
/**
* Class Fragment
* Fragments are used to create а page in other page
* Example:
* see Page class
*/
Fragment = (function(_super){
__extends(Fragment, _super);
/**
* Fragment constructor
* @param context {Page} parent Page
* @constructor
*/
function Fragment(context){
Fragment.__super__.constructor.call(this, context);
this.userIScroll = false;
this.isCurrent = false;
}
/**
* Overwrite set content view to add iscroll options
* @param view {String|View|HTMLElement} id, html element or view
*/
Fragment.prototype.setContentView = function(view){
Fragment.__super__.setContentView.call(this, view);
if(!this.userIScroll) return;
var scroll = this.view.select(".content", true);
this.scroll = new iScroll(scroll, {
hideScrollbar: true
});
};
/**
* Create and return title bar form html with class "title-bar" form fragment view
* or form view argument
* @param [view] {String|View|HTMLElement} id, html element or view
* @returns {TitleBar}
*/
Fragment.prototype.getTitle = function(view) {
return this.title = new TitleBar(view || this.view.element.querySelector('.title-bar'));
};
/**
* Get Fragment context
* @returns {Page} Fragment context
*/
Fragment.prototype.getContext = function(){
return this.context;
};
/**
* Overwrite before Show to reset iscroll if we have one
* @param [intent] {Intent} intent that we show this element
*/
Fragment.prototype.beforeShow = function(intent){
if(!this.userIScroll) return;
this.scroll.scrollTo(0, 0);
};
/**
* Overwrite on Show to refresh iscroll if we have one and set isCurrent to true
* @param [intent] {Intent} intent that we show this element
*/
Fragment.prototype.onShow = function(intent){
var _this = this;
this.isCurrent = true;
if(!this.userIScroll) return;
setTimeout(function(){
_this.scroll.refresh();
},1);
};
/**
* Overwrite on Hide to set isCurrent to false because page is not current now
* @param [intent] {Intent} intent that we hide this element
*/
Fragment.prototype.onHide = function(intent){
Fragment.__super__.onHide.call(this, intent);
this.isCurrent = false;
};
return Fragment;
})(Base); | JavaScript |
/**
* Class Views
* This class manipulate HTMLElements
* Example:
* //by html element css selector
* var collection = new Views("div");
* //by html NodeList
* var collection = new Views(document.getElementsByTagName("div"));
*/
Views = (function() {
/**
* View constructor
* Create views collection based on selector or html collection
* @param htmlcollection {String|HTMLCollection} css selector or html collection
* @constructor
*/
function Views(htmlcollection) {
if (htmlcollection instanceof NodeList || htmlcollection instanceof HTMLCollection) {
this.htmlcollection = htmlcollection;
this.toViews();
} else {
this.getByCss(htmlcollection);
}
}
/**
* Get one view from views by index
* @param index {Number} view index
* @returns {View|*} view or undefined
*/
Views.prototype.get = function(index) {
return this.elements[index];
};
/**
* Make html collection for views
*/
Views.prototype.toViews = function() {
var element, _i, _len, _ref;
this.elements = [];
_ref = this.htmlcollection;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
element = _ref[_i];
this.elements.push(new View(element));
}
};
/**
* Get html collections and create views by tag name
* @param tag {String} html tag name
*/
Views.prototype.getByTag = function(tag) {
this.htmlcollection = document.getElementsByTagName(tag);
this.toViews();
};
/**
* Get html collection and create views by css class
* @param classname {String} css class name
*/
Views.prototype.getByClass = function(classname) {
this.htmlcollection = document.getElementsByClassName(classname);
this.toViews();
};
/**
* Get html collection and create views by css selector
* @param selector {String} css selector
*/
Views.prototype.getByCss = function(selector) {
this.htmlcollection = document.querySelectorAll(selector);
this.toViews();
};
/**
* Add css class to all views
* @param name {String} css class name
*/
Views.prototype.addClass = function(name) {
var element, _i, _len, _ref;
_ref = this.elements;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
element = _ref[_i];
element.addClass(name);
}
};
/**
* Remove css class from all views
* @param name {String} css class name
*/
Views.prototype.removeClass = function(name) {
var element, _i, _len, _ref;
_ref = this.elements;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
element = _ref[_i];
element.removeClass(name);
}
};
/**
* For each views in this collection
* @param fn {Function} for each callback
*/
Views.prototype.forEach = function(fn){
this.elements.forEach(fn);
};
return Views;
})(); | JavaScript |
/**
* Class Template
* This class create html from js template and data object
* Example:
* //template text
* // <p><%=name%></p>
* var template = new Template("template-id", {name: "data"});
* template.getHtml();
* // result -> <p>data</p>
*/
Template = (function() {
/**
* Template constructor
* create template and return html
* @param id {String} template id
* @param data {Object} template data
* @returns {*}
* @constructor
*/
function Template(id, data) {
this.id = id;
this.cache = {};
return this.html = this.load(this.id, data || {});
}
/**
* Get created html
* @returns {String} created html from template
*/
Template.prototype.getHTML = function() {
return this.html;
};
/**
* Create html from template and data
* @param str {String} template or template id
* @param data {Object} template data
* @returns {String}
*/
Template.prototype.load = function(str, data) {
var fn;
fn = /^[0-9a-z_-]+$/i.test(str) ?
this.cache[str] = this.cache[str] || this.load(document.getElementById(str).innerHTML) :
new Function("obj",
"var p=[],\
print=function(){\
p.push.apply(p,arguments);\
};\
with(obj){\
p.push('" +
str.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
+ "');\
}\
return p.join('');"
);
return data ? fn(data) : fn;
};
return Template;
})(); | JavaScript |
/**
* Class Page
* this class manage pages
*/
Page = (function(_super) {
__extends(Page, _super);
/**
* Page constructor
* @param context {Application} applicaiton instance
* @constructor
*/
function Page(context) {
Page.__super__.constructor.call(this, context);
this.userIScroll = false;
this.isCurrent = false;
}
/**
* Set Content view
* @param view {String|View|HTMLElement} id, view or html element
*/
Page.prototype.setContentView = function(view){
Page.__super__.setContentView.call(this, view);
if(!this.userIScroll) return;
var scroll = this.view.select(".content", true);
this.scroll = new iScroll(scroll, {
hideScrollbar: true
});
};
/**
* Create and return title instance
* @param [view] {View|String|HTMLElement} id, view or html element search for .title-bar css class if we have no view
* @returns {TitleBar} titlebar instance
*/
Page.prototype.getTitle = function(view) {
return this.title = new TitleBar(view || this.view.select('.title-bar', true));
};
/**
* Before Show function
* @param intent {Intent} intent that we show this element
*/
Page.prototype.beforeShow = function(intent){
if(!this.userIScroll) return;
this.scroll.scrollTo(0, 0);
};
/**
* On Show function
* @param intent {Intent} intent that we show this element
*/
Page.prototype.onShow = function(intent){
var _this = this;
if(!this.userIScroll) return;
setTimeout(function(){
_this.scroll.refresh();
},1);
this.isCurrent = true;
};
/**
* On Hide function
* @param intent {Intent} intent that we hide this element
*/
Page.prototype.onHide = function(intent){
this.isCurrent = false;
};
/**
* Get page context
* @returns {Application}
*/
Page.prototype.getContext = function(){
return this.context;
};
/**
* Add new Fragment
* @param name {String}
* @param fragment {Fragment}
*/
Page.prototype.addFragment = function(name, fragment){
this.fragments = this.fragments || {};
this.fragments[name] = fragment;
this.fragments[name].name = name;
};
/**
* Show fragment with intent and set current if we want or not
* @param intent {Intent} intent that we show this fragment
* @param current {Boolean} if we want this fragment to be current or not
*/
Page.prototype.showFragment = function(intent, current){
var _name = intent.getName(),
_current = current === void 0 ? true : current,
_animation = intent.getAnimation();
if(_current === true){
this._currentFragment = this.fragments[_name];
}
if(this.fragments[_name]){
this.fragments[_name].setAnimation(_animation);
this.fragments[_name].show(intent);
}
};
/**
* Hide fragment with intent
* @param intent {Intent} intent that we hide this fragment
*/
Page.prototype.hideFragment = function(intent){
var _name = intent.getName(),
_animation = intent.getAnimation(),
fragment = this.fragments[_name];
if(fragment && fragment === this._currentFragment) this._currentFragment == null;
fragment.setAnimation(_animation);
fragment.hide(intent);
};
/**
* Hide current fragment if we have current
* @param intent {Intent} intent that we hide current fragment
*/
Page.prototype.hideCurrentFragment = function(intent){
if(!this._currentFragment) return;
if(intent){
this._currentFragment.setTranslation(intent.getTranslation());
}
this._currentFragment.hide(intent);
};
/**
* Get current fragment
* @returns {Fragment} current fragment
*/
Page.prototype.getCurrentFragment = function(){
return this._currentFragment;
};
return Page;
})(Base); | JavaScript |
/**
* Class Ajax
* This class is used to create a ajax requests
*
* Example:
*
* var ajax = new Ajax();
* ajax.open("http://api.com/test.json");
* ajax.onSuccess = function(data){
* //data.status -> "success"
* //data.data -> result form server
* };
* ajax.onError = function(data){
* //data.status -> "error"
* //data.data -> null
* };
* ajax.send();
*/
Ajax = (function() {
/**
* Class Ajax constructor
*
* @constructor
*/
function Ajax() {
var _this = this;
this.xmlhttp = (typeof window.createRequest === "function" ? window.createRequest() : void 0) || (XMLHttpRequest ? new XMLHttpRequest() : void 0);
this.xmlhttp.onreadystatechange = function() {
if (_this.xmlhttp.readyState !== 4) {
return void 0;
}
if (!(_this.xmlhttp.status === 200 || _this.xmlhttp.status === 304)) {
if(_this.successListener)
_this.successListener.call(_this, {
status: _this.xmlhttp.status,
data: {}
});
}
if (_this.xmlhttp.responseText) {
if(_this.successListener)
try{
_this.successListener.call(_this, {
status: "success",
data: JSON.parse(_this.xmlhttp.responseText)
});
}catch (e){
_this.successListener.call(_this, {
status: "success",
data: _this.xmlhttp.responseText
});
}
}
};
if ('onerror' in this.xmlhttp) {
this.xmlhttp.onerror = function() {
if(_this.errorListener)
_this.errorListener.call(this, {
status: 'error',
data: null
});
};
}
this.method = "GET";
}
/**
* Set On Success Listener this event will be fired when ajax return result
*
* @param listener {Function} Listener Function
*/
Ajax.prototype.setOnSuccessListener = function(listener) {
if(!(listener instanceof Function)) throw "listener is not a fucntion.";
this.successListener = listener;
};
/**
* Set On Success Listener this event will be fired when ajax return result
*
* @param listener {Function} Listener Function
*/
Ajax.prototype.setOnErrorListener = function(listener) {
if(!(listener instanceof Function)) throw "listener is not a fucntion.";
this.errorListener = listener;
};
/**
* Set request Method POST|GET|DELETE|PUT
*
* @param method {String} Method Type
*/
Ajax.prototype.setMethod = function(method) {
this.method = method.toUpperCase();
};
/**
* Set Headers for request
*
* @param headers {Object} Header key value proparties
*/
Ajax.prototype.setRequestHeader = function(headers) {
var key, value, _ref;
this.headers = headers;
_ref = this.headers;
for (key in _ref) {
value = _ref[key];
this.xmlhttp.setRequestHeader(key, value);
}
};
/**
* Prepare ajax request set url, data headers and query data
*
* @param url {String} Requested url
* @param [data] {Object} Query data
*/
Ajax.prototype.open = function(url, data) {
this.data = this.toQuery(data);
if (this.method === "GET") {
this.url = "" + url + (data ? (__indexOf.call(url, "?") >= 0 ? "&" : "?") : "") + (encodeURI(this.data));
}else{
this.url = url;
}
this.xmlhttp.open(this.method, this.url, true);
this.setRequestHeader({
"X-Requested-With": "XMLHttpRequest"
});
if (this.method === "POST") {
this.setRequestHeader({
"Content-type": "application/x-www-form-urlencoded"
});
}
};
/**
* Create query string form object
* Example:
* var query = {
* data: "data",
* options: {
* value1: "1",
* value2: "2"
* }
* }
* toQuery(query) -> "data=data&options[value1]=1&options[value2]=2"
*
* @param data {Object} Query data
* @param [deep] {String} Deep property
* @returns {string} Query String
*/
Ajax.prototype.toQuery = function(data, deep) {
var key, value;
return ((function() {
var _results;
_results = [];
for (key in data) {
value = data[key];
_results.push(typeof value === "object" ? this.toQuery(value, key) : !deep ? "" + key + "=" + value : "" + deep + "[" + key + "]=" + value);
}
return _results;
}).call(this)).join("&");
};
/**
* Send request if method is POST send data in form-data
*/
Ajax.prototype.send = function() {
if (this.method === "POST") {
this.xmlhttp.send(this.data);
} else {
this.xmlhttp.send();
}
};
return Ajax;
})(); | JavaScript |
/**
* Class Style
* this class is used to create css rules
*/
Style = (function () {
/**
* Style constructor
* @constructor
*/
function Style() {
this.styles = document.styleSheets;
this.style = this.styles[this.styles.length-1];
}
/**
* Create rule string form object and selector
* @param selector {String} CSS selector
* @param rule {Object} css rules
* @returns {string} string rule
*/
Style.prototype.createRule = function(selector, rule){
return selector+" "+JSON.stringify(rule).replace(/["']/g, " ").replace(/,/g, ";");
};
/**
* Add rule in to style
* @param selector {String} CSS selector
* @param rule {Object} css rules
* @returns {Number} index of rule
*/
Style.prototype.addRule = function(selector, rule){
return this.style.insertRule(this.createRule(selector, rule), this.style.cssRules.length);
};
/**
* Get rule by index
* @param index {Number} rule index
* @returns {CssRule|CSSRule}
*/
Style.prototype.getRule = function(index){
return this.style.cssRules[index];
};
/**
* Edit rule by index
* @param index {Number} index of edited rule
* @param rule {Object} new css rule
*/
Style.prototype.editRule = function(index, rule){
var cssSelector = this.getRule(index).selectorText;
this.style.removeRule(index);
this.style.insertRule(this.createRule(cssSelector, rule), index);
};
/**
* Remove Css rule
* @param index {Number} rule index
* @returns {*|void}
*/
Style.prototype.removeRule = function(index){
return this.style.removeRule(index);
};
return Style;
})(); | JavaScript |
/**
* Class View
* This class manipulate HTMLElement
* Example:
* //by html element id
* var element = new View("element-id");
* //by html node
* var element = new View(document.body);
*/
View = (function() {
/**
* This constructor get element by id or use already get and create classList object
* @param element {String|HTMLElement}
* @constructor
*/
function View(element) {
if (typeof element === "string") {
this.getById(element);
} else {
this.element = element;
}
this.childs = [];
if (this.element) {
this.classList = this.element.classList;
}
}
/**
* Method that get element by id and create classList
* @param id {String}
*/
View.prototype.getById = function(id) {
this.element = document.getElementById(id);
this.classList = this.element.classList;
};
/**
* Add css class to element or classes separated by spece(s)
* @param name {String} Css Class(es) Name
*/
View.prototype.addClass = function(name) {
var collection, item, _i, _len;
if (!this.classList) return this;
if (!name) return this;
name = name.replace(/^\s+|\s+$/g, '');
collection = name.split(/\s+/);
for (_i = 0, _len = collection.length; _i < _len; _i++) {
item = collection[_i];
this.classList.add(item);
}
return this;
};
/**
* Remove css class from element or classes separated by spece(s)
* @param name {String} Css Class(es) Name
*/
View.prototype.removeClass = function(name) {
var collection, item, _i, _len;
if (name) {
name = name.replace(/^\s+|\s+$/g, '');
}
collection = name.split(/\s+/);
if (this.classList) {
for (_i = 0, _len = collection.length; _i < _len; _i++) {
item = collection[_i];
try{
this.classList.remove(item);
}
catch(e){}
}
}
};
/**
* Check if this element already has css class or any of classes
* @param name {String} Css Class(es) Name
* @returns {boolean}
*/
View.prototype.hasClass = function(name) {
var collection, item, _i, _len,
has = false;
if (!this.classList) return;
if (!name) return;
name = name.replace(/^\s+|\s+$/g, '');
collection = name.split(/\s+/);
for (_i = 0, _len = collection.length; _i < _len; _i++) {
item = collection[_i];
has = this.classList.contains(item);
}
return has;
};
/**
* Get Closest by class name
* @param name {String} css class name
* @param el {HTMLElement} html element
* @returns {HTMLElement}
*/
View.prototype.closestByClassName = function(name, el) {
if (el == null) {
el = this.element;
}
if (el.classList.contains(name)) {
return el;
} else {
if (el.parentElement) {
return this.closestByClassName(name, el.parentElement);
}
}
};
/**
* Set or get attributes
* @param attrs {String|Object} name of attribute if we want to get attribute value or object if we want to set attribute
* @returns {*} Attribute value or false if we set
*/
View.prototype.attr = function(attrs) {
var attr;
if (typeof attrs === "string") {
if (this.element.hasOwnProperty(attr)) {
return this.element[attrs];
} else {
return this.element.getAttribute(attrs);
}
} else {
if (attrs instanceof Object) {
for (attr in attrs) {
if (this.element.hasOwnProperty(attr)) {
this.element[attr] = attrs[attr];
} else {
this.element.setAttribute(attr, attrs[attr]);
}
}
}
}
return false;
};
/**
* Set or get property
* @param props {String|Object} name of property if we want to get property value or object if we want to set property
* @returns {*} property value or false
*/
View.prototype.prop = function(props) {
var prop;
if (typeof props === "string") {
return this.element[props];
} else {
if (props instanceof Object) {
for (prop in props) {
this.element[prop] = props[prop];
}
}
}
return false;
};
/**
* Remove attribute by name
* @param attr {String} attribute name
*/
View.prototype.removeAttr = function(attr) {
if (this.element.hasOwnProperty(attr)) {
this.element[attr] = null;
} else {
this.element.removeAttribute(attr);
}
};
/**
* Get parent element
* @param ishtml {Boolean} if html or view
* @returns {HTMLElement|View}
*/
View.prototype.parent = function(ishtml){
if(ishtml){
return this.element.parentElement;
}else{
return new View(this.element.parentElement);
}
};
/**
* Get element or view by css selector
* @param selector {String} css selector
* @param html {Boolean} if html or view
* @returns {View|HTMLElement}
*/
View.prototype.select = function(selector, html){
var _el = this.element.querySelector(selector);
if(!html){
if(_el) _el = new View(_el);
}
return _el;
};
/**
* Get elements or views by css selector
* @param selector {String} css selector
* @param html {Boolean} if html or view
* @returns {Views|HTMLElement}
*/
View.prototype.selectAll = function(selector, html){
var _els;
if(html){
_els = this.element.querySelectorAll(selector);
}else{
_els = new Views(this.element.querySelectorAll(selector));
}
return _els;
};
/**
* Remove element from html
* @returns {*}
*/
View.prototype.remove = function(){
return this.parent(true).removeChild(this.element);
};
/**
* Append child to this element
* @param child {HTMLElement|View} child element or view
* @returns {View} child view
*/
View.prototype.append = function(child) {
this.childs.push(!(child instanceof View) ? new View(child) : child);
this.element.appendChild(child.element || child);
return this.childs[this.childs.length - 1];
};
/**
* Set or get inner html of this view
* @param [html] {String} string html or not if you want to get the html
* @returns {*}
*/
View.prototype.html = function(html) {
if(html) return this.element.innerHTML = html;
return this.element.innerHTML;
};
/**
* Set or get inner text of this view
* @param [text] {String} string text or not if you want to get the text
* @returns {*}
*/
View.prototype.text = function(text) {
if(text) return this.element.innerText = text;
return this.element.innerText;
};
/**
* Get all childrend html element
* @returns {HTMLElement[]} children
*/
View.prototype.childrens = function() {
return this.element.children;
};
/**
* Return if this element is in dom or is still not inserted
* @returns {boolean}
*/
View.prototype.inDOM = function() {
return !!this.element.parentElement;
};
/**
* Show element whit display or visibility
* @param [visibility] {Boolean} to use visibility or not
*/
View.prototype.show = function(visibility){
if(visibility){
this.style({visibility: ""});
}else{
this.style({display: ""});
}
};
/**
* Hide element whit display or visibility
* @param [visibility] {Boolean} to use visibility or not
*/
View.prototype.hide = function(visibility){
if(visibility){
this.style({visibility: "hidden"});
}else{
this.style({display: "none"});
}
};
/**
* Add event listener
* @param event {String} event name
* @param callback {Function} event callback
* @returns {*}
*/
View.prototype.addEvent = function(event, callback) {
if ("addEventListener" in window) {
return this.element.addEventListener(event, callback);
} else {
return this.element.attachEvent("on" + event, callback);
}
};
/**
* Remove event listener
* @param event {String} event name
* @param callback {Function} event callback
* @returns {*}
*/
View.prototype.removeEvent = function(event, callback) {
if ("removeEventListener" in window) {
return this.element.removeEventListener(event, callback);
} else {
return this.element.detachEvent("on" + event, callback);
}
};
/**
* Bind event with Touch
* @param event {String} event name
* @param callback {Function} event callback
* @param [bubble] {Boolean} to have bubble or not
* @returns {*}
*/
View.prototype.bind = function(event, callback, bubble) {
return Touch.observe(this.element, event, callback, bubble);
};
/**
* Un Bind event with Touch
* @param event {String} event name
* @param callback {Function} event callback
* @returns {*}
*/
View.prototype.unbind = function(event, callback) {
return Touch.stopObserving(this.element, event, callback);
};
/**
* Set or get html style
* @param styles {String|Object} string to get some value or object to set
* @returns {String} style value
*/
View.prototype.style = function(styles) {
var key;
if(styles instanceof String) return this.element.style[styles];
this.styles = styles;
for (key in this.styles) {
this.element.style[key] = this.styles[key];
}
};
return View;
})(); | JavaScript |
/**
* Project trunk.
* User: hp-stuff
* Date: 4/16/13
* Time: 2:01 PM
* To change this template use File | Settings | File Templates.
*/
DropDown = (function (_super) {
__extends(DropDown, _super);
function DropDown(view) {
var _this = this;
DropDown.__super__.constructor.call(this);
this.setContentView(view);
this.isOpen = false;
this.isClosed = true;
this.wrapper = new View("wrapper");
this.display = new Button(this.view.select(".display", true));
this.display.view.bind("touchstart", function(e){
_this.isClosed = !_this.isClosed;
});
this.display.setOnClickListener(function(e){
if(_this.isOpen){
_this.close();
}else{
_this.open();
}
});
this.setItemTemplate();
this.list = new List(this.view.select("ul"), this.itemTemplate);
this.list.setOnItemSelectedListener(function(){
_this.setSelected(this);
});
this.list.view.hide();
}
DropDown.prototype.setItems = function(data){
this.list.setItems(data);
this.setSelected(this.list.items[0]);
};
DropDown.prototype.setSelected = function(item){
var _selected = this.list.view.select(".selected");
if(_selected) _selected.removeClass("selected");
(this.selected = item).view.addClass("selected");
this.setDisplayText(this.selected.data);
if(this.selectedListener) this.selectedListener.call(this.selected);
this.close();
};
DropDown.prototype.setOnItemSelectedListener = function(listener){
this.selectedListener = listener;
};
DropDown.prototype.setItemTemplate = function(id){
this.itemTemplate = id || "<%=obj%>"
};
DropDown.prototype.setDisplayText = function(text){
this.display.view.html(text);
};
DropDown.prototype.getSelectedItem = function(){
return this.selected;
};
DropDown.prototype.open = function(){
var _this = this;
this.isOpen = true;
this.list.view.show();
this.wrapper.bind("touchstart", function(e){
if(!_this.isClosed) _this.close();
});
};
DropDown.prototype.close = function(){
var _this = this;
this.isOpen = false;
setTimeout(function(){
_this.list.view.hide();
},200);
this.wrapper.unbind("touchstart");
};
return DropDown;
})(Base); | JavaScript |
Application = (function() {
function Application() {
var _this = this;
this.pages = {};
this.mobile = new Mobile();
this.bootstrap = new Bootstrap();
this.config = new Config();
this.mobile.setOnLoadListener(function(){
_this.mobile.cacheupdated = true;
_this.load();
});
this.mobile.setOnCachedListener(function(e) {
_this.load();
});
this.mobile.setOnCacheUpdatedListener(function(e) {
_this.load();
});
this.mobile.setOnCacheLoadedListener(function(e) {
_this.load();
});
try{
Touch.android = this.mobile.checker.get().android || true;
}catch (e){
throw e;
}
}
Application.prototype.setOnLoadListener = function(listener) {
this.loadListener = listener;
};
Application.prototype.load = function() {
var _this = this;
this.config.setOnLoadListener(function() {
if(_this.loadListener)
_this.loadListener.call(this);
_this.setTitle(_this.config.data.title);
_this.setVersion(_this.config.data.version);
_this.createPages(_this.config.data.pages);
});
this.bootstrap.setOnReadyListener(function() {
_this.config.load(_this.mobile.cacheupdated);
});
this.bootstrap.load(this.mobile.cacheupdated);
};
Application.prototype.setTitle = function(text){
this._title = document.title = text;
};
Application.prototype.getTitle = function(){
return this._title;
};
Application.prototype.setVersion = function(version){
this.mobile.wrapper.attr({"data-version": this._version = version});
};
Application.prototype.getVersion = function(){
return this._version;
};
Application.prototype.createPages = function(pages){
var _i, _page, page;
for(_i = 0; _i < pages.length; _i++){
_page = pages[_i];
page = this.pages[_page.name] = new window[_page["class"]](this);
if(_page.visible && _page.visible === true){
if(_page.current && _page.visible === true){
page.show();
}else{
(this._currentPage = page).show();
}
}
}
};
/**
* Show page
* @param intent {Intent}
*/
Application.prototype.showPage = function(intent){
var _name = intent.getName(),
_translation = intent.getAnimation();
if(this._currentPage = this.pages[_name]) {
this._currentPage.setAnimation(_translation);
this._currentPage.show(intent);
}
};
/**
* Hide page
* @param intent {Intent}
*/
Application.prototype.hidePage = function(intent){
var _name = intent.getName(),
_translation = intent.getAnimation(),
page = this.pages[_name];
if(page && page === this._currentPage) this._currentPage = null;
page.setAnimation(_translation);
page.hide(intent);
};
Application.prototype.getCurrentPage = function(){
return this._currentPage;
};
return Application;
})();
| JavaScript |
/**
* Class Mobile
* this class is used to manage based function
* like screen size, orientation, some windows events and others
*/
Mobile = (function() {
/**
* Mobile constructor
* @param application {Application} application instance
* @constructor
*/
function Mobile(application) {
var _this = this;
this.application = application;
this.window = new View(window);
this.body = new View(document.body);
this.head = new View(document.head);
this.contents = new Views(".content");
this.wrapper = new View("wrapper");
this.checker = new Checker;
this.cacheupdated = false;
this.window.addEvent('load', function() {
return _this.documentLoaded();
});
this.window.addEvent("orientationchange", function() {
return _this.documentRotate();
});
this.window.addEvent("resize", function() {
if (_this.checker.types.iphone) {
_this.fixiPhoneLandscape();
}
return _this.documentRotate();
});
if ("applicationCache" in window) {
window.applicationCache.addEventListener('updateready', function(e) {
_this.cacheupdated = true;
if(_this.cacheUpdatedListener)
_this.cacheUpdatedListener.call(_this,e);
});
window.applicationCache.addEventListener('noupdate', function(e) {
if(_this.cacheLoadedListener)
_this.cacheLoadedListener.call(_this, e);
});
window.applicationCache.addEventListener('cached', function(e) {
if(_this.cachedListener)
_this.cachedListener.call(_this, e);
});
}
this.size = {};
}
/**
* Set on chache updated listener
* @param listener {Function} chache updated listener
*/
Mobile.prototype.setOnCacheUpdatedListener = function(listener) {
this.cacheUpdatedListener = listener;
};
/**
* Set on chache loaded listener
* @param listener {Function} chache loaded listener
*/
Mobile.prototype.setOnCacheLoadedListener = function(listener) {
this.cacheLoadedListener = listener;
};
/**
* Set on chached listener
* @param listener {Function} chached listener
*/
Mobile.prototype.setOnCachedListener = function(listener) {
this.cachedListener = listener;
};
/**
* Create Metatag based on platform
*/
Mobile.prototype.createMethaTag = function() {
var content;
this.meta = new View(document.getElementsByName('viewport')[0] || document.createElement('meta'));
this.meta.attr({
name: "viewport"
});
content = !this.checker.types.iphone5 ? "width=device-width, " : "";
content += "target-densityDpi=160, ";
content += "initial-scale=1.0, minimum-scale=1.0, maximum-scale=1, user-scalable=no";
this.meta.attr({
content: content
});
if (!this.meta.inDOM()) {
this.head.append(this.meta);
}
};
/**
* Set size and remove bar
* @param layout {String} layout orientation
* @param time {Number} set timeout time
*/
Mobile.prototype.removeBar = function(layout, time) {
this.layout = layout;
if (this.checker.types.iphone && !this.checker.types.fullscreen) {
if (this.layout && this.layout === "landscape") {
this.wrapper.style({
height: "" + (window.innerHeight < this.size.width ? this.size.width - 52 : this.size.width) + "px"
});
this.wrapper.style({
width: "" + this.size.height + "px"
});
} else {
this.wrapper.style({
height: "" + (this.size.height - 64) + "px"
});
this.wrapper.style({
width: "" + this.size.width + "px"
});
}
}
if (this.checker.types.android && !this.checker.types.chrome) {
if (this.layout && this.layout === "landscape") {
this.wrapper.style({
height: "" + (this.size.width - (12 * this.size.dpi)) + "px"
});
this.wrapper.style({
width: "" + this.size.height + "px"
});
} else {
this.wrapper.style({
height: "" + (this.size.height - (12 * this.size.dpi)) + "px"
});
this.wrapper.style({
width: "" + this.size.width + "px"
});
}
}
this.hideBar(time);
};
/**
* Hide bar by scrolling on top after some time
* @param time {Number} hide after this time
*/
Mobile.prototype.hideBar = function(time) {
setTimeout(function() {
window.scrollTo(0, 0);
}, time || 50);
};
/**
* Fix iPhone landscape fullscreen
*/
Mobile.prototype.fixiPhoneLandscape = function() {
this.removeBar(this.layout);
};
/**
* Detect orientation
* @returns {boolean} if orientation was change or not
*/
Mobile.prototype.detectOrientation = function() {
var _layout = this.layout;
if ("orientation" in window) {
this.layout = Math.abs(window.orientation) ? "landscape" : "portrait";
} else {
this.layout = window.outerWidth > window.outerHeight ? "landscape" : "portrait";
}
if(_layout === this.layout) return false;
this.body.removeClass("lanscape portrait");
this.body.addClass(this.layout);
return true;
};
/**
* Set on load listener
* @param listener {Functon} load listener
*/
Mobile.prototype.setOnLoadListener = function(listener) {
this.loadListener = listener;
};
/**
* On document loaded
*/
Mobile.prototype.documentLoaded = function() {
this.createMethaTag();
if (this.checker.types.iphone) {
this.size.width = Math.min(window.screen.width, window.screen.height);
this.size.height = Math.max(window.screen.width, window.screen.height);
this.body.addClass('iphone');
} else {
this.size.width = Math.round((Math.min(window.screen.width, window.screen.height)) / window.devicePixelRatio);
this.size.height = Math.round((Math.max(window.screen.width, window.screen.height)) / window.devicePixelRatio);
this.size.dpi = window.devicePixelRatio;
this.body.addClass('android');
}
this.detectOrientation();
if (this.checker.types.iphone && this.layout === "landscape") {
this.fixiPhoneLandscape();
}
this.removeBar(this.layout);
if(this.loadListener) this.loadListener.call(this);
};
/**
* On document rotate
*/
Mobile.prototype.documentRotate = function() {
if(this.detectOrientation()) this.removeBar(this.layout, this.checker.types.android ? 1000 : 50);
};
/**
* Class Checker
* is user to check device and device version
*/
Checker = (function() {
/**
* Checker constructor
* @constructor
*/
function Checker() {
this.ua = navigator.userAgent;
this.types = {};
this.types.iphone = this.ua.match(/(iPhone|iPod)/);
this.types.iphone5 = this.types.iphone && window.screen.height === 568;
this.types.ipad = this.ua.match(/iPad/);
this.types.chrome = this.ua.match(/Chrome/);
this.types.android = this.ua.match(/Android ([0-9](.[0-9])?)/);
this.types.ie = this.ua.match(/MSIE/);
this.types.fullscreen = navigator.standalone;
}
/**
* Get all device types
* @returns {*}
*/
Checker.prototype.get = function() {
return this.types;
};
return Checker;
})();
return Mobile;
})(); | JavaScript |
/**
* Class Animation craete css class with animatoin.
* Example:
* var animation = new Animation('slide-down', 100, 'slidedown', 'linear');
*/
Animation = (function () {
/**
*
* @param name {String} Css Class name
* @param time {Number} Animation time in ms
* @param [animationName] {String} Animation Name
* @param [timeFunction] {String} Animation timing function linear|easing or bezier
* @constructor
*/
function Animation(name, time, animationName, timeFunction) {
this.style = new Style();
this.setName(name);
this.setAnimationName(animationName);
this.setFunction(timeFunction);
this.setTime(time);
}
/**
* Create Css object rule
* @returns {Object}
*/
Animation.prototype.createRule = function(){
var rule = {};
if(this.animationName !== void 0) rule["-webkit-animation-name"] = this.animationName;
if(this.time !== void 0) rule["-webkit-animation-duration"] = this.time+"ms";
if(this.timeFunction !== void 0) rule["-webkit-animation-timing-function"] = this.timeFunction;
return rule;
};
/**
* Set Animation css class name
* @param name {String} Css Class name
*/
Animation.prototype.setName = function(name){
this.name = name;
this.ruleIndex = this.style.addRule("."+name, this.createRule());
};
/**
* Set Animation Name
* @param name {String} css animation name
*/
Animation.prototype.setAnimationName = function(name){
this.animationName = name;
this.style.editRule(this.ruleIndex, this.createRule());
};
/**
* Set Animation Timing Function
* @param [timeFunction] {String} Timing Function
*/
Animation.prototype.setFunction = function(timeFunction){
this.timeFunction = timeFunction || "linear";
this.style.editRule(this.ruleIndex, this.createRule());
};
/**
* Set Animation Time in ms
* @param time {Number} Animation Time
*/
Animation.prototype.setTime = function(time){
this.time = time;
this.style.editRule(this.ruleIndex, this.createRule());
};
/**
* Remove Animation Css Rule
* @returns {*}
*/
Animation.prototype.remove = function(){
return this.style.removeRule(this.ruleIndex);
};
return Animation;
})(); | JavaScript |
/**
* Checks if an element has a class name
* @param {String} The class name
* @return {Boolean}
*/
Element.prototype.hasClassName = document.documentElement.classList ? function(className) {
return this.classList.contains(className);
} : function(className) {
var elementClassName = this.className;
if (elementClassName.length === 0) {
return false;
}
if (elementClassName === className) {
return true;
}
var regexp = new RegExp('(^|\\s+)' + className + '(\\s+|$)');
return regexp.test(elementClassName);
};
Element.prototype.addClassName = document.documentElement.classList ? function(className) {
return this.classList.add(className);
} : function(className) {
var elementClassName = this.className;
if (elementClassName.length === 0) {
return false;
}
if (elementClassName === className) {
return true;
}
var regexp = new RegExp('(^|\\s+)' + className + '(\\s+|$)');
return regexp.test(elementClassName);
};
Element.prototype.removeClassName = document.documentElement.classList ? function(className) {
return this.classList.remove(className);
} : function(className) {
var elementClassName = this.className;
if (elementClassName.length === 0) {
return false;
}
if (elementClassName === className) {
return true;
}
var regexp = new RegExp('(^|\\s+)' + className + '(\\s+|$)');
return regexp.test(elementClassName);
};
// these need special handling
window.dataset = {};
document.dataset = {};
document.documentElement.dataset = {};
/**
* Unique id generator
*/
GUID = {};
/**
* Returns a new unique id
* @return {String}
*/
GUID.guid = (function() {
function s4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return function() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
};
})();
/**
* Returns a GUID for element
* @param {Element} The element
* @return {String}
*/
GUID.getGUIDForElement = function(element) {
if (element === document || element === document.documentElement) {
return '!!document';
}
if (element === window) {
return '!!window';
}
if (!element.dataset['guid']) {
element.dataset['guid'] = element.id || GUID.guid();
}
element.dataset
return element.dataset['guid'];
};
/**
* Touch events layer
*/
Touch = {};
Touch.android = true;
/**
* Whether this is a touch-capable browser or not
*/
Touch.touch = false;
/**
* Whether the address bar is hidden
*/
Touch.addressBarHidden = false;
/**
* 'touchstart' client X coordinate
*/
Touch.startClientX = 0;
/**
* 'touchstart' client Y coordinate
*/
Touch.startClientY = 0;
/**
* 'touchstart' screen X coordinate
*/
Touch.startScreenX = 0;
/**
* 'touchstart' screen Y coordinate
*/
Touch.startScreenY = 0;
/**
* Moved
*/
Touch.moved = false;
/**
* The element the action started on
*/
Touch.target = null;
/**
* Previous target
*/
Touch.prevTarget = null;
/**
* Event callbacks
*/
Touch.boundEventCallbacks = {};
/**
* Events that we handle
*/
Touch.handledEvents = {
'touchstart' : true,
'touchmove' : true,
'touchend' : true,
'focus' : true,
'blur' : true,
'change' : true,
'click' : true
};
/**
* Initializer
*/
Touch.initialize = function() {
if (!('ontouchstart' in window)) {
// not touch - do nothing
return;
}
this.touch = true;
// ugly hack - defer window.alert so it doesn't backfire [touchStart event]
/* window.oldAlert = window.alert;
window.alert = function(message) {
setTimeout(function() {
window.oldAlert(message);
}, 0);
};
*/
var that = this;
// subscribe for touchStart, touchMove, touchCancel & touchEnd events
window.addEventListener('touchstart', function(event) {
that.eventStart(event.target, event);
});
window.addEventListener('touchmove', function(event) {
that.eventMove(event.target, event);
});
window.addEventListener('touchend', function(event) {
that.eventEnd(event.target, event);
});
window.addEventListener('touchcancel', function(event) {
that.eventCancel(event.target, event);
});
};
/**
* Handles touchStart event
* @param {Element} The target element
* @param {Event} The event object
*/
Touch.eventStart = function(target, event) {
this.startClientX = event.touches[0].clientX;
this.startClientY = event.touches[0].clientY;
this.startScreenX = event.touches[0].screenX;
this.startScreenY = event.touches[0].screenY;
this.moved = false;
if (this.target != target) {
this.prevTarget = this.target;
if (target.tagName == 'LABEL') {
var associatedElement = document.getElementById(target.htmlFor);
if (associatedElement) {
target = associatedElement;
}
}
this.target = target;
this.fire(this.target, 'touchstart', event);
if (this.android && this.isActivatable(target)) {
this.pseudoActivate(target);
}
if (!this.isScrollable(target) || !this.isInput(target)) {
//event.preventDefault();
event.stopPropagation();
}
}
};
/**
* Handles touchMove event
* @param {Element} The target element
* @param {Event} The event object
*/
Touch.eventMove = function(target, event) {
var
clientX = event.touches[0].clientX,
clientY = event.touches[0].clientY,
screenX = event.touches[0].screenX,
screenY = event.touches[0].screenY;
if (Math.abs(clientX - this.startClientX) > 10 || Math.abs(clientY - this.startClientY) > 10) {
this.moved = true;
target = document.elementFromPoint(clientX, clientY);
if (!target || (target.nodeType == 3 && !(target = target.parentNode))) {
return;
}
this.fire(target, 'touchmove', event);
}
if (this.isScrollable(target)) {
// here comes trouble..
var container = target;
while (container && container != document.body && !container.hasClassName('content') && !container.hasClassName('scrollable')) {
container = container.parentNode;
}
if (!container) {
return;
}
var
top = container.scrollTop,
bottom = container.scrollHeight - container.scrollTop - container.offsetHeight,
dirX = Math.abs(screenX - this.startScreenX),
dirY = Math.abs(screenY - this.startScreenY);
if (top == 0 && screenY > this.startScreenY) {
//event.preventDefault();
if (dirX > dirY) {
container.scrollTop = 1;
} else {
event.preventDefault();
}
} else if (bottom == 0 && screenY < this.startScreenY) {
//event.preventDefault();
if (dirX > dirY) {
container.scrollTop = container.scrollHeight - container.offsetHeight - 1;
} else {
event.preventDefault();
}
}
} else {
event.preventDefault();
event.stopPropagation();
}
};
/**
* Handles touchEnd event
* @param {Element} The target element
* @param {Event} The event object
*/
Touch.eventEnd = function(target, event) {
this.fire(this.target, "touchend", event);
if (this.moved) {
target = document.elementFromPoint(event.changedTouches[0].clientX, event.changedTouches[0].clientY);
if (!target || (target.nodeType == 3 && !(target = target.parentNode))) {
return;
}
if (target.tagName == 'LABEL') {
var associatedElement = document.getElementById(target.htmlFor);
if (associatedElement) {
target = associatedElement;
}
}
if (target != this.target || this.android || this.isScrollable(target)) {
if (this.android) {
this.pseudoDeactivate(this.target);
}
this.target = null;
return;
}
}
if (this.target != this.prevTarget) {
if (this.isInput(this.prevTarget)) {
this.prevTarget.blur();
}
if (this.isInput(this.target)) {
//this.target.focus();
return;
}
if (this.target != document.activeElement && document.activeElement.blur) {
document.activeElement.blur();
}
}
if (this.isClickable(this.target)) {
// if (document.activeElement && document.activeElement.blur) {
// document.activeElement.blur();
// }
if (this.android) {
this.pseudoDeactivate(this.target);
}
this.fire(this.target, 'click', event);
this.target = null;
event.preventDefault();
event.stopPropagation();
// var that = this;
// setTimeout(function() {
// that.target = null;
// }, 0)
}
};
/**
* Handles touchCancel event
* @param {Element} The target element
* @param {Event} The event object
*/
Touch.eventCancel = function(target, event) {
if (this.android) {
this.pseudoDeactivate(target);
}
this.target = null;
};
/**
* Checks if element is an input
* @param {Element} The element
* @return {Boolean}
*/
Touch.isInput = function(element) {
if (element && (element.tagName == 'TEXTAREA' || element.tagName == 'SELECT' || (element.tagName == 'INPUT' && element.type != 'checkbox' && element.type != 'radio' && element.type != 'button') || (element.contentEditable == 'true'))) {
return true;
}
return false;
};
/**
* Checks if element is clickable
* @param {Element} The element
* @return {Boolean}
*/
Touch.isClickable = function(element) {
var docBody = document.body;
do {
if(!element) return;
if (((element.hasClassName('action') || element.dataset['action']) && element.tagName != 'FORM') || element.hasOwnProperty("onclick") || element.tagName == 'BUTTON' || (element.tagName == 'INPUT' && element.type == 'button')) {
return true;
}
element = element.parentNode;
} while (element && element != docBody && element != document);
return false;
};
/**
* Checks if element is scrollable
* @param {Element} The element
* @return {Boolean}
*/
Touch.isScrollable = function(element) {
var docBody = document.body;
if(this.android) return false;
do {
if(!element) return;
if (element.hasClassName('content') || element.hasClassName('scrollable')) {
return true;
}
element = element.parentNode;
} while (element && element != docBody && element != document);
return false;
};
/**
* Checks if element needs .pseudo-active
* @param {Element} The element
* @return {Boolean}
*/
Touch.isActivatable = function(element) {
var docBody = document.body;
do {
if(!element) return;
if (element.hasClassName('activatable')) {
return true;
}
element = element.parentNode;
} while (element && element != docBody && element != document && element != document);
return false;
};
/**
* Adds the .pseudo-active class
* @param {Element} The element
*/
Touch.pseudoActivate = function(element) {
var docBody = document.body;
do {
if(!element) return;
if (element.hasClassName('activatable')) {
element.addClassName('pseudo-active');
}
element = element.parentNode;
} while (element && element != docBody && element != document);
};
/**
* Removes the .pseudo-active class
* @param {Element} The element
*/
Touch.pseudoDeactivate = function(element) {
var docBody = document.body;
do {
if(!element) return;
if (element.hasClassName('pseudo-active')) {
element.removeClassName('pseudo-active');
}
element = element.parentNode;
} while (element && element != docBody && element != document);
};
/**
* Hides the address bar
*/
Touch.hideAddressBar = function() {
if (this.touch && !Base.Browser.PhoneGap && Base.Browser.iPhone && !Base.Browser.Fullscreen && !this.addressBarHidden) {
var hideAddressBar = function() {
switch (window.orientation) {
case -90:
case 90:
document.body.style.height = window.screen.width + 'px';
$('wrapper').style.height = (window.screen.width - 60) + 'px';
break;
default:
document.body.style.height = window.screen.height + 'px';
$('wrapper').style.height = (window.screen.height - 60) + 'px';
break;
}
window.scrollTo(0, 1);
};
this.addressBarHidden = true;
window.addEventListener('orientationchange', hideAddressBar);
setTimeout(hideAddressBar, 0);
}
};
/**
* "Fires" an event for an element
* @param {Element} Element
* @param {String} Event name
* @param {Event} DOM event
*/
Touch.fire = function(element, eventName, domEvent) {
var guid = GUID.getGUIDForElement(element);
if (!guid) {
return false;
}
if (this.handledEvents[eventName]) {
// rewrite the stopPropagation() method so we handle it ourselves
domEvent.nativeStopPropagation = domEvent.stopPropagation;
domEvent.stopPropagation = function() {
this.propagationStopped = true;
};
// execute events from the chain
if (this.boundEventCallbacks[guid] && this.boundEventCallbacks[guid][eventName]) {
for (var index = 0, length = this.boundEventCallbacks[guid][eventName].length; index < length; ++index) {
domEvent.propagationStopped = false;
try {
this.boundEventCallbacks[guid][eventName][index](domEvent);
} catch (e) {
}
}
}
// propagate
if (!domEvent.propagationStopped && element.parentNode) {
this.fire(element.parentNode, eventName, domEvent);
}
} else {
// TODO: find out what to do here...
}
};
/**
* Adds an event responder to element's event chain
* @param {Element} The element
* @param {String} Event name
* @param {Function} Callback
* @param {Boolean} Bubble bobble
*/
Touch.observe = function(element, eventName, callback, bubbleBobble) {
if (typeof element == 'string') {
element = document.getElementById(element);
}
if (this.handledEvents[eventName]) {
var guid = GUID.getGUIDForElement(element);
if (!this.boundEventCallbacks[guid]) {
this.boundEventCallbacks[guid] = {};
}
if (!this.boundEventCallbacks[guid][eventName]) {
this.boundEventCallbacks[guid][eventName] = [];
}
this.boundEventCallbacks[guid][eventName][bubbleBobble ? 'unshift' : 'push'](callback);
} else {
element.addEventListener(eventName, callback, bubbleBobble || false);
}
};
/**
* Removes an event responder from element's event chain
* @param {Element} The element
* @param {String} Event name
* @param {Function} Callback
*/
Touch.stopObserving = function(element, eventName, callback) {
if (typeof element == 'string') {
element = document.getElementById(element);
}
if (this.handledEvents[eventName]) {
var guid = element.dataset['guid'];
if (this.boundEventCallbacks[guid] && this.boundEventCallbacks[guid][eventName]) {
if (callback) {
this.boundEventCallbacks[guid][eventName].remove(callback);
} else {
this.boundEventCallbacks[guid][eventName] = [];
}
}
} else {
element.removeEventListener(eventName, callback);
}
};
// initialize ourselves even before we load :d
Touch.initialize(); | JavaScript |
var __indexOf, __hasProp, __extends, __date;
__indexOf = [].indexOf || function(item) {
for (var i = 0, l = this.length; i < l; i++) {
if (i in this && this[i] === item)
return i;
}
return -1;
};
__hasProp = {}.hasOwnProperty;
__extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key))
child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
}; | JavaScript |
var compressor = require('node-minify'),
fs = require("fs"),
express = require("express"),
crypto = require("crypto"),
ejs = require('ejs'),
path = require('path'),
mime = require('mime'),
app = express(),
classes_directory = "../src/classes",
libs_directory = "../src/libs",
style_file = "../src/assets/css/style.css";
app.use(express.bodyParser());
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.engine('html', ejs.renderFile);
var files = [],
files_md5 = [],
files_for_compress = [];
function generatePackage(files_c, callback){
compressFiles(files_c, callback);
}
function compressFiles(files_c, callback){
var tmp = files_for_compress.slice(0), //create new array with all libs
step = 1;
//push Base.js on top after libs
tmp.push(classes_directory+"/View.js");
tmp.push(classes_directory+"/Views.js");
tmp.push(classes_directory+"/Base.js");
tmp.push(classes_directory+"/Mobile.js");
//add all classes selected form user
files_c.forEach(function(item, index, files){
//skip Base.js
if(["Base.js", "Mobile.js", "View.js", "Views.js", "Application.js"].indexOf(item) < 0){
tmp.push(classes_directory+"/"+item);
}
});
tmp.push(classes_directory+"/Application.js");
//combine and minify all files
new compressor.minify({
type: "gcc",
options: [
"--language_in", "ECMASCRIPT5"
],
fileIn: tmp,
fileOut: "mini/androjs-min-0.1"+Date.now()+".js",
callback: function(err){
var _this = this, md5sum,
shasum = crypto.createHash('md5'),
file_path = "";
if(err) {
console.log(err);
}
else {
console.log('File "' + this.fileOut + '" is READY');
//read stream of generated file
fs.createReadStream(this.fileOut, {encoding: 'binary'})
.on('data', function(data){
shasum.update(data);
})
.on('end', function(){
//get file md5
md5sum = shasum.digest('hex');
file_path = _this.fileOut;
//check this file md5 sum in already generated files
files_md5.forEach(function(item){
//if we have this md5 sum use already generated file
if(item.md5 === md5sum){
file_path = item.path;
fs.unlink(_this.fileOut); //remove this new generated file because we already have one
return;
}
});
//Push this file and md5 sum if we don't have this file generated
if(file_path === _this.fileOut){
files_md5.push({ md5 : md5sum, path: file_path});
}
//Return property file path
callback(file_path);
});
}
}
});
}
//Delete all generated files on server restart
fs.readdir("mini", function(err, files){
files.forEach(function(file){
fs.unlink("mini/"+file);
});
});
//Get all classes files
fs.readdir(classes_directory, function(err, fiels){
files = fiels;
console.log(files);
});
//Get all libs files
fs.readdir(libs_directory, function(err, fiels){
files_for_compress = fiels;
files_for_compress.forEach(function(item, index){
files_for_compress[index] = libs_directory+"/"+item;
})
});
app.get('/', function(req, res){
res.render('index.html', { files: files })
});
app.post('/generate_package', function(req, res){
generatePackage(req.body.files, function(file){
var filename = path.basename(file);
//get file name and send to user
res.send(filename);
});
});
app.get('/get_file/:filename', function(req, res){
var filename = req.params.filename,
file = "mini/"+req.params.filename,
mimetype = mime.lookup(filename);
res.setHeader('Content-disposition', 'attachment; filename=' + file);
res.setHeader('Content-type', mimetype);
//download requested file
var filestream = fs.createReadStream(file);
filestream.pipe(res);
});
app.listen(3000); | JavaScript |
/**
* Class Ajax
* This class is used to create a ajax requests
*
* Example:
*
* var ajax = new Ajax();
* ajax.open("http://api.com/test.json");
* ajax.onSuccess = function(data){
* //data.status -> "success"
* //data.data -> result form server
* };
* ajax.onError = function(data){
* //data.status -> "error"
* //data.data -> null
* };
* ajax.send();
*/
Ajax = (function() {
/**
* Class Ajax constructor
*
* @constructor
*/
function Ajax() {
var _this = this;
this.xmlhttp = (typeof window.createRequest === "function" ? window.createRequest() : void 0) || (XMLHttpRequest ? new XMLHttpRequest() : void 0);
this.xmlhttp.onreadystatechange = function() {
if (_this.xmlhttp.readyState !== 4) {
return void 0;
}
if (!(_this.xmlhttp.status === 200 || _this.xmlhttp.status === 304)) {
if(_this.successListener)
_this.successListener.call(_this, {
status: _this.xmlhttp.status,
data: {}
});
}
if (_this.xmlhttp.responseText) {
if(_this.successListener)
try{
_this.successListener.call(_this, {
status: "success",
data: JSON.parse(_this.xmlhttp.responseText)
});
}catch (e){
_this.successListener.call(_this, {
status: "success",
data: _this.xmlhttp.responseText
});
}
}
};
if ('onerror' in this.xmlhttp) {
this.xmlhttp.onerror = function() {
if(_this.errorListener)
_this.errorListener.call(this, {
status: 'error',
data: null
});
};
}
this.method = "GET";
}
/**
* Set On Success Listener this event will be fired when ajax return result
*
* @param listener {Function} Listener Function
*/
Ajax.prototype.setOnSuccessListener = function(listener) {
if(!(listener instanceof Function)) throw "listener is not a fucntion.";
this.successListener = listener;
};
/**
* Set On Success Listener this event will be fired when ajax return result
*
* @param listener {Function} Listener Function
*/
Ajax.prototype.setOnErrorListener = function(listener) {
if(!(listener instanceof Function)) throw "listener is not a fucntion.";
this.errorListener = listener;
};
/**
* Set request Method POST|GET|DELETE|PUT
*
* @param method {String} Method Type
*/
Ajax.prototype.setMethod = function(method) {
this.method = method.toUpperCase();
};
/**
* Set Headers for request
*
* @param headers {Object} Header key value proparties
*/
Ajax.prototype.setRequestHeader = function(headers) {
var key, value, _ref;
this.headers = headers;
_ref = this.headers;
for (key in _ref) {
value = _ref[key];
this.xmlhttp.setRequestHeader(key, value);
}
};
/**
* Prepare ajax request set url, data headers and query data
*
* @param url {String} Requested url
* @param [data] {Object} Query data
*/
Ajax.prototype.open = function(url, data) {
this.data = this.toQuery(data);
if (this.method === "GET") {
this.url = "" + url + (data ? (__indexOf.call(url, "?") >= 0 ? "&" : "?") : "") + (encodeURI(this.data));
}else{
this.url = url;
}
this.xmlhttp.open(this.method, this.url, true);
this.setRequestHeader({
"X-Requested-With": "XMLHttpRequest"
});
if (this.method === "POST") {
this.setRequestHeader({
"Content-type": "application/x-www-form-urlencoded"
});
}
};
/**
* Create query string form object
* Example:
* var query = {
* data: "data",
* options: {
* value1: "1",
* value2: "2"
* }
* }
* toQuery(query) -> "data=data&options[value1]=1&options[value2]=2"
*
* @param data {Object} Query data
* @param [deep] {String} Deep property
* @returns {string} Query String
*/
Ajax.prototype.toQuery = function(data, deep) {
var key, value;
return ((function() {
var _results;
_results = [];
for (key in data) {
value = data[key];
_results.push(typeof value === "object" ? this.toQuery(value, key) : !deep ? "" + key + "=" + value : "" + deep + "[" + key + "]=" + value);
}
return _results;
}).call(this)).join("&");
};
/**
* Send request if method is POST send data in form-data
*/
Ajax.prototype.send = function() {
if (this.method === "POST") {
this.xmlhttp.send(this.data);
} else {
this.xmlhttp.send();
}
};
return Ajax;
})(); | JavaScript |
/*
Copyright 2011 Johan Maasing
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
function SK8RBotActor(box2dentities) {
if (!box2dentities) {
throw "SK8RBotActor must have Box2D entities" ;
}
this.box2dentities = box2dentities ;
this.neutralArmAngle = 1 ; // 57 degrees
this.neutralFootDistance = box2dentities.rightFootJoint.GetLowerLimit() +
(box2dentities.rightFootJoint.GetUpperLimit() - box2dentities.rightFootJoint.GetLowerLimit()) / 2 ;
this.rightArmDesiredAngle = this.neutralArmAngle ;
this.leftArmDesiredAngle = this.neutralArmAngle ;
this.leftFootDesiredTranslation = this.neutralFootDistance ;
this.rightFootDesiredTranslation = this.neutralFootDistance ;
this.renderer = new SK8RBotActorStateRenderer(this);
}
SK8RBotActor.prototype.step = function(timeSinceLastStep) {
var raj = this.box2dentities.rightArmBodyJoint;
var rajAngleError = raj.GetJointAngle() - this.rightArmDesiredAngle;
raj.SetMotorSpeed(-4 * rajAngleError) ;
var laj = this.box2dentities.leftArmBodyJoint;
var lajAngleError = laj.GetJointAngle() + this.leftArmDesiredAngle;
laj.SetMotorSpeed(-4 * lajAngleError) ;
var lfj = this.box2dentities.leftFootJoint ;
var lfjTranslationError = lfj.GetJointTranslation() - this.leftFootDesiredTranslation ;
lfj.SetMotorSpeed(-1 * lfjTranslationError) ;
var rfj = this.box2dentities.rightFootJoint ;
var rfjTranslationError = rfj.GetJointTranslation() - this.rightFootDesiredTranslation ;
rfj.SetMotorSpeed(-1 * rfjTranslationError) ;
SK8RGameWorld.queueRenderer(this.renderer) ;
}
SK8RBotActor.prototype.onkeydown = function(event) {
if (event) {
switch (event.keyIdentifier) {
case "Right" :
this.leftFootDesiredTranslation += 0.1 ;
this.rightFootDesiredTranslation -= 0.1 ;
this.rightArmDesiredAngle -= 0.1 ;
this.leftArmDesiredAngle += 0.1 ;
break ;
case "Left" :
this.leftFootDesiredTranslation -= 0.1 ;
this.rightFootDesiredTranslation += 0.1 ;
this.rightArmDesiredAngle += 0.1 ;
this.leftArmDesiredAngle -= 0.1 ;
break ;
case "Down" :
case "Up" :
console.log(event.keyIdentifier);
break ;
case "Enter" :
SK8RGameWorld.reset() ;
break ;
}
}
return true ;
}
| JavaScript |
/*
Copyright 2011 Johan Maasing
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var SK8RGameWorld = (function() {
var debugDraw = false ;
var self = {} ;
var bodies ;
var joints ;
var world ;
var actors ;
var timerID ;
var lastFrameTime ;
var renderCallback = SK8RBindApply(self, renderFixtures) ;
var deck ;
var cameraFollowsDeck = false ;
var renderers = new Array() ;
function initFixtures(progressMeter) {
createDemoGround() ;
if (progressMeter) {
progressMeter.progress(0.4) ;
}
}
function initBodies(progressMeter) {
deck = new Sk8board({
scale : 2,
offset : {
x:1.2,
y:9.8
}
}) ;
if (progressMeter) {
progressMeter.progress(0.5) ;
}
var sk8rbody = createSK8RRobot({
offsetx : 1,
offsety : 6.5,
scale: 0.8
}) ;
var sk8rActor = new SK8RBotActor(sk8rbody) ;
self.addActor(sk8rActor) ;
window.onkeydown = SK8RBindApply(sk8rActor, sk8rActor.onkeydown) ;
if (progressMeter) {
progressMeter.progress(0.6) ;
}
}
function step() {
if (!world.IsLocked()) {
// Advance physics
world.Step(1 / 30, 10, 10);
// Let AI-actors advance
var now = new Date().getTime() ;
var timeSinceLastFrame = now - lastFrameTime ;
lastFrameTime = now ;
for (var n=0; n<actors.length; n++) {
actors[n].step(timeSinceLastFrame) ;
}
if (cameraFollowsDeck) {
var wp = deck.GetPosition() ;
SK8RCanvas.panTo(wp.x, wp.y);
}
// Renderers
if (debugDraw) {
world.DrawDebugData();
} else {
SK8RCanvas.clear();
var viewportAABB = SK8RCanvas.getViewportAABB() ;
world.QueryAABB(renderCallback, viewportAABB) ;
for (var n=0; n<renderers.length; n++) {
var renderer = renderers[n].pop() ;
while (renderer) {
renderer.render() ;
renderer = renderers[n].pop() ;
}
}
}
world.ClearForces();
} else {
if (console) {
console.log("World is locked when entering step");
}
}
}
function renderFixtures(b2Fixture) {
// TODO: bodies with several fixtures will be rendered several times using this. Might be ok
var userdata = b2Fixture.GetBody().GetUserData() ;
if (userdata) {
self.queueRenderer(userdata) ;
}
return true ;
}
function start() {
lastFrameTime = new Date().getTime() ;
var callback = SK8RBindCall(self, step) ;
timerID = window.setInterval(callback, 1000 / 30);
}
self.queueRenderer = function(renderer) {
renderers[renderer.getZIndex()].push(renderer) ;
}
self.onLoad = function() {
var progressBar = new ProgressBar(SK8RCanvas.getContext()) ;
var progressMeter =
new ProgressMeter("Initializing",
[
SK8RBindApply(progressBar, progressBar.progress),
function(taskname, progressFraction) {
console.log("Progress [" + taskname + "]="+progressFraction*100 + "%") ;
}
]) ;
// Iniitalize globals
bodies = new Array();
joints = new Array();
actors = new Array();
world = new Box2D.Dynamics.b2World(
new Box2D.Common.Math.b2Vec2(0, 10), true);
// setup debug draw
if (debugDraw) {
SK8RCanvas.setupDebugDraw(world);
}
progressMeter.progress(0.1) ;
// Setup game world
initFixtures(progressMeter) ;
initBodies(progressMeter) ;
progressMeter.progress(0.7) ;
for (var n=0; n<10; n++) {
renderers[n] = new Array() ;
}
progressMeter.progress(1.0) ;
SK8RCanvas.clear() ;
start() ;
}
self.reset = function() {
SK8RCanvas.clear() ;
var n ;
window.clearInterval(timerID) ;
// Destroy the existing joints
for (n = 0; n < joints.length; n++) {
world.DestroyJoint(joints[n]);
}
joints = new Array() ;
// Destroy the existing bodies
for (n = 0; n < bodies.length; n++) {
world.DestroyBody(bodies[n]);
}
bodies = new Array();
actors = new Array() ;
// Setup game world
initBodies() ;
start();
};
self.toggleFollow = function() {
cameraFollowsDeck = !cameraFollowsDeck ;
}
self.createBody = function(bodyDef, fixtureDef) {
var body = self.createUntrackedBody(bodyDef, fixtureDef) ;
bodies.push(body) ;
return body ;
};
self.createUntrackedBody = function(bodyDef, fixtureDef) {
var fixtureDefinitions = new Array() ;
fixtureDefinitions = fixtureDefinitions.concat(fixtureDef) ;
var body = world.CreateBody(bodyDef) ;
for (var n=0; n<fixtureDefinitions.length; n++) {
body.CreateFixture(fixtureDefinitions[n]) ;
}
return body ;
};
self.createJoint = function(jointDef) {
var joint = world.CreateJoint(jointDef);
joints.push(joint);
return joint ;
};
self.addActor = function(actor) {
if (actor) {
actors.push(actor) ;
}
};
self.removeActor = function(actor) {
actors = actors.filter(function(curValue, curIndex, curArray)
{
return (element != actor) ;
}
);
};
return self ;
}()) ;
window.onload = function() {
SK8RCanvas.onLoad() ;
SK8RGameWorld.onLoad() ;
};
| JavaScript |
/*
Package: progress
Utility classes to track and draw progress (for loading.... messages).
*/
/*
Class: ProgressMeter
A class that keeps two counters. A counter of the number of tasks left to be done
and a counter of how far the current task has progressed. Execution of the tasks
are outside of ProgressMeter but when progress is made on a task the executor
calls ProgressMeter.progress. This class then issues callbacks to listeners to
inform them of the progress being made. The listeners, typicaly GUI elements,
can inform the user of the progress.
Constructor:
tasknames - An Array of (String) names for the tasks to be performed. Used in
the callbacks to inform the listeners of the current task name.
listeners - An array of functions that are to be called on progress. The first
parameter on the callback is the (String) taskname. The second
parameters on the callback is the progress as a number between 0
and 1. The progress indicates overall total progress, not the
progress for a single task.
*/
function ProgressMeter(tasknames, listeners) {
this.tasknames = new Array() ;
this.tasknames = this.tasknames.concat(tasknames) ;
this.listeners = new Array() ;
this.listeners = this.listeners.concat(listeners) ;
this.activeTaskIndex = 0 ;
this.activeTaskProgress = 0 ;
this.progressPerTask = 1/this.tasknames.length ;
this.totalTaskProgress = 0 ;
}
ProgressMeter.prototype = {
/*
Function: progress
Used to inform the ProgressMeter that a task has progressed. Issues
callbacks to the registered listeners to inform of the progress. The callback
informs of the overall progress and which task is the current active one.
Parameters:
fractionComplete - A number between 0 and 1 indicating the progress for
the current task. When progress is >= 1.0 the ProgressMeter switches
the active task to the next.
*/
progress : function(fractionComplete) {
if (fractionComplete > 1.0) {
fractionComplete = 1.0 ;
}
if (fractionComplete < 0) {
fractionComplete = 0 ;
}
this.activeTaskProgress = fractionComplete ;
this.totalTaskProgress = this.activeTaskIndex*this.progressPerTask + (this.activeTaskProgress * this.progressPerTask) ;
this.fireProgress();
if (this.activeTaskProgress > 0.99) {
this.activeTaskIndex++ ;
}
},
/*
Function: fireProgress
Internal function, do not call. Issues callbacks to the registered listener
functions to indicate progress.
*/
fireProgress : function() {
for (var n=0; n<this.listeners.length; n++) {
this.listeners[n](this.tasknames[this.activeTaskIndex], this.totalTaskProgress);
}
}
};
/*
Class: ProgressBar
Draws a progress bar on the given canvas. Register an instance of this class on
a progress meter and watch the blinken bars.
Constructor:
ctx - The canvas 2D context to draw on.
appearance - Optional object defining the appearance of the progress bar.
appearance:
x - The left edge of the progress bar in the canvas. Defaults to 10.
y - The top edge of the progress bar in the canvas. Defaults to 10.
width - The width of the progress bar in the canvas. Defaults to 620.
height - The height of the progress bar in the canvas. Defaults to 40.
*/
function ProgressBar(ctx, appearance) {
this.ctx = ctx ;
this.x = 10 ;
this.y = 10 ;
this.width = 620 ;
this.height = 40 ;
if (appearance) {
if (appearance.x) {
this.x = appearance.x ;
}
if (appearance.y) {
this.y = appearance.y ;
}
if (appearance.width) {
this.width = appearance.width ;
}
if (appearance.height) {
this.height = appearance.height ;
}
}
this.gradient = ctx.createLinearGradient(0, 0, this.width, this.height);
this.gradient.addColorStop(0, "#0000ff");
this.gradient.addColorStop(1, "#00ff00");
var fontHeight = (this.height/2)-4 ;
fontHeight = Math.min(fontHeight, 30);
this.font = fontHeight + "px sans" ;
}
ProgressBar.prototype = {
/*
callback: progress
Callback from a <ProgressMeter> to update the progress bar GUI.
*/
progress : function(taskname, progressFraction) {
this.ctx.fillStyle="#000000" ;
this.ctx.fillRect(this.x, this.y, this.width, this.height) ;
this.ctx.fillStyle=this.gradient;
this.ctx.fillRect(this.x, this.y, this.width * progressFraction, this.height) ;
this.ctx.lineWidth = 2.0 ;
this.ctx.strokeStyle="#f0f0f0" ;
this.ctx.strokeRect(this.x, this.y, this.width, this.height) ;
this.ctx.font=this.font ;
this.ctx.textBaseline="middle";
var metrics = this.ctx.measureText(taskname) ;
var textx = this.width/2 - metrics.width/2 + this.x;
this.ctx.fillStyle="#f0f0f0" ;
this.ctx.fillText(taskname, textx, this.y+this.height/2, this.width) ;
}
};
| JavaScript |
/*
Copyright 2011 Johan Maasing
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var ZIndices = {
Space : 0,
FarBackground : 1,
Background : 2,
Ground : 3,
Far : 4,
Normal : 5,
Near : 6,
FarOverlay : 7,
Overlay : 8,
NearOverlay : 9
}
function FilledCircleRenderer(body, zindex, fillStyle, radius) {
this.body = body ;
this.radius = radius ;
this.fillStyle = fillStyle ;
this.zindex = zindex || ZIndices.Normal ;
}
FilledCircleRenderer.prototype.render = function() {
var worldPosition = this.body.GetPosition() ;
var screenPosition = SK8RCanvas.worldToScreen(worldPosition) ;
var ctx = SK8RCanvas.getContext() ;
ctx.fillStyle = this.fillStyle;
ctx.beginPath();
ctx.arc(
screenPosition.x,
screenPosition.y,
SK8RCanvas.worldLengthToScreen(this.radius),
0,
Math.PI * 2,
false);
ctx.closePath();
ctx.fill();
}
FilledCircleRenderer.prototype.getZIndex = function() {
return this.zindex ;
}
function GroundRenderer(body, vertices) {
this.body = body ;
this.vertices = vertices ;
}
GroundRenderer.prototype.render = function() {
var ctx = SK8RCanvas.getContext() ;
ctx.fillStyle = "#c0c0c0";
ctx.beginPath();
var screenCoords = SK8RCanvas.worldToScreen(this.vertices[0]) ;
ctx.moveTo(screenCoords.x, screenCoords.y);
for (var n=1; n<this.vertices.length; n++) {
screenCoords = SK8RCanvas.worldToScreen(this.vertices[n]) ;
ctx.lineTo(screenCoords.x, screenCoords.y);
}
ctx.closePath();
ctx.fill();
}
GroundRenderer.prototype.getZIndex = function() {
return ZIndices.Ground ;
}
function Rotated(body, zindex) {
this.body = body ;
this.zindex = zindex ;
}
Rotated.prototype.render = function() {
var worldPosition = this.body.GetPosition() ;
var screenPosition = SK8RCanvas.worldToScreen(worldPosition) ;
var ctx = SK8RCanvas.getContext() ;
ctx.save();
ctx.translate(screenPosition.x, screenPosition.y);
ctx.rotate(this.body.GetAngle());
this.renderRotated() ;
ctx.restore() ;
}
Rotated.prototype.renderRotated = function() {
if (console) {
console.log("Forgot to override renderRotated") ;
}
}
Rotated.prototype.getZIndex = function() {
return this.zindex ;
}
function DeckRenderer(body, length, thickness) {
Rotated.call(this, body, ZIndices.Normal) ;
this.length = length ;
this.thickness = thickness ;
}
DeckRenderer.prototype = SK8RDelegate(Rotated.prototype) ;
DeckRenderer.prototype.constructor = DeckRenderer;
DeckRenderer.prototype.renderRotated = function() {
var lengthPxls = SK8RCanvas.worldLengthToScreen(this.length) ;
var thicknessPxls = SK8RCanvas.worldLengthToScreen(this.thickness) ;
var ctx = SK8RCanvas.getContext() ;
ctx.fillStyle = "#00ff00";
ctx.fillRect(-lengthPxls/2, -thicknessPxls/2,
lengthPxls, thicknessPxls);
}
function ArmRenderer(body, width, height) {
Rotated.call(this, body, ZIndices.Near) ;
this.width = width ;
this.height = height ;
}
ArmRenderer.prototype = SK8RDelegate(Rotated.prototype) ;
ArmRenderer.prototype.constructor = ArmRenderer;
ArmRenderer.prototype.renderRotated = function() {
var widthPxls = SK8RCanvas.worldLengthToScreen(this.width) ;
var heightPxls = SK8RCanvas.worldLengthToScreen(this.height) ;
var ctx = SK8RCanvas.getContext() ;
ctx.fillStyle = "#456789";
ctx.fillRect(-widthPxls/2, -heightPxls/2,
widthPxls, heightPxls);
}
function BodyRenderer(body, vertices) {
Rotated.call(this, body, ZIndices.Normal) ;
this.vertices = vertices ;
}
BodyRenderer.prototype = SK8RDelegate(Rotated.prototype) ;
BodyRenderer.prototype.constructor = BodyRenderer;
BodyRenderer.prototype.renderRotated = function() {
var ctx = SK8RCanvas.getContext() ;
ctx.fillStyle = "#789abc";
ctx.beginPath();
var screenCoords = SK8RCanvas.worldToScreenOrigo(this.vertices[0]);
ctx.moveTo(screenCoords.x, screenCoords.y);
for (var n=1; n<this.vertices.length; n++) {
screenCoords = SK8RCanvas.worldToScreenOrigo(this.vertices[n]);
ctx.lineTo(screenCoords.x, screenCoords.y);
}
ctx.closePath();
ctx.fill();
}
function SK8RBotBoxRenderer(body, zindex, fillStyle, width, height) {
Rotated.call(this, body, zindex) ;
this.width = width ;
this.height = height ;
this.fillStyle = fillStyle;
}
SK8RBotBoxRenderer.prototype = SK8RDelegate(Rotated.prototype) ;
SK8RBotBoxRenderer.prototype.constructor = SK8RBotBoxRenderer;
SK8RBotBoxRenderer.prototype.renderRotated = function() {
var widthPxls = SK8RCanvas.worldLengthToScreen(this.width) ;
var heightPxls = SK8RCanvas.worldLengthToScreen(this.height) ;
var ctx = SK8RCanvas.getContext() ;
ctx.fillStyle = this.fillStyle;
ctx.fillRect(-widthPxls/2, -heightPxls/2,
widthPxls, heightPxls);
}
function SK8RBotActorStateRenderer(actor) {
this.actor = actor ;
}
SK8RBotActorStateRenderer.prototype.render = function() {
var canvasSize = SK8RCanvas.getCanvasSize() ;
var ctx = SK8RCanvas.getContext() ;
var text = "Left Desired [Arm Angle: " +
(this.actor.leftArmDesiredAngle * (180/Math.PI)).toFixed(1) +
" foot translation: " +
this.actor.leftFootDesiredTranslation.toFixed(1) +
"]";
ctx.textBaseline="top";
ctx.font = "14px sans" ;
var metrics = ctx.measureText(text) ;
var textx = canvasSize.width/2 - metrics.width/2 ;
ctx.clearRect(20, 0, canvasSize.width-40, 24);
ctx.fillStyle="rgba(128, 128, 128, 0.5)" ;
ctx.fillRect(20, 0, canvasSize.width-40, 24);
ctx.fillStyle="rgba(255, 255, 255, 0.8)" ;
ctx.fillText(text, textx, 1, canvasSize.width) ;
}
SK8RBotActorStateRenderer.prototype.getZIndex = function() {
return ZIndices.Overlay ;
}
| JavaScript |
/*
Copyright 2011 Johan Maasing
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
function Sk8board(sizes) {
sizes = sizes || {} ;
sizes.scale = sizes.scale || 1 ;
// According to http://defekt.se/2010/04/den-standardiserade-skateboarden/
sizes.wheelRadius = (sizes.wheelRadius || 0.05) * sizes.scale ;
sizes.boardThickness = (sizes.boardThickness || 0.02) * sizes.scale ;
sizes.boardLength = (sizes.boardLength || 0.82) * sizes.scale ;
sizes.truckOffset = (sizes.truckOffset || 0.18) * sizes.scale ;
var offset = sizes.offset || {} ;
offset.x = offset.x || 0 ;
offset.y = offset.y || 0 ;
var bodyDef = new Box2D.Dynamics.b2BodyDef();
var fixDef = new Box2D.Dynamics.b2FixtureDef();
fixDef.density = 1.0;
fixDef.friction = 0.9;
fixDef.restitution = 0.1;
fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(sizes.wheelRadius);
// Back wheel
bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
bodyDef.position.x = sizes.wheelRadius + offset.x;
bodyDef.position.y = sizes.wheelRadius + offset.y;
var backwheel = SK8RGameWorld.createBody(bodyDef,fixDef);
backwheel.SetUserData(new FilledCircleRenderer(backwheel, ZIndices.Normal, "#a00000", sizes.wheelRadius)) ;
// Front wheel
bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
bodyDef.position.x = sizes.boardLength-sizes.wheelRadius + offset.x;
bodyDef.position.y = sizes.wheelRadius + offset.y;
var frontwheel = SK8RGameWorld.createBody(bodyDef,fixDef);
frontwheel.SetUserData(new FilledCircleRenderer(frontwheel, ZIndices.Normal, "#00a000", sizes.wheelRadius));
// Deck
fixDef.shape = new Box2D.Collision.Shapes.b2PolygonShape();
fixDef.shape.SetAsBox(sizes.boardLength / 2, sizes.boardThickness / 2);
bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
bodyDef.position.x = sizes.boardLength / 2 + offset.x;
bodyDef.position.y = sizes.boardThickness / 2 + offset.y;
var board = SK8RGameWorld.createBody(bodyDef, fixDef);
board.SetUserData(new DeckRenderer(board, sizes.boardLength, sizes.boardThickness)) ;
// Trucks
var b2JointDef = new Box2D.Dynamics.Joints.b2RevoluteJointDef();
b2JointDef.bodyA = backwheel;
b2JointDef.bodyB = board;
b2JointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(0, 0);
b2JointDef.localAnchorB =
new Box2D.Common.Math.b2Vec2(-sizes.boardLength/2 + sizes.truckOffset, sizes.wheelRadius);
SK8RGameWorld.createJoint(b2JointDef);
b2JointDef.bodyA = frontwheel;
b2JointDef.bodyB = board;
b2JointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(0, 0);
b2JointDef.localAnchorB =
new Box2D.Common.Math.b2Vec2(sizes.boardLength/2 - sizes.truckOffset, sizes.wheelRadius);
SK8RGameWorld.createJoint(b2JointDef);
return board ;
}
function createDemoGround() {
var fixDef = new Box2D.Dynamics.b2FixtureDef();
fixDef.density = 1.0;
fixDef.friction = 0.9;
fixDef.restitution = 0.01;
var bodyDef = new Box2D.Dynamics.b2BodyDef();
bodyDef.type = Box2D.Dynamics.b2Body.b2_staticBody;
var vertices = [
new Box2D.Common.Math.b2Vec2(0, 10),
new Box2D.Common.Math.b2Vec2(14, 12),
new Box2D.Common.Math.b2Vec2(0, 12)
] ;
fixDef.shape = Box2D.Collision.Shapes.b2PolygonShape.AsArray(vertices, vertices.length) ;
bodyDef.position.x = 0 ;
bodyDef.position.y = 0 ;
var staticBody = SK8RGameWorld.createUntrackedBody(bodyDef, fixDef) ;
staticBody.SetUserData(new GroundRenderer(staticBody, vertices)) ;
vertices = [
new Box2D.Common.Math.b2Vec2(14, 12),
new Box2D.Common.Math.b2Vec2(16, 11.5),
new Box2D.Common.Math.b2Vec2(16, 12)
] ;
fixDef.shape = Box2D.Collision.Shapes.b2PolygonShape.AsArray(vertices, vertices.length) ;
bodyDef.position.x = 0 ;
bodyDef.position.y = 0 ;
staticBody = SK8RGameWorld.createUntrackedBody(bodyDef, fixDef) ;
staticBody.SetUserData(new GroundRenderer(staticBody, vertices)) ;
}
function createRobot(sizes) {
sizes = sizes || {} ;
sizes.scale = sizes.scale || 1 ;
sizes.offsetx = sizes.offsetx || 0.7*sizes.scale ;
sizes.offsety = sizes.offsety || -1.7*sizes.scale ;
var bodyDef = new Box2D.Dynamics.b2BodyDef();
bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
var fixDef = new Box2D.Dynamics.b2FixtureDef();
fixDef.density = 1.0;
fixDef.friction = 0.9;
fixDef.restitution = 0.1;
fixDef.shape = new Box2D.Collision.Shapes.b2PolygonShape();
var limbHalfWidth = 0.25*sizes.scale ;
var limbHalfHeight = 0.5*sizes.scale ;
// right leg
bodyDef.position.x = sizes.offsetx + (0.75*sizes.scale);
bodyDef.position.y = sizes.offsety + (3*sizes.scale);
fixDef.shape.SetAsBox(limbHalfWidth, limbHalfHeight);
var rightLeg = SK8RGameWorld.createBody(bodyDef, fixDef) ;
rightLeg.SetUserData(new ArmRenderer(rightLeg, limbHalfWidth*2, limbHalfHeight*2)) ;
// Left leg
bodyDef.position.x = sizes.offsetx + (1.75*sizes.scale);
bodyDef.position.y = sizes.offsety + (3*sizes.scale);
fixDef.shape.SetAsBox(limbHalfWidth, limbHalfHeight);
var leftLeg = SK8RGameWorld.createBody(bodyDef, fixDef) ;
leftLeg.SetUserData(new ArmRenderer(leftLeg, limbHalfWidth*2, limbHalfHeight*2)) ;
// Right arm
bodyDef.position.x = sizes.offsetx + (2.25*sizes.scale);
bodyDef.position.y = sizes.offsety + (1.5*sizes.scale);
fixDef.shape.SetAsBox(limbHalfWidth, limbHalfHeight);
var rightArm = SK8RGameWorld.createBody(bodyDef, fixDef) ;
rightArm.SetUserData(new ArmRenderer(rightArm, limbHalfWidth*2, limbHalfHeight*2)) ;
// Left arm
bodyDef.position.x = sizes.offsetx + (0.25*sizes.scale);
bodyDef.position.y = sizes.offsety + (1.5*sizes.scale);
fixDef.shape.SetAsBox(limbHalfWidth, limbHalfHeight);
var leftArm = SK8RGameWorld.createBody(bodyDef, fixDef) ;
leftArm.SetUserData(new ArmRenderer(leftArm, limbHalfWidth*2, limbHalfHeight*2)) ;
// Body
bodyDef.position.x = sizes.offsetx + (1.25*sizes.scale);
bodyDef.position.y = sizes.offsety + (1.25*sizes.scale);
var bodyVertices = [
new Box2D.Common.Math.b2Vec2(-0.75 * sizes.scale, -0.75 * sizes.scale),
new Box2D.Common.Math.b2Vec2(-0.25 * sizes.scale, -1.25 * sizes.scale),
new Box2D.Common.Math.b2Vec2(0.25 * sizes.scale, -1.25 * sizes.scale),
new Box2D.Common.Math.b2Vec2(0.75 * sizes.scale, -0.75 * sizes.scale),
new Box2D.Common.Math.b2Vec2(0.75 * sizes.scale, 1.25 * sizes.scale),
new Box2D.Common.Math.b2Vec2(-0.75 * sizes.scale, 1.25 * sizes.scale)
] ;
fixDef.shape.SetAsArray(bodyVertices);
var body = SK8RGameWorld.createBody(bodyDef, fixDef) ;
body.SetUserData(new BodyRenderer(body, bodyVertices)) ;
// Arm joints
var b2JointDef = new Box2D.Dynamics.Joints.b2RevoluteJointDef();
b2JointDef.bodyA = body;
var joint ;
// Right arm
b2JointDef.bodyB = rightArm;
b2JointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(0.75*sizes.scale, -0.25*sizes.scale);
b2JointDef.localAnchorB =
new Box2D.Common.Math.b2Vec2(-limbHalfWidth, -limbHalfHeight);
b2JointDef.lowerAngle = -Math.PI ;
b2JointDef.upperAngle = 0.5 ;
b2JointDef.enableLimit = true ;
SK8RGameWorld.createJoint(b2JointDef) ;
// Left arm
b2JointDef.bodyB = leftArm;
b2JointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(-0.75*sizes.scale, -0.25*sizes.scale);
b2JointDef.localAnchorB =
new Box2D.Common.Math.b2Vec2(limbHalfWidth, -limbHalfHeight);
b2JointDef.lowerAngle = -0.5 ;
b2JointDef.upperAngle = Math.PI;
b2JointDef.enableLimit = true ;
SK8RGameWorld.createJoint(b2JointDef) ;
// Leg joints
b2JointDef = new Box2D.Dynamics.Joints.b2PrismaticJointDef();
b2JointDef.bodyA = body;
b2JointDef.localAxisA = new Box2D.Common.Math.b2Vec2(0,1);
b2JointDef.lowerTranslation = -0.5*sizes.scale ;
b2JointDef.upperTranslation = 0.5*sizes.scale ;
b2JointDef.enableLimit = true ;
// Right leg
b2JointDef.bodyB = rightLeg;
b2JointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(0.5*sizes.scale, 1.25*sizes.scale);
b2JointDef.localAnchorB =
new Box2D.Common.Math.b2Vec2(0*sizes.scale, -limbHalfHeight);
SK8RGameWorld.createJoint(b2JointDef) ;
// Left leg
b2JointDef.bodyB = leftLeg;
b2JointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(-0.5*sizes.scale, 1.25*sizes.scale);
b2JointDef.localAnchorB =
new Box2D.Common.Math.b2Vec2(0*sizes.scale, -limbHalfHeight);
SK8RGameWorld.createJoint(b2JointDef) ;
}
function createSK8RRobot(sizes) {
sizes = sizes || {} ;
sizes.scale = sizes.scale || 1 ;
sizes.offsetx = sizes.offsetx || 0*sizes.scale ;
sizes.offsety = sizes.offsety || 0*sizes.scale ;
var bodyDef = new Box2D.Dynamics.b2BodyDef();
bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
var fixDef = new Box2D.Dynamics.b2FixtureDef();
fixDef.density = 1.0;
fixDef.friction = 0.9;
fixDef.restitution = 0.1;
//// Head
// Position: 1.25, 0.5
// Radius: 0.5
var radius = 0.5 * sizes.scale;
bodyDef.position.x = sizes.offsetx + (1.25 * sizes.scale);
bodyDef.position.y = sizes.offsety + (0.5 * sizes.scale);
fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(radius);
var head = SK8RGameWorld.createBody(bodyDef, fixDef) ;
head.SetUserData(new FilledCircleRenderer(head, ZIndices.Near, "#123456", radius)) ;
//// Body
fixDef.shape = new Box2D.Collision.Shapes.b2PolygonShape();
// Position 1.25, 1.75
// halfwidth = halfheight = 0.75
var bodyHalfSize = 0.75 * sizes.scale ;
bodyDef.position.x = sizes.offsetx + (1.25 * sizes.scale);
bodyDef.position.y = sizes.offsety + (1.75 * sizes.scale);
fixDef.shape.SetAsBox(bodyHalfSize, bodyHalfSize);
var body = SK8RGameWorld.createBody(bodyDef, fixDef) ;
body.SetUserData(new SK8RBotBoxRenderer(body, ZIndices.Normal, "#123456", bodyHalfSize * 2, bodyHalfSize * 2)) ;
//// Arms
var armHalfWidth = 0.25 * sizes.scale ;
var armHalfHeight = 0.75 * sizes.scale ;
//// Right arm
// Position: 0.25, 1.75
// Halfwidth: 0.25 Halfheight: 0.75
bodyDef.position.x = sizes.offsetx + (0.25 * sizes.scale);
bodyDef.position.y = sizes.offsety + (1.75 * sizes.scale);
fixDef.shape.SetAsBox(armHalfWidth, armHalfHeight);
var rightArm = SK8RGameWorld.createBody(bodyDef, fixDef) ;
rightArm.SetUserData(new SK8RBotBoxRenderer(rightArm, ZIndices.Far, "#987654", armHalfWidth * 2, armHalfHeight * 2)) ;
//// Left arm
// Position: 2.25, 1.75
// Halfwidth: 0.25 Halfheight: 0.75
bodyDef.position.x = sizes.offsetx + (2.25 * sizes.scale);
bodyDef.position.y = sizes.offsety + (1.75 * sizes.scale);
fixDef.shape.SetAsBox(armHalfWidth, armHalfHeight);
var leftArm = SK8RGameWorld.createBody(bodyDef, fixDef) ;
leftArm.SetUserData(new SK8RBotBoxRenderer(leftArm, ZIndices.Far, "#456789", armHalfWidth * 2, armHalfHeight * 2)) ;
//// Legs
var legHalfWidth = 0.25 * sizes.scale ;
var legHalfHeight = 0.5 * sizes.scale ;
//// Right leg
// Position: 0.75, 3.0
// Halfwidth: 0.25 Halfheight: 0.5
bodyDef.position.x = sizes.offsetx + (0.75 * sizes.scale);
bodyDef.position.y = sizes.offsety + (3.0 * sizes.scale);
fixDef.shape.SetAsBox(legHalfWidth, legHalfHeight);
var rightLeg = SK8RGameWorld.createBody(bodyDef, fixDef) ;
rightLeg.SetUserData(new SK8RBotBoxRenderer(rightLeg, ZIndices.Normal, "#a0b0c0", legHalfWidth * 2, legHalfHeight * 2)) ;
//// Left leg
// Position: 1.75, 3
// Halfwidth: 0.25 Halfheight: 0.5
bodyDef.position.x = sizes.offsetx + (1.75 * sizes.scale);
bodyDef.position.y = sizes.offsety + (3.0 * sizes.scale);
fixDef.shape.SetAsBox(legHalfWidth, legHalfHeight);
var leftLeg = SK8RGameWorld.createBody(bodyDef, fixDef) ;
leftLeg.SetUserData(new SK8RBotBoxRenderer(leftLeg, ZIndices.Normal, "#c0b0a0", legHalfWidth * 2, legHalfHeight * 2)) ;
//// Feet
var feetHalfWidth = 0.25 * sizes.scale ;
var feetHalfHeight = 0.5 * sizes.scale ;
//// Right foot
// Position: 0.75, 3.75
// Halfwidth = Halfheight: 0.5
bodyDef.position.x = sizes.offsetx + (0.75 * sizes.scale);
bodyDef.position.y = sizes.offsety + (3.75 * sizes.scale);
fixDef.shape.SetAsBox(feetHalfWidth, feetHalfHeight);
var rightFoot = SK8RGameWorld.createBody(bodyDef, fixDef) ;
rightFoot.SetUserData(new SK8RBotBoxRenderer(rightFoot, ZIndices.Near, "#102030", feetHalfWidth * 2, feetHalfHeight * 2)) ;
//// Left foot
// Position: 1.75, 3.75
// Halfwidth = Halfheight: 0.25
bodyDef.position.x = sizes.offsetx + (1.75 * sizes.scale);
bodyDef.position.y = sizes.offsety + (3.75 * sizes.scale);
fixDef.shape.SetAsBox(feetHalfWidth, feetHalfHeight);
var leftFoot = SK8RGameWorld.createBody(bodyDef, fixDef) ;
leftFoot.SetUserData(new SK8RBotBoxRenderer(leftFoot, ZIndices.Near, "#302010", feetHalfWidth * 2, feetHalfHeight * 2)) ;
//// Joints
var revolutionJointDef = new Box2D.Dynamics.Joints.b2RevoluteJointDef();
revolutionJointDef.enableLimit = true ;
//// Head body revolution joint
// BodyA = body
// BodyB = head
// BodyA-pos: 0, -0.75
// BodyB-pos: 0, 0.5
revolutionJointDef.bodyA = body;
revolutionJointDef.bodyB = head;
revolutionJointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(0, -0.75 * sizes.scale);
revolutionJointDef.localAnchorB = new Box2D.Common.Math.b2Vec2(0, 0.5 * sizes.scale);
revolutionJointDef.lowerAngle = -(Math.PI / 8) ; // 180/8 = 22.5 degrees
revolutionJointDef.upperAngle = Math.PI / 8 ;
var headBodyJoint = SK8RGameWorld.createJoint(revolutionJointDef) ;
//// Arm joints
revolutionJointDef.maxMotorTorque = 10.0 ;
revolutionJointDef.motorSpeed = 0.0 ;
revolutionJointDef.enableMotor = true;
//// Right arm-body revolution joint
// BodyA = body
// BodyB = right arm
// BodyA-pos: -0.75, -0.75
// BodyB-pos: 0.25, -0.75
revolutionJointDef.bodyA = body;
revolutionJointDef.bodyB = rightArm;
revolutionJointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(-0.75 * sizes.scale, -0.75 * sizes.scale);
revolutionJointDef.localAnchorB = new Box2D.Common.Math.b2Vec2(0.25 * sizes.scale, -0.75 * sizes.scale);
revolutionJointDef.lowerAngle = -(Math.PI / 8) ; // 180/8 = 22.5 degrees
revolutionJointDef.upperAngle = Math.PI ;
var rArmBodyBodyJoint = SK8RGameWorld.createJoint(revolutionJointDef) ;
//// Left arm-body revolution joint
// BodyA = body
// BodyB = left arm
// BodyA-pos: 0.75, -0.75
// BodyB-pos: -0.25, -0.75
revolutionJointDef.bodyA = body;
revolutionJointDef.bodyB = leftArm;
revolutionJointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(0.75 * sizes.scale, -0.75 * sizes.scale);
revolutionJointDef.localAnchorB = new Box2D.Common.Math.b2Vec2(-0.25 * sizes.scale, -0.75 * sizes.scale);
revolutionJointDef.lowerAngle = -Math.PI;
revolutionJointDef.upperAngle = Math.PI / 8 ; // 180/8 = 22.5 degrees
var lArmBodyBodyJoint = SK8RGameWorld.createJoint(revolutionJointDef) ;
//// Right leg-body revolution joint
// BodyA = body
// BodyB = right leg
// BodyA-pos: -0.5, 0.75
// BodyB-pos: 0, -0.5
revolutionJointDef.bodyA = body;
revolutionJointDef.bodyB = rightLeg;
revolutionJointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(-0.5 * sizes.scale, 0.75 * sizes.scale);
revolutionJointDef.localAnchorB = new Box2D.Common.Math.b2Vec2(0, -0.5 * sizes.scale);
revolutionJointDef.lowerAngle = -Math.PI / 8 ; // 180/8 = 22.5 degrees
revolutionJointDef.upperAngle = Math.PI / 8 ; // 180/8 = 22.5 degrees
var rLegBodyBodyJoint = SK8RGameWorld.createJoint(revolutionJointDef) ;
//// Left leg-body revolution joint
// BodyA = body
// BodyB = left leg
// BodyA-pos: 0.5, 0.75
// BodyB-pos: 0, -0.5
revolutionJointDef.bodyA = body;
revolutionJointDef.bodyB = leftLeg;
revolutionJointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(0.5 * sizes.scale, 0.75 * sizes.scale);
revolutionJointDef.localAnchorB = new Box2D.Common.Math.b2Vec2(0, -0.5 * sizes.scale);
revolutionJointDef.lowerAngle = -Math.PI / 8 ; // 180/8 = 22.5 degrees
revolutionJointDef.upperAngle = Math.PI / 8 ; // 180/8 = 22.5 degrees
var lLegBodyBodyJoint = SK8RGameWorld.createJoint(revolutionJointDef) ;
//// Feet joints
var prismaticJointDef = new Box2D.Dynamics.Joints.b2PrismaticJointDef();
prismaticJointDef.enableLimit = true ;
prismaticJointDef.localAxisA = new Box2D.Common.Math.b2Vec2(0,1);
prismaticJointDef.lowerTranslation = -feetHalfHeight * 2 * sizes.scale ;
prismaticJointDef.upperTranslation = feetHalfHeight * 2 * sizes.scale ;
prismaticJointDef.maxMotorForce = 10.0 ;
prismaticJointDef.motorSpeed = 0.0 ;
prismaticJointDef.enableMotor = true;
//// Right leg-Right foot prismatic joint
// BodyA = right leg
// BodyB = right foot
// BodyA-pos: 0, 0.5
// BodyB-pos: 0, -0.25
prismaticJointDef.bodyA = rightLeg;
prismaticJointDef.bodyB = rightFoot;
prismaticJointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(0, 0.5 * sizes.scale);
prismaticJointDef.localAnchorB = new Box2D.Common.Math.b2Vec2(0, -feetHalfHeight * 2 * sizes.scale);
var lFootJoint = SK8RGameWorld.createJoint(prismaticJointDef) ;
//// Left leg-Left foot prismatic joint
// BodyA = left leg
// BodyB = left foot
// BodyA-pos: 0, 0.5
// BodyB-pos: 0, -0.25
prismaticJointDef.bodyA = leftLeg;
prismaticJointDef.bodyB = leftFoot;
prismaticJointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(0, 0.5 * sizes.scale);
prismaticJointDef.localAnchorB = new Box2D.Common.Math.b2Vec2(0, -feetHalfHeight * 2 * sizes.scale);
var rFootJoint = SK8RGameWorld.createJoint(prismaticJointDef) ;
return {
body : body,
head : head,
headBodyJoint : headBodyJoint,
rightArm : rightArm,
rightArmBodyJoint: rArmBodyBodyJoint,
leftArm : leftArm,
leftArmBodyJoint: lArmBodyBodyJoint,
rightLeg : rightLeg,
rightLegBodyJoint : rLegBodyBodyJoint,
leftLeg : leftLeg,
leftLegBodyJoint : lLegBodyBodyJoint,
rightFoot : rightFoot,
rightFootJoint : rFootJoint,
leftFoot : leftFoot,
leftFootJoint : lFootJoint
} ;
} | JavaScript |
/*
Copyright 2011 Johan Maasing
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var SK8RCanvas = (function() {
var self = {} ;
var width = 640 ;
var height = 480 ;
var pixelsPerMeter = 20 ;
var cameraDefaultWorldViewportValues = {
halfWidth : 16,
helfHeight : 12,
xoffset : 16,
yoffset : 12
};
var cameraDefaultWorldViewport = {
lowerBound : new Box2D.Common.Math.b2Vec2(
cameraDefaultWorldViewportValues.xoffset-cameraDefaultWorldViewportValues.halfWidth,
cameraDefaultWorldViewportValues.yoffset-cameraDefaultWorldViewportValues.helfHeight),
upperBound : new Box2D.Common.Math.b2Vec2(
cameraDefaultWorldViewportValues.xoffset+cameraDefaultWorldViewportValues.halfWidth,
cameraDefaultWorldViewportValues.yoffset+cameraDefaultWorldViewportValues.helfHeight)
} ;
var cameraWorldViewport = {
lowerBound : new Box2D.Common.Math.b2Vec2(cameraDefaultWorldViewport.lowerBound.x, cameraDefaultWorldViewport.lowerBound.y),
upperBound : new Box2D.Common.Math.b2Vec2(cameraDefaultWorldViewport.upperBound.x, cameraDefaultWorldViewport.upperBound.y)
} ;
var cameraZoom = 1 ;
var ctx ;
var canvas ;
self.onLoad = function() {
canvas = document.getElementById('canvas');
width = canvas.getAttribute("width") ;
height = canvas.getAttribute("height") ;
ctx = canvas.getContext('2d');
};
self.getContext = function() {
return ctx ;
};
self.getCanvas = function() {
return canvas ;
};
self.getCanvasSize = function() {
return {
width : width,
height : height
} ;
};
self.clear = function() {
ctx.clearRect(0,0,width,height);
};
self.worldToScreen = function(wp) {
var sp = {} ;
sp.x = Math.round((wp.x -cameraWorldViewport.lowerBound.x) * pixelsPerMeter) ;
sp.y = Math.round((wp.y - cameraWorldViewport.lowerBound.y) * pixelsPerMeter) ;
return sp ;
}
self.worldToScreenOrigo = function(wp) {
var sp = {} ;
sp.x = Math.round(wp.x * pixelsPerMeter) ;
sp.y = Math.round(wp.y * pixelsPerMeter) ;
return sp ;
}
self.worldLengthToScreen = function(length) {
return Math.max(1, Math.round(length * pixelsPerMeter)) ;
}
self.getViewportAABB = function() {
return cameraWorldViewport ;
}
self.pan = function(x,y) {
cameraWorldViewport.lowerBound.x += x ;
cameraWorldViewport.lowerBound.y += y ;
cameraWorldViewport.upperBound.x += x ;
cameraWorldViewport.upperBound.y += y ;
}
self.panTo = function(x,y) {
cameraWorldViewport.lowerBound.x = x - cameraDefaultWorldViewportValues.halfWidth ;
cameraWorldViewport.lowerBound.y = y - cameraDefaultWorldViewportValues.helfHeight ;
cameraWorldViewport.upperBound.x = x + cameraDefaultWorldViewportValues.halfWidth;
cameraWorldViewport.upperBound.y = y + cameraDefaultWorldViewportValues.helfHeight;
}
self.resetCamera = function() {
cameraWorldViewport.lowerBound.x = cameraDefaultWorldViewport.lowerBound.x ;
cameraWorldViewport.lowerBound.y = cameraDefaultWorldViewport.lowerBound.y ;
cameraWorldViewport.upperBound.x = cameraDefaultWorldViewport.upperBound.x ;
cameraWorldViewport.upperBound.y = cameraDefaultWorldViewport.upperBound.y ;
}
self.setupDebugDraw = function(world) {
var dd = new Box2D.Dynamics.b2DebugDraw();
dd.SetSprite(ctx);
dd.SetDrawScale(pixelsPerMeter);
dd.SetFillAlpha(0.6);
dd.SetLineThickness(1.0);
dd.SetFlags(Box2D.Dynamics.b2DebugDraw.e_shapeBit
| Box2D.Dynamics.b2DebugDraw.e_jointBit);
world.SetDebugDraw(dd);
}
return self ;
}()) ;
| JavaScript |
/*
Copyright 2011 Johan Maasing
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
function Person(name) {
this.name = name;
}
function Employee(name, salary) {
Person.call(this, name);
this.salary = salary;
}
Employee.prototype = delegate(Person.prototype);
Employee.prototype.constructor = Employee;
*/
var SK8RDelegate = (function() {
function F() {}
return (function(obj) {
F.prototype = obj;
return new F();
});
})();
function SK8RBindCall(obj, fn) {
return function() {
return fn.call(obj) ;
};
}
function SK8RBindApply(obj, fn) {
return function() {
return fn.apply(obj, arguments) ;
};
}
| JavaScript |
/*
Copyright 2011 Johan Maasing
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var gameWorld;
window.onload = function() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
gameWorld = new World(ctx);
gameWorld.init();
}
function reset() {
gameWorld.reset();
}
// Global constants
var pixelsPerMeter = 40;
var worldWidthInMeter = 16; // 640/pixelsPerMeter ;
var worldHeightInMeter = 12; // 480/pixelsPerMeter ;
function World(ctx) {
this.bodies = new Array();
this.joints = new Array();
this.world = new Box2D.Dynamics.b2World(
new Box2D.Common.Math.b2Vec2(0, 10), true);
this.ctx = ctx;
}
function bind(obj, fn) {
return function() {
fn.call(obj) ;
};
}
World.prototype = {
init : function() {
this.initRamp() ;
this.initBodies();
// setup debug draw
var debugDraw = new Box2D.Dynamics.b2DebugDraw();
debugDraw.SetSprite(this.ctx);
debugDraw.SetDrawScale(pixelsPerMeter);
debugDraw.SetFillAlpha(0.6);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(Box2D.Dynamics.b2DebugDraw.e_shapeBit
| Box2D.Dynamics.b2DebugDraw.e_jointBit);
this.world.SetDebugDraw(debugDraw);
var callback = bind(this, this.update) ;
this.timerId = window.setInterval(callback, 1000 / 30);
},
reset : function() {
// Destroy the existing joints
for ( var n = 0; n < this.joints.length; n++) {
this.world.DestroyJoint(this.joints[n]);
}
this.joints = new Array() ;
// Destroy the existing bodies
for ( var n = 0; n < this.bodies.length; n++) {
this.world.DestroyBody(this.bodies[n]);
}
this.bodies = new Array();
Actors.clear() ;
this.initBodies();
},
initRamp : function() {
var fixDef = new Box2D.Dynamics.b2FixtureDef();
fixDef.density = 1.0;
fixDef.friction = 0.9;
fixDef.restitution = 0.01;
var bodyDef = new Box2D.Dynamics.b2BodyDef();
bodyDef.type = Box2D.Dynamics.b2Body.b2_staticBody;
var vertices = [
new Box2D.Common.Math.b2Vec2(0, 0),
new Box2D.Common.Math.b2Vec2(1,1),
new Box2D.Common.Math.b2Vec2(2, 3),
new Box2D.Common.Math.b2Vec2(2, 11),
new Box2D.Common.Math.b2Vec2(0, 11)
] ;
fixDef.shape = Box2D.Collision.Shapes.b2PolygonShape.AsArray(vertices, vertices.length) ;
bodyDef.position.x = 0 ;
bodyDef.position.y = 1 ;
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
var vertices = [
new Box2D.Common.Math.b2Vec2(0, 0),
new Box2D.Common.Math.b2Vec2(2, 4),
new Box2D.Common.Math.b2Vec2(2, 6),
new Box2D.Common.Math.b2Vec2(0, 6)
] ;
fixDef.shape = Box2D.Collision.Shapes.b2PolygonShape.AsArray(vertices, vertices.length) ;
bodyDef.position.x = 2 ;
bodyDef.position.y = 6 ;
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
var vertices = [
new Box2D.Common.Math.b2Vec2(0, 0),
new Box2D.Common.Math.b2Vec2(1, 1),
new Box2D.Common.Math.b2Vec2(1, 2),
new Box2D.Common.Math.b2Vec2(0, 2)
] ;
fixDef.shape = Box2D.Collision.Shapes.b2PolygonShape.AsArray(vertices, vertices.length) ;
bodyDef.position.x = 4 ;
bodyDef.position.y = 10 ;
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
var vertices = [
new Box2D.Common.Math.b2Vec2(0, 0),
new Box2D.Common.Math.b2Vec2(2, 1),
new Box2D.Common.Math.b2Vec2(0, 1)
] ;
fixDef.shape = Box2D.Collision.Shapes.b2PolygonShape.AsArray(vertices, vertices.length) ;
bodyDef.position.x = 5 ;
bodyDef.position.y = 11 ;
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
var vertices = [
new Box2D.Common.Math.b2Vec2(0, 0),
new Box2D.Common.Math.b2Vec2(2, 0),
new Box2D.Common.Math.b2Vec2(2, 1),
new Box2D.Common.Math.b2Vec2(0, 1)
] ;
fixDef.shape = Box2D.Collision.Shapes.b2PolygonShape.AsArray(vertices, vertices.length) ;
bodyDef.position.x = 7 ;
bodyDef.position.y = 12 ;
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
var vertices = [
new Box2D.Common.Math.b2Vec2(0, 1),
new Box2D.Common.Math.b2Vec2(2, 0),
new Box2D.Common.Math.b2Vec2(2, 1)
] ;
fixDef.shape = Box2D.Collision.Shapes.b2PolygonShape.AsArray(vertices, vertices.length) ;
bodyDef.position.x = 9 ;
bodyDef.position.y = 11 ;
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
var vertices = [
new Box2D.Common.Math.b2Vec2(0, 1),
new Box2D.Common.Math.b2Vec2(1, 0),
new Box2D.Common.Math.b2Vec2(1, 2),
new Box2D.Common.Math.b2Vec2(0, 2)
] ;
fixDef.shape = Box2D.Collision.Shapes.b2PolygonShape.AsArray(vertices, vertices.length) ;
bodyDef.position.x = 11 ;
bodyDef.position.y = 10 ;
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
var vertices = [
new Box2D.Common.Math.b2Vec2(0, 4),
new Box2D.Common.Math.b2Vec2(2, 0),
new Box2D.Common.Math.b2Vec2(2, 6),
new Box2D.Common.Math.b2Vec2(0, 6)
] ;
fixDef.shape = Box2D.Collision.Shapes.b2PolygonShape.AsArray(vertices, vertices.length) ;
bodyDef.position.x = 12;
bodyDef.position.y = 6 ;
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
var bodyDef = new Box2D.Dynamics.b2BodyDef();
bodyDef.type = Box2D.Dynamics.b2Body.b2_staticBody;
var vertices = [
new Box2D.Common.Math.b2Vec2(0, 3),
new Box2D.Common.Math.b2Vec2(1, 1),
new Box2D.Common.Math.b2Vec2(2, 0),
new Box2D.Common.Math.b2Vec2(2, 12),
new Box2D.Common.Math.b2Vec2(0, 12)
] ;
fixDef.shape = Box2D.Collision.Shapes.b2PolygonShape.AsArray(vertices, vertices.length) ;
bodyDef.position.x = 14 ;
bodyDef.position.y = 1 ;
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
},
initBodies : function() {
Actors.clear() ;
var sk8board = new Sk8board(this.world, this.ctx) ;
sk8board.init(this.bodies, this.joints) ;
createRobot(this.bodies, this.joints, this.ctx, this.world, {scale: 0.4});
},
update : function() {
this.world.Step(1 / 30 // frame-rate
, 10 // velocity iterations
, 10 // position iterations
);
this.world.DrawDebugData();
//this.ctx.clearRect(0, 0, 640, 480);
Actors.step(0) ;
this.world.ClearForces();
}
};
| JavaScript |
var Actors = (function() {
var self = {} ;
var actors = new Array() ;
self.step = function(timeSinceLastFrame) {
for (var n=0; n<actors.length; n++) {
actors[n].step(timeSinceLastFrame) ;
}
};
self.addActor = function(actor) {
if (actor) {
actors.push(actor) ;
}
};
self.removeActor = function(actor) {
actors = actors.filter(function(curValue, curIndex, curArray)
{ return (element != actor) ; }
);
};
self.clear = function() {
actors = new Array() ;
};
return self ;
}()) ;
var MathUtil = (function() {
var self = {} ;
self.worldToScreen = function(wp) {
var sp = {} ;
sp.x = Math.round(wp.x * 40) ;
sp.y = Math.round(wp.y * 40) ;
return sp ;
}
self.worldLengthToScreen = function(length) {
return Math.max(1, Math.round(length * 40)) ;
}
return self ;
}());
function Wheel(ctx, body, radius) {
this.ctx = ctx ;
this.body = body ;
this.radius = radius ;
}
Wheel.prototype.step = function(timeSinceLastFrame) {
var worldPosition = this.body.GetPosition() ;
var screenPosition = MathUtil.worldToScreen(worldPosition) ;
this.ctx.fillStyle = "#ff0000";
this.ctx.beginPath();
this.ctx.arc(
screenPosition.x,
screenPosition.y,
MathUtil.worldLengthToScreen(this.radius),
0,
Math.PI * 2,
false);
this.ctx.closePath();
this.ctx.fill();
};
function Rotated(ctx, body, delegate) {
this.body = body ;
this.delegate = delegate;
this.ctx = ctx ;
}
Rotated.prototype.step = function(timeSinceLastFrame) {
var worldPosition = this.body.GetPosition() ;
var screenPosition = MathUtil.worldToScreen(worldPosition) ;
this.ctx.save();
this.ctx.translate(screenPosition.x, screenPosition.y);
this.ctx.rotate(this.body.GetAngle());
this.delegate.render(timeSinceLastFrame) ;
this.ctx.restore() ;
};
function Deck(ctx, length, thickness) {
this.ctx = ctx ;
this.lengthPxls = MathUtil.worldLengthToScreen(length) ;
this.thicknessPxls = MathUtil.worldLengthToScreen(thickness) ;
}
Deck.prototype.render = function() {
this.ctx.fillStyle = "#00ff00";
this.ctx.fillRect(-this.lengthPxls/2, -this.thicknessPxls/2,
this.lengthPxls, this.thicknessPxls);
}
function Sk8board(world, ctx, sizes) {
this.world = world ;
this.ctx = ctx ;
sizes = sizes || {} ;
this.sizes = {} ;
// According to http://defekt.se/2010/04/den-standardiserade-skateboarden/
this.sizes.wheelRadius = sizes.wheelRadius || 0.05 ;
this.sizes.boardThickness = sizes.boardThickness || 0.02 ;
this.sizes.boardLength = sizes.boardLength || 0.82 ;
this.sizes.truckOffset = sizes.truckOffset || 0.18 ;
}
Sk8board.prototype.init = function(bodies, joints) {
var bodyDef = new Box2D.Dynamics.b2BodyDef();
var fixDef = new Box2D.Dynamics.b2FixtureDef();
fixDef.density = 1.0;
fixDef.friction = 0.9;
fixDef.restitution = 0.1;
fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(this.sizes.wheelRadius);
// Back wheel
bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
bodyDef.position.x = this.sizes.wheelRadius;
bodyDef.position.y = this.sizes.wheelRadius;
var backwheel = this.world.CreateBody(bodyDef);
backwheel.CreateFixture(fixDef);
bodies.push(backwheel) ;
Actors.addActor(new Wheel(this.ctx, backwheel, this.sizes.wheelRadius)) ;
// Front wheel
bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
bodyDef.position.x = this.sizes.boardLength-this.sizes.wheelRadius;
bodyDef.position.y = this.sizes.wheelRadius;
var frontwheel = this.world.CreateBody(bodyDef);
frontwheel.CreateFixture(fixDef);
bodies.push(frontwheel) ;
Actors.addActor(new Wheel(this.ctx, frontwheel, this.sizes.wheelRadius)) ;
// Deck
fixDef.shape = new Box2D.Collision.Shapes.b2PolygonShape();
fixDef.shape.SetAsBox(this.sizes.boardLength / 2, this.sizes.boardThickness / 2);
bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
bodyDef.position.x = this.sizes.boardLength / 2;
bodyDef.position.y = this.sizes.boardThickness / 2;
var board = this.world.CreateBody(bodyDef);
board.CreateFixture(fixDef);
bodies.push(board) ;
var boardRenderer = new Deck(this.ctx, this.sizes.boardLength, this.sizes.boardThickness) ;
Actors.addActor(new Rotated(this.ctx, board, boardRenderer)) ;
// Trucks
var b2JointDef = new Box2D.Dynamics.Joints.b2RevoluteJointDef();
b2JointDef.bodyA = backwheel;
b2JointDef.bodyB = board;
b2JointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(0, 0);
b2JointDef.localAnchorB =
new Box2D.Common.Math.b2Vec2(-this.sizes.boardLength/2 + this.sizes.truckOffset, this.sizes.wheelRadius);
var joint = this.world.CreateJoint(b2JointDef);
joints.push(joint);
b2JointDef.bodyA = frontwheel;
b2JointDef.bodyB = board;
b2JointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(0, 0);
b2JointDef.localAnchorB =
new Box2D.Common.Math.b2Vec2(this.sizes.boardLength/2 - this.sizes.truckOffset, this.sizes.wheelRadius);
joint = this.world.CreateJoint(b2JointDef);
joints.push(joint);
board.SetPosition(new Box2D.Common.Math.b2Vec2(0.4, 1.5));
}
function createRobot(bodies, joints, ctx, world, sizes) {
sizes = sizes || {} ;
sizes.scale = sizes.scale || 1 ;
sizes.createoffsetx = sizes.createoffsetx || 0.7*sizes.scale ;
sizes.createoffsety = sizes.createoffsety || -1.7*sizes.scale ;
var bodyDef = new Box2D.Dynamics.b2BodyDef();
bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
var fixDef = new Box2D.Dynamics.b2FixtureDef();
fixDef.density = 1.0;
fixDef.friction = 0.9;
fixDef.restitution = 0.1;
fixDef.shape = new Box2D.Collision.Shapes.b2PolygonShape();
// right leg
bodyDef.position.x = sizes.createoffsetx + (0.5*sizes.scale);
bodyDef.position.y = sizes.createoffsety + (3*sizes.scale);
fixDef.shape.SetAsBox(0.25*sizes.scale, 0.5*sizes.scale);
var rightLeg = world.CreateBody(bodyDef);
rightLeg.CreateFixture(fixDef) ;
bodies.push(rightLeg) ;
// Left leg
bodyDef.position.x = sizes.createoffsetx + (-0.5*sizes.scale);
bodyDef.position.y = sizes.createoffsety + (3*sizes.scale);
fixDef.shape.SetAsBox(0.25*sizes.scale, 0.5*sizes.scale);
var leftLeg = world.CreateBody(bodyDef);
leftLeg.CreateFixture(fixDef) ;
bodies.push(leftLeg) ;
// Right arm
bodyDef.position.x = sizes.createoffsetx + (2.25*sizes.scale);
bodyDef.position.y = sizes.createoffsety + (1.5*sizes.scale);
fixDef.shape.SetAsBox(0.25*sizes.scale, 0.5*sizes.scale);
var rightArm = world.CreateBody(bodyDef);
rightArm.CreateFixture(fixDef) ;
bodies.push(rightArm) ;
// Left arm
bodyDef.position.x = sizes.createoffsetx + (0.5*sizes.scale);
bodyDef.position.y = sizes.createoffsety + (1.5*sizes.scale);
fixDef.shape.SetAsBox(0.25*sizes.scale, 0.5*sizes.scale);
var leftArm = world.CreateBody(bodyDef);
leftArm.CreateFixture(fixDef) ;
bodies.push(leftArm) ;
// Body
bodyDef.position.x = sizes.createoffsetx + (1.25*sizes.scale);
bodyDef.position.y = sizes.createoffsety + (1.25*sizes.scale);
fixDef.shape.SetAsArray([
new Box2D.Common.Math.b2Vec2(-0.75 * sizes.scale, -0.75 * sizes.scale),
new Box2D.Common.Math.b2Vec2(-0.25 * sizes.scale, -1.25 * sizes.scale),
new Box2D.Common.Math.b2Vec2(0.25 * sizes.scale, -1.25 * sizes.scale),
new Box2D.Common.Math.b2Vec2(0.75 * sizes.scale, -0.75 * sizes.scale),
new Box2D.Common.Math.b2Vec2(0.75 * sizes.scale, 1.25 * sizes.scale),
new Box2D.Common.Math.b2Vec2(-0.75 * sizes.scale, 1.25 * sizes.scale)
]);
var body = world.CreateBody(bodyDef) ;
body.CreateFixture(fixDef) ;
bodies.push(body) ;
// Arm joints
var b2JointDef = new Box2D.Dynamics.Joints.b2RevoluteJointDef();
b2JointDef.bodyA = body;
var joint ;
// Right arm
b2JointDef.bodyB = rightArm;
b2JointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(0.75*sizes.scale, -0.25*sizes.scale);
b2JointDef.localAnchorB =
new Box2D.Common.Math.b2Vec2(-0.25*sizes.scale, -0.5*sizes.scale);
b2JointDef.lowerAngle = -Math.PI ;
b2JointDef.upperAngle = 0.5 ;
b2JointDef.enableLimit = true ;
joint = world.CreateJoint(b2JointDef);
joints.push(joint);
// Left arm
b2JointDef.bodyB = leftArm;
b2JointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(-0.75*sizes.scale, -0.25*sizes.scale);
b2JointDef.localAnchorB =
new Box2D.Common.Math.b2Vec2(0.25*sizes.scale, -0.5*sizes.scale);
b2JointDef.lowerAngle = -0.5 ;
b2JointDef.upperAngle = Math.PI;
b2JointDef.enableLimit = true ;
joint = world.CreateJoint(b2JointDef);
joints.push(joint);
// Leg joints
b2JointDef = new Box2D.Dynamics.Joints.b2PrismaticJointDef();
b2JointDef.bodyA = body;
b2JointDef.localAxisA = new Box2D.Common.Math.b2Vec2(0,1);
b2JointDef.lowerTranslation = -0.5*sizes.scale ;
b2JointDef.upperTranslation = 0.5*sizes.scale ;
b2JointDef.enableLimit = true ;
// Right leg
b2JointDef.bodyB = rightLeg;
b2JointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(0.5*sizes.scale, 1.25*sizes.scale);
b2JointDef.localAnchorB =
new Box2D.Common.Math.b2Vec2(0*sizes.scale, -0.5*sizes.scale);
joint = world.CreateJoint(b2JointDef);
joints.push(joint);
// Left leg
b2JointDef.bodyB = leftLeg;
b2JointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(-0.5*sizes.scale, 1.25*sizes.scale);
b2JointDef.localAnchorB =
new Box2D.Common.Math.b2Vec2(0*sizes.scale, -0.5*sizes.scale);
joint = world.CreateJoint(b2JointDef);
joints.push(joint);
} | JavaScript |
/*
Copyright 2011 Johan Maasing
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var gameWorld;
window.onload = function() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
gameWorld = new World(ctx);
gameWorld.init();
}
function reset() {
gameWorld.reset();
}
// Global constants
var pixelsPerMeter = 40;
var worldWidthInMeter = 16; // 640/pixelsPerMeter ;
var worldHeightInMeter = 12; // 480/pixelsPerMeter ;
var groundHalfWidth = 0.5;
var numberOfLinks = 16;
var linkRadius = 0.2;
function World(ctx) {
this.bodies = new Array();
this.joints = new Array();
this.world = new Box2D.Dynamics.b2World(
new Box2D.Common.Math.b2Vec2(0, 10), true);
this.ctx = ctx;
}
function bind(obj, fn) {
return function() {
fn.call(obj) ;
};
}
World.prototype = {
init : function() {
var fixDef = new Box2D.Dynamics.b2FixtureDef();
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = 0.2;
var bodyDef = new Box2D.Dynamics.b2BodyDef();
bodyDef.type = Box2D.Dynamics.b2Body.b2_staticBody;
// create ground
bodyDef.position.x = worldWidthInMeter / 2;
bodyDef.position.y = worldHeightInMeter + groundHalfWidth;
fixDef.shape = new Box2D.Collision.Shapes.b2PolygonShape();
fixDef.shape.SetAsBox(worldWidthInMeter / 2, groundHalfWidth);
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
// Left wall
bodyDef.position.x = -groundHalfWidth;
bodyDef.position.y = worldHeightInMeter / 2;
fixDef.shape = new Box2D.Collision.Shapes.b2PolygonShape();
fixDef.shape.SetAsBox(groundHalfWidth, worldHeightInMeter / 2);
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
// Right wall
bodyDef.position.x = worldWidthInMeter + groundHalfWidth; // center
bodyDef.position.y = worldHeightInMeter / 2; // bottom
fixDef.shape = new Box2D.Collision.Shapes.b2PolygonShape();
fixDef.shape.SetAsBox(groundHalfWidth, worldHeightInMeter / 2);
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
// Pyramid
bodyDef.position.x = worldWidthInMeter / 2 + 0.3;
bodyDef.position.y = worldHeightInMeter - groundHalfWidth*4;
fixDef.shape = new Box2D.Collision.Shapes.b2PolygonShape();
fixDef.shape.SetAsBox(worldWidthInMeter / 8, groundHalfWidth*3);
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
this.initBodies();
// setup debug draw
var debugDraw = new Box2D.Dynamics.b2DebugDraw();
debugDraw.SetSprite(this.ctx);
debugDraw.SetDrawScale(pixelsPerMeter);
debugDraw.SetFillAlpha(0.6);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(Box2D.Dynamics.b2DebugDraw.e_shapeBit
| Box2D.Dynamics.b2DebugDraw.e_jointBit);
this.world.SetDebugDraw(debugDraw);
var callback = bind(this, this.update) ;
window.setInterval(callback, 1000 / 30);
},
reset : function() {
// Destroy the existing joints
for ( var n = 0; n < this.joints.length; n++) {
this.world.DestroyJoint(this.joints[n]);
}
// Destroy the existing bodies
for ( var n = 0; n < this.bodies.length; n++) {
this.world.DestroyBody(this.bodies[n]);
}
this.bodies = new Array();
this.initBodies();
},
initBodies : function() {
var fixDef = new Box2D.Dynamics.b2FixtureDef();
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = 0.2;
// 0.1 meter radius
fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(linkRadius);
var bodyDef = new Box2D.Dynamics.b2BodyDef();
bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
// Create chain
var b2JointDef = new Box2D.Dynamics.Joints.b2RevoluteJointDef();
b2JointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(linkRadius, 0);
b2JointDef.localAnchorB = new Box2D.Common.Math.b2Vec2(-linkRadius, 0);
var linkOffsetX = worldWidthInMeter / 2 - linkRadius * numberOfLinks;
var previousLink;
for ( var n = 0; n < numberOfLinks; n++) {
bodyDef.position.x = linkOffsetX + linkRadius * 2 * n;
bodyDef.position.y = 0.1;
var link = this.world.CreateBody(bodyDef);
link.CreateFixture(fixDef);
this.bodies.push(link);
if (previousLink) {
b2JointDef.bodyA = previousLink;
b2JointDef.bodyB = link;
var joint = this.world.CreateJoint(b2JointDef);
this.joints.push(joint);
}
previousLink = link;
}
},
update : function() {
this.world.Step(1 / 30 // frame-rate
, 10 // velocity iterations
, 10 // position iterations
);
this.world.DrawDebugData();
this.world.ClearForces();
}
};
| JavaScript |
/**
*
*/
var world;
var pixelsPerMeter = 40;
var worldWidthInMeter = 16; // 640/pixelsPerMeter ;
var worldHeightInMeter = 12; // 480/pixelsPerMeter ;
var groundHalfWidth = 0.5;
var trailcircle;
var trailcircleBody;
var crateBody;
var halfCrateWidthInMeters = 0.1;
var halfCrateHeightInMeters = 1.0;
var halfCrateWidthInPixels = (halfCrateWidthInMeters * pixelsPerMeter);
var halfCrateHeightInPixels = (halfCrateHeightInMeters * pixelsPerMeter);
var unnamedBodies = new Array() ;
var ctx;
// Name alias
var b2Vec2 = Box2D.Common.Math.b2Vec2, b2BodyDef = Box2D.Dynamics.b2BodyDef, b2Body = Box2D.Dynamics.b2Body, b2FixtureDef = Box2D.Dynamics.b2FixtureDef, b2Fixture = Box2D.Dynamics.b2Fixture, b2World = Box2D.Dynamics.b2World, b2MassData = Box2D.Collision.Shapes.b2MassData, b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape, b2CircleShape = Box2D.Collision.Shapes.b2CircleShape, b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
function init() {
world = new b2World(new b2Vec2(0, 10) // gravity
, true // allow sleep
);
var fixDef = new b2FixtureDef;
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = 0.2;
var bodyDef = new b2BodyDef;
// create ground
bodyDef.type = b2Body.b2_staticBody;
bodyDef.position.x = worldWidthInMeter / 2; // center
bodyDef.position.y = worldHeightInMeter + groundHalfWidth; // bottom
fixDef.shape = new b2PolygonShape;
fixDef.shape.SetAsBox(worldWidthInMeter / 2, groundHalfWidth);
world.CreateBody(bodyDef).CreateFixture(fixDef);
// Left wall
bodyDef.position.x = -groundHalfWidth;
bodyDef.position.y = worldHeightInMeter / 2;
fixDef.shape = new b2PolygonShape;
fixDef.shape.SetAsBox(groundHalfWidth, worldHeightInMeter / 2);
world.CreateBody(bodyDef).CreateFixture(fixDef);
// Right wall
bodyDef.position.x = worldWidthInMeter + groundHalfWidth; // center
bodyDef.position.y = worldHeightInMeter / 2; // bottom
fixDef.shape = new b2PolygonShape;
fixDef.shape.SetAsBox(groundHalfWidth, worldHeightInMeter / 2);
world.CreateBody(bodyDef).CreateFixture(fixDef);
ctx = document.getElementById("canvas").getContext("2d");
// setup debug draw
var debugDraw = new b2DebugDraw();
debugDraw.SetSprite(ctx);
debugDraw.SetDrawScale(pixelsPerMeter);
debugDraw.SetFillAlpha(0.6);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
world.SetDebugDraw(debugDraw);
initBodies();
window.setInterval(update, 1000 / 30);
};
function reset() {
for (var n=0; n<unnamedBodies.length; n++) {
world.DestroyBody(unnamedBodies[n]) ;
}
unnamedBodies = new Array() ;
world.DestroyBody(trailcircleBody) ;
world.DestroyBody(crateBody) ;
initBodies() ;
}
function initBodies() {
var fixDef = new b2FixtureDef;
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = 0.2;
var bodyDef = new b2BodyDef;
// create some objects
bodyDef.type = b2Body.b2_dynamicBody;
for ( var i = 0; i < 8; ++i) {
if (Math.random() > 0.5) {
fixDef.shape = new b2PolygonShape;
fixDef.shape.SetAsBox(Math.random() + 0.1 // half width
, Math.random() + 0.1 // half height
);
} else {
fixDef.shape = new b2CircleShape(Math.random() + 0.1 // radius
);
}
bodyDef.position.x = Math.random() * (worldWidthInMeter - 3) + 1.5;
bodyDef.position.y = Math.random() * 3;
var body = world.CreateBody(bodyDef) ;
body.CreateFixture(fixDef);
unnamedBodies.push(body) ;
}
// 0.5 meter circle
var trailcircleRadiusInMeters = 0.2;
bodyDef.position.x = worldWidthInMeter / 2;
bodyDef.position.y = 0;
fixDef.shape = new b2CircleShape(trailcircleRadiusInMeters);
fixDef.restitution = 0.6;
trailcircleBody = world.CreateBody(bodyDef);
trailcircleBody.CreateFixture(fixDef);
trailcircle = new TrailCircle(ctx, {
radius : trailcircleRadiusInMeters * pixelsPerMeter,
position : {
x : 320,
y : 0
},
color : {
red : 8,
green : 255,
blue : 255
}
});
bodyDef.position.x = 5;
bodyDef.position.y = 0;
crateBody = world.CreateBody(bodyDef);
fixDef.shape = new b2PolygonShape;
fixDef.shape.SetAsBox(halfCrateWidthInMeters, halfCrateHeightInMeters);
fixDef.restitution = 0.2;
crateBody.CreateFixture(fixDef);
}
function update() {
world.Step(1 / 30 // frame-rate
, 10 // velocity iterations
, 10 // position iterations
);
world.DrawDebugData();
var position = trailcircleBody.GetPosition();
var screencoords = worldToScreenCoordinates(position);
trailcircle.setPosition(screencoords.x, screencoords.y);
trailcircle.draw();
var crateScreenPosition = worldToScreenCoordinates(crateBody.GetPosition());
ctx.save();
ctx.translate(crateScreenPosition.x, crateScreenPosition.y);
ctx.rotate(crateBody.GetAngle());
ctx.fillStyle = "#00ff00";
ctx.fillRect(-halfCrateWidthInPixels, -halfCrateHeightInPixels,
halfCrateWidthInPixels * 2, halfCrateHeightInPixels * 2);
ctx.restore();
world.ClearForces();
};
function worldToScreenCoordinates(worldPosition) {
var screenPosition = {
x : Math.floor(worldPosition.x * pixelsPerMeter),
y : Math.floor(worldPosition.y * pixelsPerMeter)
};
return screenPosition;
} | JavaScript |
var numSpeedghosts = 16;
var alphaValues = new Array();
for ( var n = 0; n < numSpeedghosts; n++) {
alphaValues[n] = (1 - ((1 / numSpeedghosts) * n));
};
function TrailCircle(ctx, appearance) {
this.ctx = ctx;
this.xpos = new Array();
this.ypos = new Array();
this.colors = new Array();
this.hidden = false;
this.radius = 5;
if ((appearance) && (appearance.radius)) {
this.radius = appearance.radius;
}
this.xpos[0] = -this.radius * 2;
this.ypos[0] = -this.radius * 2;
if ((appearance) && (appearance.position)) {
this.xpos[0] = appearance.position.x;
this.ypos[0] = appearance.position.y;
}
this.colors[0] = {
red : 255,
green : 255,
blue : 255
};
if ((appearance) && (appearance.color)) {
this.colors[0] = {
red : appearance.color.red,
green : appearance.color.green,
blue : appearance.color.blue
};
}
};
TrailCircle.prototype = {
setPosition : function(x, y) {
this.xpos[0] = x;
this.ypos[0] = y;
},
setRadius : function(radius) {
this.radius = radius ;
},
setColor : function(color) {
this.colors[0] = {
red : color.red,
green : color.green,
blue : color.blue
};
},
getColor : function() {
return {
red : this.colors[0].red,
green : this.colors[0].green,
blue : this.colors[0].blue
};
},
draw : function() {
if (!this.hidden) {
for ( var n = alphaValues.length - 1; n > -1; n--) {
if (this.xpos[n]) {
var colorValue = this.createColorValue(n);
this.ctx.fillStyle = colorValue;
var pixelx = Math.round(this.xpos[n]);
var pixely = Math.round(this.ypos[n]);
this.drawTrailCircle(pixelx, pixely);
}
if (n > 0) {
this.xpos[n] = this.xpos[n - 1];
this.ypos[n] = this.ypos[n - 1];
this.colors[n] = this.colors[n - 1];
}
}
}
},
createColorValue : function(index) {
var color = this.colors[index];
var colorValue = 'rgba(';
colorValue += color.red;
colorValue += ' ,';
colorValue += color.green;
colorValue += ' ,';
colorValue += color.blue;
colorValue += ' ,';
colorValue += alphaValues[index];
colorValue += ')';
return colorValue;
},
drawTrailCircle : function(x, y) {
this.ctx.beginPath();
this.ctx.arc(x, y, this.radius, 0, Math.PI * 2, false);
this.ctx.closePath();
this.ctx.fill();
}
}; | JavaScript |
var Actors = (function() {
var self = {};
var actors = new Array();
self.step = function(timeSinceLastFrame) {
for (var n=0; n<actors.length; n++) {
actors[n].step(timeSinceLastFrame);
}
};
self.addActor = function(actor) {
if (actor) {
actors.push(actor);
}
};
self.removeActor = function(actor) {
actors = actors.filter(function(curValue, curIndex, curArray)
{ return (element != actor); }
);
};
self.clear = function() {
actors = new Array();
};
return self;
}());
var MathUtil = (function() {
var self = {};
self.worldToScreen = function(wp) {
var sp = {};
sp.x = Math.round(wp.x * 40);
sp.y = Math.round(wp.y * 40);
return sp;
};
self.worldLengthToScreen = function(length) {
return Math.max(1, Math.round(length * 40));
};
self.slope = function(a, b) {
return (a.y - b.y) / (a.x - b.x);
};
self.screenToWorld = function(screenPosition) {
var worldPosition = {
x : parseFloat(screenPosition.x / 40.0),
y : parseFloat(screenPosition.y / 40.0)
};
return worldPosition;
};
return self;
}());
function Wheel(ctx, body, radius) {
this.ctx = ctx;
this.body = body;
this.radius = MathUtil.worldLengthToScreen(radius);
}
Wheel.prototype.step = function(timeSinceLastFrame) {
var worldPosition = this.body.GetPosition();
var screenPosition = MathUtil.worldToScreen(worldPosition);
console.log("screenposition x" + screenPosition.x);
this.ctx.fillStyle = "#ff0000";
this.ctx.beginPath();
this.ctx.arc(
screenPosition.x,
screenPosition.y,
this.radius,
0,
Math.PI * 2,
false);
this.ctx.closePath();
this.ctx.fill();
};
function Rotated(ctx, body, delegate) {
this.body = body;
this.delegate = delegate;
this.ctx = ctx;
}
Rotated.prototype.step = function(timeSinceLastFrame) {
var worldPosition = this.body.GetPosition();
var screenPosition = MathUtil.worldToScreen(worldPosition);
this.ctx.save();
this.ctx.translate(screenPosition.x, screenPosition.y);
this.ctx.rotate(this.body.GetAngle());
this.delegate.render(timeSinceLastFrame);
this.ctx.restore();
};
function Board(ctx, body, length, thickness) {
this.body = body;
this.ctx = ctx;
this.lengthPxls = MathUtil.worldLengthToScreen(length);
this.thicknessPxls = MathUtil.worldLengthToScreen(thickness);
}
Board.prototype.render = function(timeSinceLastFrame) {
this.ctx.fillStyle = "#00ff00";
this.ctx.fillRect(-this.lengthPxls/2, -this.thicknessPxls/2,
this.lengthPxls, this.thicknessPxls);
};
| JavaScript |
(function() {
var SkateBoard, World, b2Body, b2BodyDef, b2CircleShape, b2DebugDraw, b2DynamicBody, b2Fixture, b2FixtureDef, b2MassData, b2PolygonShape, b2RevoluteJointDef, b2StaticBody, b2Vec2, b2World, createFixture, screenToWorld, worldPositionToScreenPosition, worldToScreen;
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
window.onload = function() {
var Line, b2dWorld, canvas, line, skateboard, world;
Line = window.Line;
console.log(Line);
canvas = document.getElementById("canvas");
b2dWorld = new b2World(new b2Vec2(0, 10), true);
world = new World(b2dWorld, canvas);
skateboard = new SkateBoard(b2dWorld, canvas);
line = null;
window.ollie = function() {
return skateboard.ollie(document.getElementById("x").value, document.getElementById("y").value);
};
window.update = __bind(function() {
world.setDebug(document.getElementById("debug").value);
return world.update();
}, this);
canvas.onmousedown = __bind(function(e) {
line = new Line(b2dWorld, canvas);
return line.setStart(e);
}, this);
canvas.onmouseup = __bind(function(e) {
if (line != null) {
line.setEnd(e);
line.render();
line.create();
world.addActor(line);
return line = null;
}
}, this);
canvas.onmousemove = __bind(function(e) {
if (line != null) {
canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
line.setEnd(e);
return line.render();
}
}, this);
window.play = function() {
skateboard.create();
return world.addActor(skateboard);
};
return setInterval(window.update, 1000 / 30);
};
b2Vec2 = Box2D.Common.Math.b2Vec2;
b2BodyDef = Box2D.Dynamics.b2BodyDef;
b2Body = Box2D.Dynamics.b2Body;
b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
b2Fixture = Box2D.Dynamics.b2Fixture;
b2World = Box2D.Dynamics.b2World;
b2MassData = Box2D.Collision.Shapes.b2MassData;
b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
b2StaticBody = Box2D.Dynamics.b2Body.b2_staticBody;
b2DynamicBody = Box2D.Dynamics.b2Body.b2_dynamicBody;
b2RevoluteJointDef = Box2D.Dynamics.Joints.b2RevoluteJointDef;
createFixture = function(density, friction, restitution) {
var fixDef;
fixDef = new b2FixtureDef();
fixDef.density = density;
fixDef.friction = friction;
fixDef.restitution = restitution;
return fixDef;
};
worldPositionToScreenPosition = function(wp) {
return {
x: Math.round(wp.x * 40),
y: Math.round(wp.y * 40)
};
};
screenToWorld = function(sp) {
return {
x: parseFloat(sp.x / 40.0),
y: parseFloat(sp.y / 40.0)
};
};
worldToScreen = function(length) {
return Math.max(1, Math.round(length * 40));
};
World = (function() {
function World(world, canvas) {
this.world = world;
this.canvas = canvas;
this.ctx = this.canvas.getContext("2d");
this.pixelsPerMeter = 40;
this.worldWidthInMeter = 16;
this.worldHeightInMeter = 12;
this.groundHalfWidth = 0.5;
this.actors = [];
this.debug = false;
this.setUpDebugDraw();
this.create();
}
World.prototype.create = function() {
var bodyDef, fixDef;
fixDef = createFixture(1.0, 0.5, 0.2);
fixDef.shape = new b2PolygonShape();
fixDef.shape.SetAsBox(this.worldWidthInMeter / 2, this.groundHalfWidth);
bodyDef = new b2BodyDef();
bodyDef.type = b2StaticBody;
bodyDef.position.Set(this.worldWidthInMeter / 2, this.worldHeightInMeter + this.groundHalfWidth);
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
bodyDef.position.Set(-this.groundHalfWidth, this.worldHeightInMeter / 2);
fixDef.shape.SetAsBox(this.groundHalfWidth, this.worldHeightInMeter / 2);
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
bodyDef.position.Set(this.worldWidthInMeter + this.groundHalfWidth, this.worldHeightInMeter / 2);
fixDef.shape.SetAsBox(this.groundHalfWidth, this.worldHeightInMeter / 2);
return this.world.CreateBody(bodyDef).CreateFixture(fixDef);
};
World.prototype.setDebug = function(debug) {
if (debug) {
return this.debug = true;
} else {
return this.debug = false;
}
};
World.prototype.setUpDebugDraw = function() {
var debugDraw;
debugDraw = new b2DebugDraw();
debugDraw.SetSprite(this.ctx);
debugDraw.SetDrawScale(this.pixelsPerMeter);
debugDraw.SetFillAlpha(0.9);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(Box2D.Dynamics.b2DebugDraw.e_shapeBit | Box2D.Dynamics.b2DebugDraw.e_jointBit);
return this.world.SetDebugDraw(debugDraw);
};
World.prototype.addActor = function(actor) {
return this.actors.push(actor);
};
World.prototype.update = function() {
var actor, _i, _len, _ref;
this.world.Step(1 / 30, 10, 10);
this.ctx.clearRect(0, 0, canvas.width, canvas.height);
_ref = this.actors;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
actor = _ref[_i];
actor.step(0);
}
if (this.debug) {
this.world.DrawDebugData();
}
return this.world.ClearForces();
};
return World;
})();
SkateBoard = (function() {
function SkateBoard(world, canvas) {
this.world = world;
this.canvas = canvas;
this.ctx = this.canvas.getContext("2d");
this.wheelRadius = 0.05;
this.boardThickness = 0.02;
this.boardLength = 0.82;
this.truckOffset = 0.18;
this.lengthPxls = worldToScreen(this.boardLength);
this.thicknessPxls = worldToScreen(this.boardThickness);
this.board;
this.fronwheel;
this.backwheel;
}
SkateBoard.prototype.create = function() {
var b2JointDef, bodyDef, fixDef, joint;
bodyDef = new b2BodyDef();
fixDef = createFixture(1.0, 0.9, 0.1);
fixDef.shape = new b2CircleShape(this.wheelRadius);
bodyDef.type = b2DynamicBody;
bodyDef.position.Set(this.wheelRadius, this.wheelRadius);
this.backwheel = this.world.CreateBody(bodyDef);
this.backwheel.CreateFixture(fixDef);
bodyDef.position.Set(this.boardLength - this.wheelRadius, this.wheelRadius);
this.frontwheel = this.world.CreateBody(bodyDef);
this.frontwheel.CreateFixture(fixDef);
fixDef.shape = new b2PolygonShape();
fixDef.shape.SetAsBox(this.boardLength / 2, this.boardThickness / 2);
bodyDef.position.Set(this.boardLength / 2, this.boardThickness / 2);
this.board = this.world.CreateBody(bodyDef);
this.board.CreateFixture(fixDef);
b2JointDef = new b2RevoluteJointDef();
b2JointDef.bodyA = this.backwheel;
b2JointDef.bodyB = this.board;
b2JointDef.localAnchorA = new b2Vec2(0, 0);
b2JointDef.localAnchorB = new b2Vec2(-this.boardLength / 2 + this.truckOffset, this.wheelRadius);
joint = this.world.CreateJoint(b2JointDef);
b2JointDef.bodyA = this.frontwheel;
b2JointDef.bodyB = this.board;
b2JointDef.localAnchorA = new b2Vec2(0, 0);
b2JointDef.localAnchorB = new b2Vec2(this.boardLength / 2 - this.truckOffset, this.wheelRadius);
joint = this.world.CreateJoint(b2JointDef);
return this.board.SetPosition(new b2Vec2(0.8, 1.5));
};
SkateBoard.prototype.step = function(timeSinceLastStep) {
var screenPosition, worldPosition;
worldPosition = this.board.GetPosition();
screenPosition = worldPositionToScreenPosition(worldPosition);
this.ctx.save();
this.ctx.translate(screenPosition.x, screenPosition.y);
this.ctx.rotate(this.board.GetAngle());
this.render(timeSinceLastStep);
this.ctx.restore();
this.renderWheel(this.backwheel);
return this.renderWheel(this.frontwheel);
};
SkateBoard.prototype.render = function() {
this.ctx.fillStyle = "#00ff00";
return this.ctx.fillRect(-this.lengthPxls / 2, -this.thicknessPxls / 2, this.lengthPxls, this.thicknessPxls);
};
SkateBoard.prototype.renderWheel = function(wheel) {
var screenPosition, worldPosition;
worldPosition = wheel.GetPosition();
screenPosition = worldPositionToScreenPosition(worldPosition);
this.ctx.fillStyle = "#ff0000";
this.ctx.beginPath();
this.ctx.arc(screenPosition.x, screenPosition.y, worldToScreen(this.wheelRadius), 0, Math.PI * 2, false);
this.ctx.closePath();
return this.ctx.fill();
};
SkateBoard.prototype.ollie = function(x, y) {
var localCenter;
localCenter = this.board.GetLocalCenter().Copy();
localCenter.x -= this.boardLength / 2.0;
return this.board.ApplyImpulse(new b2Vec2(x, y), localCenter);
};
return SkateBoard;
})();
}).call(this);
| JavaScript |
(function() {
var BaseRenderer, Line, SkateBoard, World, b2Body, b2BodyDef, b2CircleShape, b2DebugDraw, b2DynamicBody, b2Fixture, b2FixtureDef, b2MassData, b2PolygonShape, b2RevoluteJointDef, b2StaticBody, b2Vec2, b2World, createFixture, screenToWorld, worldPositionToScreenPosition, worldToScreen;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor;
child.__super__ = parent.prototype;
return child;
}, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
BaseRenderer = (function() {
function BaseRenderer(world, canvas) {
this.world = world;
this.canvas = canvas;
this.ctx = this.canvas.getContext("2d");
this.canvasPosition = this.getElementPosition(canvas);
}
BaseRenderer.prototype.getElementPosition = function(element) {
var elem, tagname, x, y;
elem = element;
tagname = "";
x = 0;
y = 0;
while ((typeof elem === "object") && (typeof elem.tagName !== "undefined")) {
y += elem.offsetTop;
x += elem.offsetLeft;
tagname = elem.tagName.toUpperCase();
if (tagname === "BODY") {
elem = 0;
}
if (typeof elem === "object") {
if (typeof elem.offsetParent === "object") {
elem = elem.offsetParent;
}
}
}
return {
x: x,
y: y
};
};
return BaseRenderer;
})();
SkateBoard = (function() {
__extends(SkateBoard, BaseRenderer);
function SkateBoard(b2dWorld, canvas) {
this.b2dWorld = b2dWorld;
this.canvas = canvas;
SkateBoard.__super__.constructor.call(this, this.b2dWorld, this.canvas);
this.wheelRadius = 0.15;
this.boardThickness = 0.02;
this.boardLength = 0.82;
this.truckOffset = 0.18;
this.lengthPxls = worldToScreen(this.boardLength);
this.thicknessPxls = worldToScreen(this.boardThickness);
this.board;
this.fronwheel;
this.backwheel;
}
SkateBoard.prototype.create = function() {
var b2JointDef, bodyDef, fixDef, joint;
bodyDef = new b2BodyDef();
fixDef = createFixture(1.0, 0.9, 0.1);
fixDef.shape = new b2CircleShape(this.wheelRadius);
bodyDef.type = b2DynamicBody;
bodyDef.position.Set(this.wheelRadius, this.wheelRadius);
this.backwheel = this.b2dWorld.CreateBody(bodyDef);
this.backwheel.CreateFixture(fixDef);
bodyDef.position.Set(this.boardLength - this.wheelRadius, this.wheelRadius);
this.frontwheel = this.b2dWorld.CreateBody(bodyDef);
this.frontwheel.CreateFixture(fixDef);
fixDef.shape = new b2PolygonShape();
fixDef.shape.SetAsBox(this.boardLength / 2, this.boardThickness / 2);
bodyDef.position.Set(this.boardLength / 2, this.boardThickness / 2);
this.board = this.b2dWorld.CreateBody(bodyDef);
this.board.CreateFixture(fixDef);
b2JointDef = new b2RevoluteJointDef();
b2JointDef.bodyA = this.backwheel;
b2JointDef.bodyB = this.board;
b2JointDef.localAnchorA = new b2Vec2(0, 0);
b2JointDef.localAnchorB = new b2Vec2(-this.boardLength / 2 + this.truckOffset, this.wheelRadius);
joint = this.b2dWorld.CreateJoint(b2JointDef);
b2JointDef.bodyA = this.frontwheel;
b2JointDef.bodyB = this.board;
b2JointDef.localAnchorA = new b2Vec2(0, 0);
b2JointDef.localAnchorB = new b2Vec2(this.boardLength / 2 - this.truckOffset, this.wheelRadius);
joint = this.b2dWorld.CreateJoint(b2JointDef);
return this.board.SetPosition(new b2Vec2(0.8, 1.5));
};
SkateBoard.prototype.step = function(timeSinceLastStep) {
var screenPosition, worldPosition;
worldPosition = this.board.GetPosition();
screenPosition = worldPositionToScreenPosition(worldPosition);
console.log(this.ctx);
this.ctx.save();
this.ctx.translate(screenPosition.x, screenPosition.y);
this.ctx.rotate(this.board.GetAngle());
this.render(timeSinceLastStep);
this.ctx.restore();
this.renderWheel(this.backwheel);
return this.renderWheel(this.frontwheel);
};
SkateBoard.prototype.render = function() {
this.ctx.fillStyle = "#00ff00";
return this.ctx.fillRect(-this.lengthPxls / 2, -this.thicknessPxls / 2, this.lengthPxls, this.thicknessPxls);
};
SkateBoard.prototype.renderWheel = function(wheel) {
var screenPosition, worldPosition;
worldPosition = wheel.GetPosition();
screenPosition = worldPositionToScreenPosition(worldPosition);
this.ctx.fillStyle = "#ff0000";
this.ctx.beginPath();
this.ctx.arc(screenPosition.x, screenPosition.y, worldToScreen(this.wheelRadius), 0, Math.PI * 2, false);
this.ctx.closePath();
return this.ctx.fill();
};
SkateBoard.prototype.ollie = function(x, y) {
var localCenter;
localCenter = this.board.GetLocalCenter().Copy();
localCenter.x -= this.boardLength / 2.0;
return this.board.ApplyImpulse(new b2Vec2(x, y), localCenter);
};
return SkateBoard;
})();
Line = (function() {
__extends(Line, BaseRenderer);
function Line(b2dWorld, canvas) {
this.b2dWorld = b2dWorld;
Line.__super__.constructor.call(this, this.b2dWorld, canvas);
this.start = {};
this.end = {};
this.mouseIsDown;
}
Line.prototype.setStart = function(e) {
this.start.x = e.clientX - this.canvasPosition.x;
return this.start.y = e.clientY - this.canvasPosition.y;
};
Line.prototype.setEnd = function(e) {
this.end.x = e.clientX - this.canvasPosition.x;
return this.end.y = e.clientY - this.canvasPosition.y;
};
Line.prototype.step = function() {
return this.render();
};
Line.prototype.render = function() {
this.ctx.strokeStyle = "#000";
this.ctx.beginPath();
this.ctx.moveTo(this.start.x, this.start.y);
this.ctx.lineTo(this.end.x, this.end.y);
this.ctx.stroke();
return this.ctx.closePath();
};
Line.prototype.create = function() {
var bodyDef, end, fixDef, start, vertices;
if (!(this.start && this.end)) {
return;
}
start = screenToWorld(this.start);
end = screenToWorld(this.end);
bodyDef = new b2BodyDef();
bodyDef.position.Set(0.0, 0.0);
fixDef = createFixture(1.0, 0.5, 0.2);
fixDef.shape = new b2PolygonShape();
vertices = [new Box2D.Common.Math.b2Vec2(start.x, start.y), new Box2D.Common.Math.b2Vec2(end.x, end.y), new Box2D.Common.Math.b2Vec2(end.x, end.y + 0.01), new Box2D.Common.Math.b2Vec2(start.x, start.y + 0.01)];
fixDef.shape.SetAsArray(vertices, vertices.length);
return this.b2dWorld.CreateBody(bodyDef).CreateFixture(fixDef);
};
return Line;
})();
window.onload = function() {
var b2dWorld, canvas, line, skateboard, world;
canvas = document.getElementById("canvas");
b2dWorld = new b2World(new b2Vec2(0, 10), true);
world = new World(b2dWorld, canvas);
skateboard = new SkateBoard(b2dWorld, canvas);
line = new Line(b2dWorld, canvas);
window.ollie = function() {
return skateboard.ollie(document.getElementById("x").value, document.getElementById("y").value);
};
window.update = __bind(function() {
world.setDebug(document.getElementById("debug").value);
return world.update();
}, this);
canvas.onmousedown = __bind(function(e) {
line = new Line(b2dWorld, canvas);
return line.setStart(e);
}, this);
canvas.onmouseup = __bind(function(e) {
if (line != null) {
line.setEnd(e);
line.render();
line.create();
world.addActor(line);
return line = null;
}
}, this);
canvas.onmousemove = __bind(function(e) {
if (line != null) {
canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
line.setEnd(e);
return line.render();
}
}, this);
window.play = function() {
skateboard.create();
return world.addActor(skateboard);
};
return setInterval(window.update, 1000 / 30);
};
b2Vec2 = Box2D.Common.Math.b2Vec2;
b2BodyDef = Box2D.Dynamics.b2BodyDef;
b2Body = Box2D.Dynamics.b2Body;
b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
b2Fixture = Box2D.Dynamics.b2Fixture;
b2World = Box2D.Dynamics.b2World;
b2MassData = Box2D.Collision.Shapes.b2MassData;
b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
b2StaticBody = Box2D.Dynamics.b2Body.b2_staticBody;
b2DynamicBody = Box2D.Dynamics.b2Body.b2_dynamicBody;
b2RevoluteJointDef = Box2D.Dynamics.Joints.b2RevoluteJointDef;
createFixture = function(density, friction, restitution) {
var fixDef;
fixDef = new b2FixtureDef();
fixDef.density = density;
fixDef.friction = friction;
fixDef.restitution = restitution;
return fixDef;
};
worldPositionToScreenPosition = function(wp) {
return {
x: Math.round(wp.x * 40),
y: Math.round(wp.y * 40)
};
};
screenToWorld = function(sp) {
return {
x: parseFloat(sp.x / 40.0),
y: parseFloat(sp.y / 40.0)
};
};
worldToScreen = function(length) {
return Math.max(1, Math.round(length * 40));
};
World = (function() {
function World(world, canvas) {
this.world = world;
this.canvas = canvas;
this.ctx = this.canvas.getContext("2d");
this.pixelsPerMeter = 40;
this.worldWidthInMeter = 16;
this.worldHeightInMeter = 12;
this.groundHalfWidth = 0.5;
this.actors = [];
this.debug = false;
this.setUpDebugDraw();
this.create();
}
World.prototype.create = function() {
var bodyDef, fixDef;
fixDef = createFixture(1.0, 0.5, 0.2);
fixDef.shape = new b2PolygonShape();
fixDef.shape.SetAsBox(this.worldWidthInMeter / 2, this.groundHalfWidth);
bodyDef = new b2BodyDef();
bodyDef.type = b2StaticBody;
bodyDef.position.Set(this.worldWidthInMeter / 2, this.worldHeightInMeter + this.groundHalfWidth);
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
bodyDef.position.Set(-this.groundHalfWidth, this.worldHeightInMeter / 2);
fixDef.shape.SetAsBox(this.groundHalfWidth, this.worldHeightInMeter / 2);
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
bodyDef.position.Set(this.worldWidthInMeter + this.groundHalfWidth, this.worldHeightInMeter / 2);
fixDef.shape.SetAsBox(this.groundHalfWidth, this.worldHeightInMeter / 2);
return this.world.CreateBody(bodyDef).CreateFixture(fixDef);
};
World.prototype.setDebug = function(debug) {
if (debug) {
return this.debug = true;
} else {
return this.debug = false;
}
};
World.prototype.setUpDebugDraw = function() {
var debugDraw;
debugDraw = new b2DebugDraw();
debugDraw.SetSprite(this.ctx);
debugDraw.SetDrawScale(this.pixelsPerMeter);
debugDraw.SetFillAlpha(0.9);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(Box2D.Dynamics.b2DebugDraw.e_shapeBit | Box2D.Dynamics.b2DebugDraw.e_jointBit);
return this.world.SetDebugDraw(debugDraw);
};
World.prototype.addActor = function(actor) {
return this.actors.push(actor);
};
World.prototype.update = function() {
var actor, _i, _len, _ref;
this.world.Step(1 / 30, 10, 10);
this.ctx.clearRect(0, 0, canvas.width, canvas.height);
_ref = this.actors;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
actor = _ref[_i];
actor.step(0);
}
if (this.debug) {
this.world.DrawDebugData();
}
return this.world.ClearForces();
};
return World;
})();
}).call(this);
| JavaScript |
/*
Copyright 2011 Johan Maasing
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var gameWorld;
window.onload = function() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
gameWorld = new World(ctx);
gameWorld.init();
}
function reset() {
gameWorld.reset();
}
function fire() {
gameWorld.fireCannonball();
}
// Global constants
var pixelsPerMeter = 40;
var worldWidthInMeter = 16; // 640/pixelsPerMeter ;
var worldHeightInMeter = 12; // 480/pixelsPerMeter ;
var groundHalfWidth = 0.5;
var numberOfLinks = 20;
var linkRadius = 0.2;
function World(ctx) {
this.bodies = new Array();
this.joints = new Array();
this.world = new Box2D.Dynamics.b2World(
new Box2D.Common.Math.b2Vec2(0, 10), true);
this.ctx = ctx;
this.chainAnchor ;
}
function bind(obj, fn) {
return function() {
fn.call(obj) ;
};
}
World.prototype = {
init : function() {
var fixDef = new Box2D.Dynamics.b2FixtureDef();
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = 0.2;
var bodyDef = new Box2D.Dynamics.b2BodyDef();
bodyDef.type = Box2D.Dynamics.b2Body.b2_staticBody;
// create ground
bodyDef.position.x = worldWidthInMeter / 2;
bodyDef.position.y = worldHeightInMeter + groundHalfWidth;
fixDef.shape = new Box2D.Collision.Shapes.b2PolygonShape();
fixDef.shape.SetAsBox(worldWidthInMeter / 2, groundHalfWidth);
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
// Left wall
bodyDef.position.x = -groundHalfWidth;
bodyDef.position.y = worldHeightInMeter / 2;
fixDef.shape = new Box2D.Collision.Shapes.b2PolygonShape();
fixDef.shape.SetAsBox(groundHalfWidth, worldHeightInMeter / 2);
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
// Right wall
bodyDef.position.x = worldWidthInMeter + groundHalfWidth; // center
bodyDef.position.y = worldHeightInMeter / 2; // bottom
fixDef.shape = new Box2D.Collision.Shapes.b2PolygonShape();
fixDef.shape.SetAsBox(groundHalfWidth, worldHeightInMeter / 2);
this.world.CreateBody(bodyDef).CreateFixture(fixDef);
// roof-anchor for chain
bodyDef.position.x = worldWidthInMeter / 2;
bodyDef.position.y = 0;
fixDef.shape = new Box2D.Collision.Shapes.b2PolygonShape();
fixDef.shape.SetAsBox(linkRadius, groundHalfWidth);
this.chainAnchor = this.world.CreateBody(bodyDef);
this.chainAnchor.CreateFixture(fixDef);
this.initBodies();
// setup debug draw
var debugDraw = new Box2D.Dynamics.b2DebugDraw();
debugDraw.SetSprite(this.ctx);
debugDraw.SetDrawScale(pixelsPerMeter);
debugDraw.SetFillAlpha(0.6);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(Box2D.Dynamics.b2DebugDraw.e_shapeBit
| Box2D.Dynamics.b2DebugDraw.e_jointBit);
this.world.SetDebugDraw(debugDraw);
var callback = bind(this, this.update) ;
window.setInterval(callback, 1000 / 30);
},
reset : function() {
// Destroy the existing joints
for ( var n = 0; n < this.joints.length; n++) {
this.world.DestroyJoint(this.joints[n]);
}
// Destroy the existing bodies
for ( var n = 0; n < this.bodies.length; n++) {
this.world.DestroyBody(this.bodies[n]);
}
this.bodies = new Array();
this.initBodies();
},
initBodies : function() {
var fixDef = new Box2D.Dynamics.b2FixtureDef();
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = 0.2;
fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(linkRadius);
var bodyDef = new Box2D.Dynamics.b2BodyDef();
bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
bodyDef.linearDamping = 0.01;
// Create chain
var b2JointDef = new Box2D.Dynamics.Joints.b2RevoluteJointDef();
b2JointDef.maxMotorTorque = 10.0;
b2JointDef.motorSpeed = 0.0;
b2JointDef.enableMotor = true;
var previousLink;
for ( var n = 0; n < numberOfLinks; n++) {
bodyDef.position.x = worldWidthInMeter / 2 ;
bodyDef.position.y = groundHalfWidth + linkRadius * 2 * n;
var link = this.world.CreateBody(bodyDef);
link.CreateFixture(fixDef);
this.bodies.push(link);
if (previousLink) {
b2JointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(0,linkRadius);
b2JointDef.localAnchorB = new Box2D.Common.Math.b2Vec2(0, -linkRadius);
b2JointDef.bodyA = previousLink;
b2JointDef.bodyB = link;
var joint = this.world.CreateJoint(b2JointDef);
this.joints.push(joint);
} else {
b2JointDef.localAnchorA = new Box2D.Common.Math.b2Vec2(0, groundHalfWidth);
b2JointDef.localAnchorB = new Box2D.Common.Math.b2Vec2(0,-linkRadius);
b2JointDef.bodyA = this.chainAnchor;
b2JointDef.bodyB = link;
var joint = this.world.CreateJoint(b2JointDef);
this.joints.push(joint);
}
previousLink = link;
}
},
update : function() {
this.world.Step(1 / 30 // frame-rate
, 10 // velocity iterations
, 10 // position iterations
);
this.world.DrawDebugData();
this.world.ClearForces();
},
fireCannonball : function() {
var fixDef = new Box2D.Dynamics.b2FixtureDef();
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = 0.2;
fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(linkRadius);
var bodyDef = new Box2D.Dynamics.b2BodyDef();
bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
bodyDef.linearDamping = 0.01;
bodyDef.position.x = linkRadius;
bodyDef.position.y = worldHeightInMeter-linkRadius;
var cannonball = this.world.CreateBody(bodyDef);
cannonball.CreateFixture(fixDef);
this.bodies.push(cannonball) ;
cannonball.ApplyImpulse(
new Box2D.Common.Math.b2Vec2(1,-1.5),
new Box2D.Common.Math.b2Vec2(bodyDef.position.x,bodyDef.position.y)
);
}
};
| JavaScript |
/*
* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
var a2j = {};
(function (a2j, window) {
if(!window.flash) window.flash = {utils: {Dictionary: Object} };
else if(!window.flash.utils) window.flash.utils = {Dictionary: Object};
else if(!window.flash.utils.Dictionary) window.flash.utils.Dictionary = Object;
window.Vector = window.Array;
Function.prototype.inherit = function (base) {
var tmpCtr = this;
var empty = Function.prototype.inherit.empty;
empty.prototype = base.prototype;
this.prototype = new empty();
this.prototype.constructor = tmpCtr;
};
Function.prototype.inherit.empty = function () {};
window.trace = function () {
if (window.console && (window.console.log instanceof Function)) window.console.log.apply(window.console, arguments);
};
window.assert = function () {
if (window.console && (window.console.assert instanceof Function)) window.console.assert.apply(window.console, arguments);
};
a2j.warn = function warn() {
if (window.console) console.warn.apply(console, arguments);
};
a2j.generateCallback = function generateCallback(context, cb) {
return function () {
cb.apply(context, arguments);
};
};
a2j.NVector = function NVector(length) {
if (length === undefined) length = 0;
var tmp = new Array(length || 0);
for (var i = 0; i < length; ++i)
tmp[i] = 0;
return tmp;
};
a2j.is = function is(o1, o2) {
if (o1 === null) return false;
if ((o2 instanceof Function) && (o1 instanceof o2)) return true;
if ((o1.constructor.__implements != undefined) && (o1.constructor.__implements[o2])) return true;
return false;
};
a2j.parseUInt = function(v) {
return Math.abs(parseInt(v));
}
})(a2j, window, undefined);
var Vector_a2j_Number = a2j.NVector;
//package structure
if (!window.Box2D) Box2D = {};
if (!window.Box2D.Collision) Box2D.Collision = {};
if (!window.Box2D.Collision.Shapes) Box2D.Collision.Shapes = {};
if (!window.Box2D.Common) Box2D.Common = {};
if (!window.Box2D.Common.Math) Box2D.Common.Math = {};
if (!window.Box2D.Dynamics) Box2D.Dynamics = {};
if (!window.Box2D.Dynamics.Contacts) Box2D.Dynamics.Contacts = {};
if (!window.Box2D.Dynamics.Controllers) Box2D.Dynamics.Controllers = {};
if (!window.Box2D.Dynamics.Joints) Box2D.Dynamics.Joints = {};
//pre-definitions
(function () {
Box2D.Collision.IBroadPhase = 'Box2D.Collision.IBroadPhase';
function b2AABB() {
b2AABB.b2AABB.apply(this, arguments);
};
Box2D.Collision.b2AABB = b2AABB;
function b2Bound() {
b2Bound.b2Bound.apply(this, arguments);
};
Box2D.Collision.b2Bound = b2Bound;
function b2BoundValues() {
b2BoundValues.b2BoundValues.apply(this, arguments);
if (this.constructor === b2BoundValues) this.b2BoundValues.apply(this, arguments);
};
Box2D.Collision.b2BoundValues = b2BoundValues;
function b2BroadPhase() {
b2BroadPhase.b2BroadPhase.apply(this, arguments);
if (this.constructor === b2BroadPhase) this.b2BroadPhase.apply(this, arguments);
};
Box2D.Collision.b2BroadPhase = b2BroadPhase;
function b2Collision() {
b2Collision.b2Collision.apply(this, arguments);
};
Box2D.Collision.b2Collision = b2Collision;
function b2ContactID() {
b2ContactID.b2ContactID.apply(this, arguments);
if (this.constructor === b2ContactID) this.b2ContactID.apply(this, arguments);
};
Box2D.Collision.b2ContactID = b2ContactID;
function b2ContactPoint() {
b2ContactPoint.b2ContactPoint.apply(this, arguments);
};
Box2D.Collision.b2ContactPoint = b2ContactPoint;
function b2Distance() {
b2Distance.b2Distance.apply(this, arguments);
};
Box2D.Collision.b2Distance = b2Distance;
function b2DistanceInput() {
b2DistanceInput.b2DistanceInput.apply(this, arguments);
};
Box2D.Collision.b2DistanceInput = b2DistanceInput;
function b2DistanceOutput() {
b2DistanceOutput.b2DistanceOutput.apply(this, arguments);
};
Box2D.Collision.b2DistanceOutput = b2DistanceOutput;
function b2DistanceProxy() {
b2DistanceProxy.b2DistanceProxy.apply(this, arguments);
};
Box2D.Collision.b2DistanceProxy = b2DistanceProxy;
function b2DynamicTree() {
b2DynamicTree.b2DynamicTree.apply(this, arguments);
if (this.constructor === b2DynamicTree) this.b2DynamicTree.apply(this, arguments);
};
Box2D.Collision.b2DynamicTree = b2DynamicTree;
function b2DynamicTreeBroadPhase() {
b2DynamicTreeBroadPhase.b2DynamicTreeBroadPhase.apply(this, arguments);
};
Box2D.Collision.b2DynamicTreeBroadPhase = b2DynamicTreeBroadPhase;
function b2DynamicTreeNode() {
b2DynamicTreeNode.b2DynamicTreeNode.apply(this, arguments);
};
Box2D.Collision.b2DynamicTreeNode = b2DynamicTreeNode;
function b2DynamicTreePair() {
b2DynamicTreePair.b2DynamicTreePair.apply(this, arguments);
};
Box2D.Collision.b2DynamicTreePair = b2DynamicTreePair;
function b2Manifold() {
b2Manifold.b2Manifold.apply(this, arguments);
if (this.constructor === b2Manifold) this.b2Manifold.apply(this, arguments);
};
Box2D.Collision.b2Manifold = b2Manifold;
function b2ManifoldPoint() {
b2ManifoldPoint.b2ManifoldPoint.apply(this, arguments);
if (this.constructor === b2ManifoldPoint) this.b2ManifoldPoint.apply(this, arguments);
};
Box2D.Collision.b2ManifoldPoint = b2ManifoldPoint;
function b2OBB() {
b2OBB.b2OBB.apply(this, arguments);
};
Box2D.Collision.b2OBB = b2OBB;
function b2Pair() {
b2Pair.b2Pair.apply(this, arguments);
};
Box2D.Collision.b2Pair = b2Pair;
function b2PairManager() {
b2PairManager.b2PairManager.apply(this, arguments);
if (this.constructor === b2PairManager) this.b2PairManager.apply(this, arguments);
};
Box2D.Collision.b2PairManager = b2PairManager;
function b2Point() {
b2Point.b2Point.apply(this, arguments);
};
Box2D.Collision.b2Point = b2Point;
function b2Proxy() {
b2Proxy.b2Proxy.apply(this, arguments);
};
Box2D.Collision.b2Proxy = b2Proxy;
function b2RayCastInput() {
b2RayCastInput.b2RayCastInput.apply(this, arguments);
if (this.constructor === b2RayCastInput) this.b2RayCastInput.apply(this, arguments);
};
Box2D.Collision.b2RayCastInput = b2RayCastInput;
function b2RayCastOutput() {
b2RayCastOutput.b2RayCastOutput.apply(this, arguments);
};
Box2D.Collision.b2RayCastOutput = b2RayCastOutput;
function b2Segment() {
b2Segment.b2Segment.apply(this, arguments);
};
Box2D.Collision.b2Segment = b2Segment;
function b2SeparationFunction() {
b2SeparationFunction.b2SeparationFunction.apply(this, arguments);
};
Box2D.Collision.b2SeparationFunction = b2SeparationFunction;
function b2Simplex() {
b2Simplex.b2Simplex.apply(this, arguments);
if (this.constructor === b2Simplex) this.b2Simplex.apply(this, arguments);
};
Box2D.Collision.b2Simplex = b2Simplex;
function b2SimplexCache() {
b2SimplexCache.b2SimplexCache.apply(this, arguments);
};
Box2D.Collision.b2SimplexCache = b2SimplexCache;
function b2SimplexVertex() {
b2SimplexVertex.b2SimplexVertex.apply(this, arguments);
};
Box2D.Collision.b2SimplexVertex = b2SimplexVertex;
function b2TimeOfImpact() {
b2TimeOfImpact.b2TimeOfImpact.apply(this, arguments);
};
Box2D.Collision.b2TimeOfImpact = b2TimeOfImpact;
function b2TOIInput() {
b2TOIInput.b2TOIInput.apply(this, arguments);
};
Box2D.Collision.b2TOIInput = b2TOIInput;
function b2WorldManifold() {
b2WorldManifold.b2WorldManifold.apply(this, arguments);
if (this.constructor === b2WorldManifold) this.b2WorldManifold.apply(this, arguments);
};
Box2D.Collision.b2WorldManifold = b2WorldManifold;
function ClipVertex() {
ClipVertex.ClipVertex.apply(this, arguments);
};
Box2D.Collision.ClipVertex = ClipVertex;
function Features() {
Features.Features.apply(this, arguments);
};
Box2D.Collision.Features = Features;
function b2CircleShape() {
b2CircleShape.b2CircleShape.apply(this, arguments);
if (this.constructor === b2CircleShape) this.b2CircleShape.apply(this, arguments);
};
Box2D.Collision.Shapes.b2CircleShape = b2CircleShape;
function b2EdgeChainDef() {
b2EdgeChainDef.b2EdgeChainDef.apply(this, arguments);
if (this.constructor === b2EdgeChainDef) this.b2EdgeChainDef.apply(this, arguments);
};
Box2D.Collision.Shapes.b2EdgeChainDef = b2EdgeChainDef;
function b2EdgeShape() {
b2EdgeShape.b2EdgeShape.apply(this, arguments);
if (this.constructor === b2EdgeShape) this.b2EdgeShape.apply(this, arguments);
};
Box2D.Collision.Shapes.b2EdgeShape = b2EdgeShape;
function b2MassData() {
b2MassData.b2MassData.apply(this, arguments);
};
Box2D.Collision.Shapes.b2MassData = b2MassData;
function b2PolygonShape() {
b2PolygonShape.b2PolygonShape.apply(this, arguments);
if (this.constructor === b2PolygonShape) this.b2PolygonShape.apply(this, arguments);
};
Box2D.Collision.Shapes.b2PolygonShape = b2PolygonShape;
function b2Shape() {
b2Shape.b2Shape.apply(this, arguments);
if (this.constructor === b2Shape) this.b2Shape.apply(this, arguments);
};
Box2D.Collision.Shapes.b2Shape = b2Shape;
Box2D.Common.b2internal = 'Box2D.Common.b2internal';
function b2Color() {
b2Color.b2Color.apply(this, arguments);
if (this.constructor === b2Color) this.b2Color.apply(this, arguments);
};
Box2D.Common.b2Color = b2Color;
function b2Settings() {
b2Settings.b2Settings.apply(this, arguments);
};
Box2D.Common.b2Settings = b2Settings;
function b2Mat22() {
b2Mat22.b2Mat22.apply(this, arguments);
if (this.constructor === b2Mat22) this.b2Mat22.apply(this, arguments);
};
Box2D.Common.Math.b2Mat22 = b2Mat22;
function b2Mat33() {
b2Mat33.b2Mat33.apply(this, arguments);
if (this.constructor === b2Mat33) this.b2Mat33.apply(this, arguments);
};
Box2D.Common.Math.b2Mat33 = b2Mat33;
function b2Math() {
b2Math.b2Math.apply(this, arguments);
};
Box2D.Common.Math.b2Math = b2Math;
function b2Sweep() {
b2Sweep.b2Sweep.apply(this, arguments);
};
Box2D.Common.Math.b2Sweep = b2Sweep;
function b2Transform() {
b2Transform.b2Transform.apply(this, arguments);
if (this.constructor === b2Transform) this.b2Transform.apply(this, arguments);
};
Box2D.Common.Math.b2Transform = b2Transform;
function b2Vec2() {
b2Vec2.b2Vec2.apply(this, arguments);
if (this.constructor === b2Vec2) this.b2Vec2.apply(this, arguments);
};
Box2D.Common.Math.b2Vec2 = b2Vec2;
function b2Vec3() {
b2Vec3.b2Vec3.apply(this, arguments);
if (this.constructor === b2Vec3) this.b2Vec3.apply(this, arguments);
};
Box2D.Common.Math.b2Vec3 = b2Vec3;
function b2Body() {
b2Body.b2Body.apply(this, arguments);
if (this.constructor === b2Body) this.b2Body.apply(this, arguments);
};
Box2D.Dynamics.b2Body = b2Body;
function b2BodyDef() {
b2BodyDef.b2BodyDef.apply(this, arguments);
if (this.constructor === b2BodyDef) this.b2BodyDef.apply(this, arguments);
};
Box2D.Dynamics.b2BodyDef = b2BodyDef;
function b2ContactFilter() {
b2ContactFilter.b2ContactFilter.apply(this, arguments);
};
Box2D.Dynamics.b2ContactFilter = b2ContactFilter;
function b2ContactImpulse() {
b2ContactImpulse.b2ContactImpulse.apply(this, arguments);
};
Box2D.Dynamics.b2ContactImpulse = b2ContactImpulse;
function b2ContactListener() {
b2ContactListener.b2ContactListener.apply(this, arguments);
};
Box2D.Dynamics.b2ContactListener = b2ContactListener;
function b2ContactManager() {
b2ContactManager.b2ContactManager.apply(this, arguments);
if (this.constructor === b2ContactManager) this.b2ContactManager.apply(this, arguments);
};
Box2D.Dynamics.b2ContactManager = b2ContactManager;
function b2DebugDraw() {
b2DebugDraw.b2DebugDraw.apply(this, arguments);
if (this.constructor === b2DebugDraw) this.b2DebugDraw.apply(this, arguments);
};
Box2D.Dynamics.b2DebugDraw = b2DebugDraw;
function b2DestructionListener() {
b2DestructionListener.b2DestructionListener.apply(this, arguments);
};
Box2D.Dynamics.b2DestructionListener = b2DestructionListener;
function b2FilterData() {
b2FilterData.b2FilterData.apply(this, arguments);
};
Box2D.Dynamics.b2FilterData = b2FilterData;
function b2Fixture() {
b2Fixture.b2Fixture.apply(this, arguments);
if (this.constructor === b2Fixture) this.b2Fixture.apply(this, arguments);
};
Box2D.Dynamics.b2Fixture = b2Fixture;
function b2FixtureDef() {
b2FixtureDef.b2FixtureDef.apply(this, arguments);
if (this.constructor === b2FixtureDef) this.b2FixtureDef.apply(this, arguments);
};
Box2D.Dynamics.b2FixtureDef = b2FixtureDef;
function b2Island() {
b2Island.b2Island.apply(this, arguments);
if (this.constructor === b2Island) this.b2Island.apply(this, arguments);
};
Box2D.Dynamics.b2Island = b2Island;
function b2TimeStep() {
b2TimeStep.b2TimeStep.apply(this, arguments);
};
Box2D.Dynamics.b2TimeStep = b2TimeStep;
function b2World() {
b2World.b2World.apply(this, arguments);
if (this.constructor === b2World) this.b2World.apply(this, arguments);
};
Box2D.Dynamics.b2World = b2World;
function b2CircleContact() {
b2CircleContact.b2CircleContact.apply(this, arguments);
};
Box2D.Dynamics.Contacts.b2CircleContact = b2CircleContact;
function b2Contact() {
b2Contact.b2Contact.apply(this, arguments);
if (this.constructor === b2Contact) this.b2Contact.apply(this, arguments);
};
Box2D.Dynamics.Contacts.b2Contact = b2Contact;
function b2ContactConstraint() {
b2ContactConstraint.b2ContactConstraint.apply(this, arguments);
if (this.constructor === b2ContactConstraint) this.b2ContactConstraint.apply(this, arguments);
};
Box2D.Dynamics.Contacts.b2ContactConstraint = b2ContactConstraint;
function b2ContactConstraintPoint() {
b2ContactConstraintPoint.b2ContactConstraintPoint.apply(this, arguments);
};
Box2D.Dynamics.Contacts.b2ContactConstraintPoint = b2ContactConstraintPoint;
function b2ContactEdge() {
b2ContactEdge.b2ContactEdge.apply(this, arguments);
};
Box2D.Dynamics.Contacts.b2ContactEdge = b2ContactEdge;
function b2ContactFactory() {
b2ContactFactory.b2ContactFactory.apply(this, arguments);
if (this.constructor === b2ContactFactory) this.b2ContactFactory.apply(this, arguments);
};
Box2D.Dynamics.Contacts.b2ContactFactory = b2ContactFactory;
function b2ContactRegister() {
b2ContactRegister.b2ContactRegister.apply(this, arguments);
};
Box2D.Dynamics.Contacts.b2ContactRegister = b2ContactRegister;
function b2ContactResult() {
b2ContactResult.b2ContactResult.apply(this, arguments);
};
Box2D.Dynamics.Contacts.b2ContactResult = b2ContactResult;
function b2ContactSolver() {
b2ContactSolver.b2ContactSolver.apply(this, arguments);
if (this.constructor === b2ContactSolver) this.b2ContactSolver.apply(this, arguments);
};
Box2D.Dynamics.Contacts.b2ContactSolver = b2ContactSolver;
function b2EdgeAndCircleContact() {
b2EdgeAndCircleContact.b2EdgeAndCircleContact.apply(this, arguments);
};
Box2D.Dynamics.Contacts.b2EdgeAndCircleContact = b2EdgeAndCircleContact;
function b2NullContact() {
b2NullContact.b2NullContact.apply(this, arguments);
if (this.constructor === b2NullContact) this.b2NullContact.apply(this, arguments);
};
Box2D.Dynamics.Contacts.b2NullContact = b2NullContact;
function b2PolyAndCircleContact() {
b2PolyAndCircleContact.b2PolyAndCircleContact.apply(this, arguments);
};
Box2D.Dynamics.Contacts.b2PolyAndCircleContact = b2PolyAndCircleContact;
function b2PolyAndEdgeContact() {
b2PolyAndEdgeContact.b2PolyAndEdgeContact.apply(this, arguments);
};
Box2D.Dynamics.Contacts.b2PolyAndEdgeContact = b2PolyAndEdgeContact;
function b2PolygonContact() {
b2PolygonContact.b2PolygonContact.apply(this, arguments);
};
Box2D.Dynamics.Contacts.b2PolygonContact = b2PolygonContact;
function b2PositionSolverManifold() {
b2PositionSolverManifold.b2PositionSolverManifold.apply(this, arguments);
if (this.constructor === b2PositionSolverManifold) this.b2PositionSolverManifold.apply(this, arguments);
};
Box2D.Dynamics.Contacts.b2PositionSolverManifold = b2PositionSolverManifold;
function b2BuoyancyController() {
b2BuoyancyController.b2BuoyancyController.apply(this, arguments);
};
Box2D.Dynamics.Controllers.b2BuoyancyController = b2BuoyancyController;
function b2ConstantAccelController() {
b2ConstantAccelController.b2ConstantAccelController.apply(this, arguments);
};
Box2D.Dynamics.Controllers.b2ConstantAccelController = b2ConstantAccelController;
function b2ConstantForceController() {
b2ConstantForceController.b2ConstantForceController.apply(this, arguments);
};
Box2D.Dynamics.Controllers.b2ConstantForceController = b2ConstantForceController;
function b2Controller() {
b2Controller.b2Controller.apply(this, arguments);
};
Box2D.Dynamics.Controllers.b2Controller = b2Controller;
function b2ControllerEdge() {
b2ControllerEdge.b2ControllerEdge.apply(this, arguments);
};
Box2D.Dynamics.Controllers.b2ControllerEdge = b2ControllerEdge;
function b2GravityController() {
b2GravityController.b2GravityController.apply(this, arguments);
};
Box2D.Dynamics.Controllers.b2GravityController = b2GravityController;
function b2TensorDampingController() {
b2TensorDampingController.b2TensorDampingController.apply(this, arguments);
};
Box2D.Dynamics.Controllers.b2TensorDampingController = b2TensorDampingController;
function b2DistanceJoint() {
b2DistanceJoint.b2DistanceJoint.apply(this, arguments);
if (this.constructor === b2DistanceJoint) this.b2DistanceJoint.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2DistanceJoint = b2DistanceJoint;
function b2DistanceJointDef() {
b2DistanceJointDef.b2DistanceJointDef.apply(this, arguments);
if (this.constructor === b2DistanceJointDef) this.b2DistanceJointDef.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2DistanceJointDef = b2DistanceJointDef;
function b2FrictionJoint() {
b2FrictionJoint.b2FrictionJoint.apply(this, arguments);
if (this.constructor === b2FrictionJoint) this.b2FrictionJoint.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2FrictionJoint = b2FrictionJoint;
function b2FrictionJointDef() {
b2FrictionJointDef.b2FrictionJointDef.apply(this, arguments);
if (this.constructor === b2FrictionJointDef) this.b2FrictionJointDef.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2FrictionJointDef = b2FrictionJointDef;
function b2GearJoint() {
b2GearJoint.b2GearJoint.apply(this, arguments);
if (this.constructor === b2GearJoint) this.b2GearJoint.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2GearJoint = b2GearJoint;
function b2GearJointDef() {
b2GearJointDef.b2GearJointDef.apply(this, arguments);
if (this.constructor === b2GearJointDef) this.b2GearJointDef.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2GearJointDef = b2GearJointDef;
function b2Jacobian() {
b2Jacobian.b2Jacobian.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2Jacobian = b2Jacobian;
function b2Joint() {
b2Joint.b2Joint.apply(this, arguments);
if (this.constructor === b2Joint) this.b2Joint.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2Joint = b2Joint;
function b2JointDef() {
b2JointDef.b2JointDef.apply(this, arguments);
if (this.constructor === b2JointDef) this.b2JointDef.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2JointDef = b2JointDef;
function b2JointEdge() {
b2JointEdge.b2JointEdge.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2JointEdge = b2JointEdge;
function b2LineJoint() {
b2LineJoint.b2LineJoint.apply(this, arguments);
if (this.constructor === b2LineJoint) this.b2LineJoint.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2LineJoint = b2LineJoint;
function b2LineJointDef() {
b2LineJointDef.b2LineJointDef.apply(this, arguments);
if (this.constructor === b2LineJointDef) this.b2LineJointDef.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2LineJointDef = b2LineJointDef;
function b2MouseJoint() {
b2MouseJoint.b2MouseJoint.apply(this, arguments);
if (this.constructor === b2MouseJoint) this.b2MouseJoint.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2MouseJoint = b2MouseJoint;
function b2MouseJointDef() {
b2MouseJointDef.b2MouseJointDef.apply(this, arguments);
if (this.constructor === b2MouseJointDef) this.b2MouseJointDef.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2MouseJointDef = b2MouseJointDef;
function b2PrismaticJoint() {
b2PrismaticJoint.b2PrismaticJoint.apply(this, arguments);
if (this.constructor === b2PrismaticJoint) this.b2PrismaticJoint.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2PrismaticJoint = b2PrismaticJoint;
function b2PrismaticJointDef() {
b2PrismaticJointDef.b2PrismaticJointDef.apply(this, arguments);
if (this.constructor === b2PrismaticJointDef) this.b2PrismaticJointDef.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2PrismaticJointDef = b2PrismaticJointDef;
function b2PulleyJoint() {
b2PulleyJoint.b2PulleyJoint.apply(this, arguments);
if (this.constructor === b2PulleyJoint) this.b2PulleyJoint.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2PulleyJoint = b2PulleyJoint;
function b2PulleyJointDef() {
b2PulleyJointDef.b2PulleyJointDef.apply(this, arguments);
if (this.constructor === b2PulleyJointDef) this.b2PulleyJointDef.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2PulleyJointDef = b2PulleyJointDef;
function b2RevoluteJoint() {
b2RevoluteJoint.b2RevoluteJoint.apply(this, arguments);
if (this.constructor === b2RevoluteJoint) this.b2RevoluteJoint.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2RevoluteJoint = b2RevoluteJoint;
function b2RevoluteJointDef() {
b2RevoluteJointDef.b2RevoluteJointDef.apply(this, arguments);
if (this.constructor === b2RevoluteJointDef) this.b2RevoluteJointDef.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2RevoluteJointDef = b2RevoluteJointDef;
function b2WeldJoint() {
b2WeldJoint.b2WeldJoint.apply(this, arguments);
if (this.constructor === b2WeldJoint) this.b2WeldJoint.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2WeldJoint = b2WeldJoint;
function b2WeldJointDef() {
b2WeldJointDef.b2WeldJointDef.apply(this, arguments);
if (this.constructor === b2WeldJointDef) this.b2WeldJointDef.apply(this, arguments);
};
Box2D.Dynamics.Joints.b2WeldJointDef = b2WeldJointDef;
})(); //definitions
_A2J_postDefs = []; /* source: disabled*/
(function () {
var Dictionary = flash.utils.Dictionary;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2EdgeChainDef = Box2D.Collision.Shapes.b2EdgeChainDef;
var b2EdgeShape = Box2D.Collision.Shapes.b2EdgeShape;
var b2MassData = Box2D.Collision.Shapes.b2MassData;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2Shape = Box2D.Collision.Shapes.b2Shape;
var b2Color = Box2D.Common.b2Color;
var b2internal = Box2D.Common.b2internal;
var b2Settings = Box2D.Common.b2Settings;
var b2internal = Box2D.Common.b2internal;
var b2Mat22 = Box2D.Common.Math.b2Mat22;
var b2Mat33 = Box2D.Common.Math.b2Mat33;
var b2Math = Box2D.Common.Math.b2Math;
var b2Sweep = Box2D.Common.Math.b2Sweep;
var b2Transform = Box2D.Common.Math.b2Transform;
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2Vec3 = Box2D.Common.Math.b2Vec3;
var b2AABB = Box2D.Collision.b2AABB;
var b2Bound = Box2D.Collision.b2Bound;
var b2BoundValues = Box2D.Collision.b2BoundValues;
var b2BroadPhase = Box2D.Collision.b2BroadPhase;
var b2Collision = Box2D.Collision.b2Collision;
var b2ContactID = Box2D.Collision.b2ContactID;
var b2ContactPoint = Box2D.Collision.b2ContactPoint;
var b2Distance = Box2D.Collision.b2Distance;
var b2DistanceInput = Box2D.Collision.b2DistanceInput;
var b2DistanceOutput = Box2D.Collision.b2DistanceOutput;
var b2DistanceProxy = Box2D.Collision.b2DistanceProxy;
var b2DynamicTree = Box2D.Collision.b2DynamicTree;
var b2DynamicTreeBroadPhase = Box2D.Collision.b2DynamicTreeBroadPhase;
var b2DynamicTreeNode = Box2D.Collision.b2DynamicTreeNode;
var b2DynamicTreePair = Box2D.Collision.b2DynamicTreePair;
var b2Manifold = Box2D.Collision.b2Manifold;
var b2ManifoldPoint = Box2D.Collision.b2ManifoldPoint;
var b2OBB = Box2D.Collision.b2OBB;
var b2Pair = Box2D.Collision.b2Pair;
var b2PairManager = Box2D.Collision.b2PairManager;
var b2Point = Box2D.Collision.b2Point;
var b2Proxy = Box2D.Collision.b2Proxy;
var b2RayCastInput = Box2D.Collision.b2RayCastInput;
var b2RayCastOutput = Box2D.Collision.b2RayCastOutput;
var b2Segment = Box2D.Collision.b2Segment;
var b2SeparationFunction = Box2D.Collision.b2SeparationFunction;
var b2Simplex = Box2D.Collision.b2Simplex;
var b2SimplexCache = Box2D.Collision.b2SimplexCache;
var b2SimplexVertex = Box2D.Collision.b2SimplexVertex;
var b2TimeOfImpact = Box2D.Collision.b2TimeOfImpact;
var b2TOIInput = Box2D.Collision.b2TOIInput;
var b2WorldManifold = Box2D.Collision.b2WorldManifold;
var ClipVertex = Box2D.Collision.ClipVertex;
var Features = Box2D.Collision.Features;
var IBroadPhase = Box2D.Collision.IBroadPhase;
var b2internal = Box2D.Common.b2internal;
var b2internal = Box2D.Common.b2internal;
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2AABB = Box2D.Collision.b2AABB;
var b2Bound = Box2D.Collision.b2Bound;
var b2BoundValues = Box2D.Collision.b2BoundValues;
var b2BroadPhase = Box2D.Collision.b2BroadPhase;
var b2Collision = Box2D.Collision.b2Collision;
var b2ContactID = Box2D.Collision.b2ContactID;
var b2ContactPoint = Box2D.Collision.b2ContactPoint;
var b2Distance = Box2D.Collision.b2Distance;
var b2DistanceInput = Box2D.Collision.b2DistanceInput;
var b2DistanceOutput = Box2D.Collision.b2DistanceOutput;
var b2DistanceProxy = Box2D.Collision.b2DistanceProxy;
var b2DynamicTree = Box2D.Collision.b2DynamicTree;
var b2DynamicTreeBroadPhase = Box2D.Collision.b2DynamicTreeBroadPhase;
var b2DynamicTreeNode = Box2D.Collision.b2DynamicTreeNode;
var b2DynamicTreePair = Box2D.Collision.b2DynamicTreePair;
var b2Manifold = Box2D.Collision.b2Manifold;
var b2ManifoldPoint = Box2D.Collision.b2ManifoldPoint;
var b2OBB = Box2D.Collision.b2OBB;
var b2Pair = Box2D.Collision.b2Pair;
var b2PairManager = Box2D.Collision.b2PairManager;
var b2Point = Box2D.Collision.b2Point;
var b2Proxy = Box2D.Collision.b2Proxy;
var b2RayCastInput = Box2D.Collision.b2RayCastInput;
var b2RayCastOutput = Box2D.Collision.b2RayCastOutput;
var b2Segment = Box2D.Collision.b2Segment;
var b2SeparationFunction = Box2D.Collision.b2SeparationFunction;
var b2Simplex = Box2D.Collision.b2Simplex;
var b2SimplexCache = Box2D.Collision.b2SimplexCache;
var b2SimplexVertex = Box2D.Collision.b2SimplexVertex;
var b2TimeOfImpact = Box2D.Collision.b2TimeOfImpact;
var b2TOIInput = Box2D.Collision.b2TOIInput;
var b2WorldManifold = Box2D.Collision.b2WorldManifold;
var ClipVertex = Box2D.Collision.ClipVertex;
var Features = Box2D.Collision.Features;
var IBroadPhase = Box2D.Collision.IBroadPhase;
var IBroadPhase = Box2D.Collision.IBroadPhase;
b2AABB.b2AABB = function () {
this.lowerBound = new b2Vec2();
this.upperBound = new b2Vec2();
};
b2AABB.prototype.IsValid = function () {
var dX = this.upperBound.x - this.lowerBound.x;
var dY = this.upperBound.y - this.lowerBound.y;
var valid = dX >= 0.0 && dY >= 0.0;
valid = valid && this.lowerBound.IsValid() && this.upperBound.IsValid();
return valid;
}
b2AABB.prototype.GetCenter = function () {
return new b2Vec2((this.lowerBound.x + this.upperBound.x) / 2, (this.lowerBound.y + this.upperBound.y) / 2);
}
b2AABB.prototype.GetExtents = function () {
return new b2Vec2((this.upperBound.x - this.lowerBound.x) / 2, (this.upperBound.y - this.lowerBound.y) / 2);
}
b2AABB.prototype.Contains = function (aabb) {
var result = true;
result = result && this.lowerBound.x <= aabb.lowerBound.x;
result = result && this.lowerBound.y <= aabb.lowerBound.y;
result = result && aabb.upperBound.x <= this.upperBound.x;
result = result && aabb.upperBound.y <= this.upperBound.y;
return result;
}
b2AABB.prototype.RayCast = function (output, input) {
var tmin = (-Number.MAX_VALUE);
var tmax = Number.MAX_VALUE;
var pX = input.p1.x;
var pY = input.p1.y;
var dX = input.p2.x - input.p1.x;
var dY = input.p2.y - input.p1.y;
var absDX = Math.abs(dX);
var absDY = Math.abs(dY);
var normal = output.normal;
var inv_d = 0;
var t1 = 0;
var t2 = 0;
var t3 = 0;
var s = 0; {
if (absDX < Number.MIN_VALUE) {
if (pX < this.lowerBound.x || this.upperBound.x < pX) return false;
}
else {
inv_d = 1.0 / dX;
t1 = (this.lowerBound.x - pX) * inv_d;
t2 = (this.upperBound.x - pX) * inv_d;
s = (-1.0);
if (t1 > t2) {
t3 = t1;
t1 = t2;
t2 = t3;
s = 1.0;
}
if (t1 > tmin) {
normal.x = s;
normal.y = 0;
tmin = t1;
}
tmax = Math.min(tmax, t2);
if (tmin > tmax) return false;
}
} {
if (absDY < Number.MIN_VALUE) {
if (pY < this.lowerBound.y || this.upperBound.y < pY) return false;
}
else {
inv_d = 1.0 / dY;
t1 = (this.lowerBound.y - pY) * inv_d;
t2 = (this.upperBound.y - pY) * inv_d;
s = (-1.0);
if (t1 > t2) {
t3 = t1;
t1 = t2;
t2 = t3;
s = 1.0;
}
if (t1 > tmin) {
normal.y = s;
normal.x = 0;
tmin = t1;
}
tmax = Math.min(tmax, t2);
if (tmin > tmax) return false;
}
}
output.fraction = tmin;
return true;
}
b2AABB.prototype.TestOverlap = function (other) {
var d1X = other.lowerBound.x - this.upperBound.x;
var d1Y = other.lowerBound.y - this.upperBound.y;
var d2X = this.lowerBound.x - other.upperBound.x;
var d2Y = this.lowerBound.y - other.upperBound.y;
if (d1X > 0.0 || d1Y > 0.0) return false;
if (d2X > 0.0 || d2Y > 0.0) return false;
return true;
}
b2AABB.prototype.Combine = function (aabb1, aabb2) {
var aabb = new b2AABB();
if (this.constructor === Box2D.Collision.b2AABB) this._a2j__Combine(aabb1, aabb2);
else aabb._a2j__Combine(aabb1, aabb2);
return aabb;
}
b2AABB.Combine = b2AABB.prototype.Combine;
b2AABB.prototype._a2j__Combine = function (aabb1, aabb2) {
this.lowerBound.x = Math.min(aabb1.lowerBound.x, aabb2.lowerBound.x);
this.lowerBound.y = Math.min(aabb1.lowerBound.y, aabb2.lowerBound.y);
this.upperBound.x = Math.max(aabb1.upperBound.x, aabb2.upperBound.x);
this.upperBound.y = Math.max(aabb1.upperBound.y, aabb2.upperBound.y);
}
b2Bound.b2Bound = function () {};
b2Bound.prototype.IsLower = function () {
return (this.value & 1) == 0;
}
b2Bound.prototype.IsUpper = function () {
return (this.value & 1) == 1;
}
b2Bound.prototype.Swap = function (b) {
var tempValue = this.value;
var tempProxy = this.proxy;
var tempStabbingCount = this.stabbingCount;
this.value = b.value;
this.proxy = b.proxy;
this.stabbingCount = b.stabbingCount;
b.value = tempValue;
b.proxy = tempProxy;
b.stabbingCount = tempStabbingCount;
}
b2BoundValues.b2BoundValues = function () {};
b2BoundValues.prototype.b2BoundValues = function () {
this.lowerValues = new Vector_a2j_Number();
this.lowerValues[0] = 0.0;
this.lowerValues[1] = 0.0;
this.upperValues = new Vector_a2j_Number();
this.upperValues[0] = 0.0;
this.upperValues[1] = 0.0;
}
b2BroadPhase.b2BroadPhase = function () {
this.m_pairManager = new b2PairManager();
this.m_proxyPool = new Array();
this.m_querySortKeys = new Array();
this.m_queryResults = new Array();
this.m_quantizationFactor = new b2Vec2();
};
b2BroadPhase.prototype.b2BroadPhase = function (worldAABB) {
var i = 0;
this.m_pairManager.Initialize(this);
this.m_worldAABB = worldAABB;
this.m_proxyCount = 0;
this.m_bounds = new Vector();
for (i = 0;
i < 2; i++) {
this.m_bounds[i] = new Vector();
}
var dX = worldAABB.upperBound.x - worldAABB.lowerBound.x;
var dY = worldAABB.upperBound.y - worldAABB.lowerBound.y;
this.m_quantizationFactor.x = b2Settings.USHRT_MAX / dX;
this.m_quantizationFactor.y = b2Settings.USHRT_MAX / dY;
this.m_timeStamp = 1;
this.m_queryResultCount = 0;
}
b2BroadPhase.prototype.InRange = function (aabb) {
var dX = 0;
var dY = 0;
var d2X = 0;
var d2Y = 0;
dX = aabb.lowerBound.x;
dY = aabb.lowerBound.y;
dX -= this.m_worldAABB.upperBound.x;
dY -= this.m_worldAABB.upperBound.y;
d2X = this.m_worldAABB.lowerBound.x;
d2Y = this.m_worldAABB.lowerBound.y;
d2X -= aabb.upperBound.x;
d2Y -= aabb.upperBound.y;
dX = b2Math.Max(dX, d2X);
dY = b2Math.Max(dY, d2Y);
return b2Math.Max(dX, dY) < 0.0;
}
b2BroadPhase.prototype.CreateProxy = function (aabb, userData) {
var index = 0;
var proxy;
var i = 0;
var j = 0;
if (!this.m_freeProxy) {
this.m_freeProxy = this.m_proxyPool[this.m_proxyCount] = new b2Proxy();
this.m_freeProxy.next = null;
this.m_freeProxy.timeStamp = 0;
this.m_freeProxy.overlapCount = b2BroadPhase.b2_invalid;
this.m_freeProxy.userData = null;
for (i = 0;
i < 2; i++) {
j = this.m_proxyCount * 2;
this.m_bounds[i][j++] = new b2Bound();
this.m_bounds[i][j] = new b2Bound();
}
}
proxy = this.m_freeProxy;
this.m_freeProxy = proxy.next;
proxy.overlapCount = 0;
proxy.userData = userData;
var boundCount = 2 * this.m_proxyCount;
var lowerValues = new Vector_a2j_Number();
var upperValues = new Vector_a2j_Number();
this.ComputeBounds(lowerValues, upperValues, aabb);
for (var axis = 0; axis < 2; ++axis) {
var bounds = this.m_bounds[axis];
var lowerIndex = 0;
var upperIndex = 0;
var lowerIndexOut = new Vector_a2j_Number();
lowerIndexOut.push(lowerIndex);
var upperIndexOut = new Vector_a2j_Number();
upperIndexOut.push(upperIndex);
this.QueryAxis(lowerIndexOut, upperIndexOut, lowerValues[axis], upperValues[axis], bounds, boundCount, axis);
lowerIndex = lowerIndexOut[0];
upperIndex = upperIndexOut[0];
bounds.splice(upperIndex, 0, bounds[bounds.length - 1]);
bounds.length--;
bounds.splice(lowerIndex, 0, bounds[bounds.length - 1]);
bounds.length--;
++upperIndex;
var tBound1 = bounds[lowerIndex];
var tBound2 = bounds[upperIndex];
tBound1.value = lowerValues[axis];
tBound1.proxy = proxy;
tBound2.value = upperValues[axis];
tBound2.proxy = proxy;
var tBoundAS3 = bounds[parseInt(lowerIndex - 1)];
tBound1.stabbingCount = lowerIndex == 0 ? 0 : tBoundAS3.stabbingCount;
tBoundAS3 = bounds[parseInt(upperIndex - 1)];
tBound2.stabbingCount = tBoundAS3.stabbingCount;
for (index = lowerIndex;
index < upperIndex; ++index) {
tBoundAS3 = bounds[index];
tBoundAS3.stabbingCount++;
}
for (index = lowerIndex;
index < boundCount + 2; ++index) {
tBound1 = bounds[index];
var proxy2 = tBound1.proxy;
if (tBound1.IsLower()) {
proxy2.lowerBounds[axis] = index;
}
else {
proxy2.upperBounds[axis] = index;
}
}
}++this.m_proxyCount;
for (i = 0;
i < this.m_queryResultCount; ++i) {
this.m_pairManager.AddBufferedPair(proxy, this.m_queryResults[i]);
}
this.m_queryResultCount = 0;
this.IncrementTimeStamp();
return proxy;
}
b2BroadPhase.prototype.DestroyProxy = function (proxy_) {
var proxy = (proxy_ instanceof b2Proxy ? proxy_ : null);
var tBound1;
var tBound2;
var boundCount = parseInt(2 * this.m_proxyCount);
for (var axis = 0; axis < 2; ++axis) {
var bounds = this.m_bounds[axis];
var lowerIndex = proxy.lowerBounds[axis];
var upperIndex = proxy.upperBounds[axis];
tBound1 = bounds[lowerIndex];
var lowerValue = tBound1.value;
tBound2 = bounds[upperIndex];
var upperValue = tBound2.value;
bounds.splice(upperIndex, 1);
bounds.splice(lowerIndex, 1);
bounds.push(tBound1);
bounds.push(tBound2);
var tEnd = parseInt(boundCount - 2);
for (var index = lowerIndex; index < tEnd; ++index) {
tBound1 = bounds[index];
var proxy2 = tBound1.proxy;
if (tBound1.IsLower()) {
proxy2.lowerBounds[axis] = index;
}
else {
proxy2.upperBounds[axis] = index;
}
}
tEnd = upperIndex - 1;
for (var index2 = parseInt(lowerIndex); index2 < tEnd; ++index2) {
tBound1 = bounds[index2];
tBound1.stabbingCount--;
}
var ignore = new Vector_a2j_Number();
this.QueryAxis(ignore, ignore, lowerValue, upperValue, bounds, boundCount - 2, axis);
}
for (var i = 0; i < this.m_queryResultCount; ++i) {
this.m_pairManager.RemoveBufferedPair(proxy, this.m_queryResults[i]);
}
this.m_queryResultCount = 0;
this.IncrementTimeStamp();
proxy.userData = null;
proxy.overlapCount = b2BroadPhase.b2_invalid;
proxy.lowerBounds[0] = b2BroadPhase.b2_invalid;
proxy.lowerBounds[1] = b2BroadPhase.b2_invalid;
proxy.upperBounds[0] = b2BroadPhase.b2_invalid;
proxy.upperBounds[1] = b2BroadPhase.b2_invalid;
proxy.next = this.m_freeProxy;
this.m_freeProxy = proxy;
--this.m_proxyCount;
}
b2BroadPhase.prototype.MoveProxy = function (proxy_, aabb, displacement) {
var proxy = (proxy_ instanceof b2Proxy ? proxy_ : null);
var as3arr;
var as3int = 0;
var axis = 0;
var index = 0;
var bound;
var prevBound;
var nextBound;
var nextProxyId = 0;
var nextProxy;
if (proxy == null) {
return;
}
if (aabb.IsValid() == false) {
return;
}
var boundCount = 2 * this.m_proxyCount;
var newValues = new b2BoundValues();
this.ComputeBounds(newValues.lowerValues, newValues.upperValues, aabb);
var oldValues = new b2BoundValues();
for (axis = 0;
axis < 2; ++axis) {
bound = this.m_bounds[axis][proxy.lowerBounds[axis]];
oldValues.lowerValues[axis] = bound.value;
bound = this.m_bounds[axis][proxy.upperBounds[axis]];
oldValues.upperValues[axis] = bound.value;
}
for (axis = 0;
axis < 2; ++axis) {
var bounds = this.m_bounds[axis];
var lowerIndex = proxy.lowerBounds[axis];
var upperIndex = proxy.upperBounds[axis];
var lowerValue = newValues.lowerValues[axis];
var upperValue = newValues.upperValues[axis];
bound = bounds[lowerIndex];
var deltaLower = parseInt(lowerValue - bound.value);
bound.value = lowerValue;
bound = bounds[upperIndex];
var deltaUpper = parseInt(upperValue - bound.value);
bound.value = upperValue;
if (deltaLower < 0) {
index = lowerIndex;
while (index > 0 && lowerValue < ((bounds[parseInt(index - 1)] instanceof b2Bound ? bounds[parseInt(index - 1)] : null)).value) {
bound = bounds[index];
prevBound = bounds[parseInt(index - 1)];
var prevProxy = prevBound.proxy;
prevBound.stabbingCount++;
if (prevBound.IsUpper() == true) {
if (this.TestOverlapBound(newValues, prevProxy)) {
this.m_pairManager.AddBufferedPair(proxy, prevProxy);
}
as3arr = prevProxy.upperBounds;
as3int = as3arr[axis];
as3int++;
as3arr[axis] = as3int;
bound.stabbingCount++;
}
else {
as3arr = prevProxy.lowerBounds;
as3int = as3arr[axis];
as3int++;
as3arr[axis] = as3int;
bound.stabbingCount--;
}
as3arr = proxy.lowerBounds;
as3int = as3arr[axis];
as3int--;
as3arr[axis] = as3int;
bound.Swap(prevBound);
--index;
}
}
if (deltaUpper > 0) {
index = upperIndex;
while (index < boundCount - 1 && ((bounds[parseInt(index + 1)] instanceof b2Bound ? bounds[parseInt(index + 1)] : null)).value <= upperValue) {
bound = bounds[index];
nextBound = bounds[parseInt(index + 1)];
nextProxy = nextBound.proxy;
nextBound.stabbingCount++;
if (nextBound.IsLower() == true) {
if (this.TestOverlapBound(newValues, nextProxy)) {
this.m_pairManager.AddBufferedPair(proxy, nextProxy);
}
as3arr = nextProxy.lowerBounds;
as3int = as3arr[axis];
as3int--;
as3arr[axis] = as3int;
bound.stabbingCount++;
}
else {
as3arr = nextProxy.upperBounds;
as3int = as3arr[axis];
as3int--;
as3arr[axis] = as3int;
bound.stabbingCount--;
}
as3arr = proxy.upperBounds;
as3int = as3arr[axis];
as3int++;
as3arr[axis] = as3int;
bound.Swap(nextBound);
index++;
}
}
if (deltaLower > 0) {
index = lowerIndex;
while (index < boundCount - 1 && ((bounds[parseInt(index + 1)] instanceof b2Bound ? bounds[parseInt(index + 1)] : null)).value <= lowerValue) {
bound = bounds[index];
nextBound = bounds[parseInt(index + 1)];
nextProxy = nextBound.proxy;
nextBound.stabbingCount--;
if (nextBound.IsUpper()) {
if (this.TestOverlapBound(oldValues, nextProxy)) {
this.m_pairManager.RemoveBufferedPair(proxy, nextProxy);
}
as3arr = nextProxy.upperBounds;
as3int = as3arr[axis];
as3int--;
as3arr[axis] = as3int;
bound.stabbingCount--;
}
else {
as3arr = nextProxy.lowerBounds;
as3int = as3arr[axis];
as3int--;
as3arr[axis] = as3int;
bound.stabbingCount++;
}
as3arr = proxy.lowerBounds;
as3int = as3arr[axis];
as3int++;
as3arr[axis] = as3int;
bound.Swap(nextBound);
index++;
}
}
if (deltaUpper < 0) {
index = upperIndex;
while (index > 0 && upperValue < ((bounds[parseInt(index - 1)] instanceof b2Bound ? bounds[parseInt(index - 1)] : null)).value) {
bound = bounds[index];
prevBound = bounds[parseInt(index - 1)];
prevProxy = prevBound.proxy;
prevBound.stabbingCount--;
if (prevBound.IsLower() == true) {
if (this.TestOverlapBound(oldValues, prevProxy)) {
this.m_pairManager.RemoveBufferedPair(proxy, prevProxy);
}
as3arr = prevProxy.lowerBounds;
as3int = as3arr[axis];
as3int++;
as3arr[axis] = as3int;
bound.stabbingCount--;
}
else {
as3arr = prevProxy.upperBounds;
as3int = as3arr[axis];
as3int++;
as3arr[axis] = as3int;
bound.stabbingCount++;
}
as3arr = proxy.upperBounds;
as3int = as3arr[axis];
as3int--;
as3arr[axis] = as3int;
bound.Swap(prevBound);
index--;
}
}
}
}
b2BroadPhase.prototype.UpdatePairs = function (callback) {
this.m_pairManager.Commit(callback);
}
b2BroadPhase.prototype.TestOverlap = function (proxyA, proxyB) {
var proxyA_ = (proxyA instanceof b2Proxy ? proxyA : null);
var proxyB_ = (proxyB instanceof b2Proxy ? proxyB : null);
if (proxyA_.lowerBounds[0] > proxyB_.upperBounds[0]) return false;
if (proxyB_.lowerBounds[0] > proxyA_.upperBounds[0]) return false;
if (proxyA_.lowerBounds[1] > proxyB_.upperBounds[1]) return false;
if (proxyB_.lowerBounds[1] > proxyA_.upperBounds[1]) return false;
return true;
}
b2BroadPhase.prototype.GetUserData = function (proxy) {
return ((proxy instanceof b2Proxy ? proxy : null)).userData;
}
b2BroadPhase.prototype.GetFatAABB = function (proxy_) {
var aabb = new b2AABB();
var proxy = (proxy_ instanceof b2Proxy ? proxy_ : null);
aabb.lowerBound.x = this.m_worldAABB.lowerBound.x + this.m_bounds[0][proxy.lowerBounds[0]].value / this.m_quantizationFactor.x;
aabb.lowerBound.y = this.m_worldAABB.lowerBound.y + this.m_bounds[1][proxy.lowerBounds[1]].value / this.m_quantizationFactor.y;
aabb.upperBound.x = this.m_worldAABB.lowerBound.x + this.m_bounds[0][proxy.upperBounds[0]].value / this.m_quantizationFactor.x;
aabb.upperBound.y = this.m_worldAABB.lowerBound.y + this.m_bounds[1][proxy.upperBounds[1]].value / this.m_quantizationFactor.y;
return aabb;
}
b2BroadPhase.prototype.GetProxyCount = function () {
return this.m_proxyCount;
}
b2BroadPhase.prototype.Query = function (callback, aabb) {
var lowerValues = new Vector_a2j_Number();
var upperValues = new Vector_a2j_Number();
this.ComputeBounds(lowerValues, upperValues, aabb);
var lowerIndex = 0;
var upperIndex = 0;
var lowerIndexOut = new Vector_a2j_Number();
lowerIndexOut.push(lowerIndex);
var upperIndexOut = new Vector_a2j_Number();
upperIndexOut.push(upperIndex);
this.QueryAxis(lowerIndexOut, upperIndexOut, lowerValues[0], upperValues[0], this.m_bounds[0], 2 * this.m_proxyCount, 0);
this.QueryAxis(lowerIndexOut, upperIndexOut, lowerValues[1], upperValues[1], this.m_bounds[1], 2 * this.m_proxyCount, 1);
for (var i = 0; i < this.m_queryResultCount; ++i) {
var proxy = this.m_queryResults[i];
if (!callback(proxy)) {
break;
}
}
this.m_queryResultCount = 0;
this.IncrementTimeStamp();
}
b2BroadPhase.prototype.Validate = function () {
var pair;
var proxy1;
var proxy2;
var overlap;
for (var axis = 0; axis < 2; ++axis) {
var bounds = this.m_bounds[axis];
var boundCount = 2 * this.m_proxyCount;
var stabbingCount = 0;
for (var i = 0; i < boundCount; ++i) {
var bound = bounds[i];
if (bound.IsLower() == true) {
stabbingCount++;
}
else {
stabbingCount--;
}
}
}
}
b2BroadPhase.prototype.Rebalance = function (iterations) {
if (iterations === undefined) iterations = 0;
}
b2BroadPhase.prototype.RayCast = function (callback, input) {
var subInput = new b2RayCastInput();
subInput.p1.SetV(input.p1);
subInput.p2.SetV(input.p2);
subInput.maxFraction = input.maxFraction;
var dx = (input.p2.x - input.p1.x) * this.m_quantizationFactor.x;
var dy = (input.p2.y - input.p1.y) * this.m_quantizationFactor.y;
var sx = parseInt(dx < (-Number.MIN_VALUE ? (-1) : (dx > Number.MIN_VALUE ? 1 : 0)));
var sy = parseInt(dy < (-Number.MIN_VALUE ? (-1) : (dy > Number.MIN_VALUE ? 1 : 0)));
var p1x = this.m_quantizationFactor.x * (input.p1.x - this.m_worldAABB.lowerBound.x);
var p1y = this.m_quantizationFactor.y * (input.p1.y - this.m_worldAABB.lowerBound.y);
var startValues = new Array();
var startValues2 = new Array();
startValues[0] = a2j.parseUInt(p1x) & (b2Settings.USHRT_MAX - 1);
startValues[1] = a2j.parseUInt(p1y) & (b2Settings.USHRT_MAX - 1);
startValues2[0] = startValues[0] + 1;
startValues2[1] = startValues[1] + 1;
var startIndices = new Array();
var xIndex = 0;
var yIndex = 0;
var proxy;
var lowerIndex = 0;
var upperIndex = 0;
var lowerIndexOut = new Vector_a2j_Number();
lowerIndexOut.push(lowerIndex);
var upperIndexOut = new Vector_a2j_Number();
upperIndexOut.push(upperIndex);
this.QueryAxis(lowerIndexOut, upperIndexOut, startValues[0], startValues2[0], this.m_bounds[0], 2 * this.m_proxyCount, 0);
if (sx >= 0) xIndex = upperIndexOut[0] - 1;
else xIndex = lowerIndexOut[0];
this.QueryAxis(lowerIndexOut, upperIndexOut, startValues[1], startValues2[1], this.m_bounds[1], 2 * this.m_proxyCount, 1);
if (sy >= 0) yIndex = upperIndexOut[0] - 1;
else yIndex = lowerIndexOut[0];
for (var i = 0; i < this.m_queryResultCount; i++) {
subInput.maxFraction = callback(subInput, this.m_queryResults[i]);
}
for (;;) {
var xProgress = 0;
var yProgress = 0;
xIndex += sx >= 0 ? 1 : (-1);
if (xIndex < 0 || xIndex >= this.m_proxyCount * 2) break;
if (sx != 0) {
xProgress = (this.m_bounds[0][xIndex].value - p1x) / dx;
}
yIndex += sy >= 0 ? 1 : (-1);
if (yIndex < 0 || yIndex >= this.m_proxyCount * 2) break;
if (sy != 0) {
yProgress = (this.m_bounds[1][yIndex].value - p1y) / dy;
}
for (;;) {
if (sy == 0 || (sx != 0 && xProgress < yProgress)) {
if (xProgress > subInput.maxFraction) break;
if (sx > 0 ? this.m_bounds[0][xIndex].IsLower() : this.m_bounds[0][xIndex].IsUpper()) {
proxy = this.m_bounds[0][xIndex].proxy;
if (sy >= 0) {
if (proxy.lowerBounds[1] <= yIndex - 1 && proxy.upperBounds[1] >= yIndex) {
subInput.maxFraction = callback(subInput, proxy);
}
}
else {
if (proxy.lowerBounds[1] <= yIndex && proxy.upperBounds[1] >= yIndex + 1) {
subInput.maxFraction = callback(subInput, proxy);
}
}
}
if (subInput.maxFraction == 0) break;
if (sx > 0) {
xIndex++;
if (xIndex == this.m_proxyCount * 2) break;
}
else {
xIndex--;
if (xIndex < 0) break;
}
xProgress = (this.m_bounds[0][xIndex].value - p1x) / dx;
}
else {
if (yProgress > subInput.maxFraction) break;
if (sy > 0 ? this.m_bounds[1][yIndex].IsLower() : this.m_bounds[1][yIndex].IsUpper()) {
proxy = this.m_bounds[1][yIndex].proxy;
if (sx >= 0) {
if (proxy.lowerBounds[0] <= xIndex - 1 && proxy.upperBounds[0] >= xIndex) {
subInput.maxFraction = callback(subInput, proxy);
}
}
else {
if (proxy.lowerBounds[0] <= xIndex && proxy.upperBounds[0] >= xIndex + 1) {
subInput.maxFraction = callback(subInput, proxy);
}
}
}
if (subInput.maxFraction == 0) break;
if (sy > 0) {
yIndex++;
if (yIndex == this.m_proxyCount * 2) break;
}
else {
yIndex--;
if (yIndex < 0) break;
}
yProgress = (this.m_bounds[1][yIndex].value - p1y) / dy;
}
}
break;
}
this.m_queryResultCount = 0;
this.IncrementTimeStamp();
return;
}
b2BroadPhase.prototype.ComputeBounds = function (lowerValues, upperValues, aabb) {
var minVertexX = aabb.lowerBound.x;
var minVertexY = aabb.lowerBound.y;
minVertexX = b2Math.Min(minVertexX, this.m_worldAABB.upperBound.x);
minVertexY = b2Math.Min(minVertexY, this.m_worldAABB.upperBound.y);
minVertexX = b2Math.Max(minVertexX, this.m_worldAABB.lowerBound.x);
minVertexY = b2Math.Max(minVertexY, this.m_worldAABB.lowerBound.y);
var maxVertexX = aabb.upperBound.x;
var maxVertexY = aabb.upperBound.y;
maxVertexX = b2Math.Min(maxVertexX, this.m_worldAABB.upperBound.x);
maxVertexY = b2Math.Min(maxVertexY, this.m_worldAABB.upperBound.y);
maxVertexX = b2Math.Max(maxVertexX, this.m_worldAABB.lowerBound.x);
maxVertexY = b2Math.Max(maxVertexY, this.m_worldAABB.lowerBound.y);
lowerValues[0] = a2j.parseUInt(this.m_quantizationFactor.x * (minVertexX - this.m_worldAABB.lowerBound.x)) & (b2Settings.USHRT_MAX - 1);
upperValues[0] = (a2j.parseUInt(this.m_quantizationFactor.x * (maxVertexX - this.m_worldAABB.lowerBound.x)) & 0x0000ffff) | 1;
lowerValues[1] = a2j.parseUInt(this.m_quantizationFactor.y * (minVertexY - this.m_worldAABB.lowerBound.y)) & (b2Settings.USHRT_MAX - 1);
upperValues[1] = (a2j.parseUInt(this.m_quantizationFactor.y * (maxVertexY - this.m_worldAABB.lowerBound.y)) & 0x0000ffff) | 1;
}
b2BroadPhase.prototype.TestOverlapValidate = function (p1, p2) {
for (var axis = 0; axis < 2; ++axis) {
var bounds = this.m_bounds[axis];
var bound1 = bounds[p1.lowerBounds[axis]];
var bound2 = bounds[p2.upperBounds[axis]];
if (bound1.value > bound2.value) return false;
bound1 = bounds[p1.upperBounds[axis]];
bound2 = bounds[p2.lowerBounds[axis]];
if (bound1.value < bound2.value) return false;
}
return true;
}
b2BroadPhase.prototype.TestOverlapBound = function (b, p) {
for (var axis = 0; axis < 2; ++axis) {
var bounds = this.m_bounds[axis];
var bound = bounds[p.upperBounds[axis]];
if (b.lowerValues[axis] > bound.value) return false;
bound = bounds[p.lowerBounds[axis]];
if (b.upperValues[axis] < bound.value) return false;
}
return true;
}
b2BroadPhase.prototype.QueryAxis = function (lowerQueryOut, upperQueryOut, lowerValue, upperValue, bounds, boundCount, axis) {
if (lowerValue === undefined) lowerValue = 0;
if (upperValue === undefined) upperValue = 0;
if (boundCount === undefined) boundCount = 0;
if (axis === undefined) axis = 0;
var lowerQuery = this.BinarySearch(bounds, boundCount, lowerValue);
var upperQuery = this.BinarySearch(bounds, boundCount, upperValue);
var bound;
for (var j = lowerQuery; j < upperQuery; ++j) {
bound = bounds[j];
if (bound.IsLower()) {
this.IncrementOverlapCount(bound.proxy);
}
}
if (lowerQuery > 0) {
var i = parseInt(lowerQuery - 1);
bound = bounds[i];
var s = parseInt(bound.stabbingCount);
while (s) {
bound = bounds[i];
if (bound.IsLower()) {
var proxy = bound.proxy;
if (lowerQuery <= proxy.upperBounds[axis]) {
this.IncrementOverlapCount(bound.proxy);
--s;
}
}--i;
}
}
lowerQueryOut[0] = lowerQuery;
upperQueryOut[0] = upperQuery;
}
b2BroadPhase.prototype.IncrementOverlapCount = function (proxy) {
if (proxy.timeStamp < this.m_timeStamp) {
proxy.timeStamp = this.m_timeStamp;
proxy.overlapCount = 1;
}
else {
proxy.overlapCount = 2;
this.m_queryResults[this.m_queryResultCount] = proxy;
++this.m_queryResultCount;
}
}
b2BroadPhase.prototype.IncrementTimeStamp = function () {
if (this.m_timeStamp == b2Settings.USHRT_MAX) {
for (var i = 0; i < this.m_proxyPool.length; ++i) {
((this.m_proxyPool[i] instanceof b2Proxy ? this.m_proxyPool[i] : null)).timeStamp = 0;
}
this.m_timeStamp = 1;
}
else {
++this.m_timeStamp;
}
}
b2BroadPhase.prototype.BinarySearch = function (bounds, count, value) {
if (count === undefined) count = 0;
if (value === undefined) value = 0;
var low = 0;
var high = parseInt(count - 1);
while (low <= high) {
var mid = parseInt(((low + high) / 2));
var bound = bounds[mid];
if (bound.value > value) {
high = mid - 1;
}
else if (bound.value < value) {
low = mid + 1;
}
else {
return a2j.parseUInt(mid);
}
}
return a2j.parseUInt(low);
}
b2BroadPhase.BinarySearch = b2BroadPhase.prototype.BinarySearch;
_A2J_postDefs.push(function () {
Box2D.Collision.b2BroadPhase.s_validate = false;
Box2D.Collision.b2BroadPhase.prototype.s_validate = Box2D.Collision.b2BroadPhase.s_validate;
Box2D.Collision.b2BroadPhase.b2_invalid = parseInt(b2Settings.USHRT_MAX);
Box2D.Collision.b2BroadPhase.prototype.b2_invalid = Box2D.Collision.b2BroadPhase.b2_invalid;
Box2D.Collision.b2BroadPhase.b2_nullEdge = parseInt(b2Settings.USHRT_MAX);
Box2D.Collision.b2BroadPhase.prototype.b2_nullEdge = Box2D.Collision.b2BroadPhase.b2_nullEdge;
});
b2BroadPhase.__implements = {};
b2BroadPhase.__implements[IBroadPhase] = true;
b2Collision.b2Collision = function () {};
b2Collision.prototype.ClipSegmentToLine = function (vOut, vIn, normal, offset) {
if (offset === undefined) offset = 0;
var cv;
var numOut = 0;
cv = vIn[0];
var vIn0 = cv.v;
cv = vIn[1];
var vIn1 = cv.v;
var distance0 = normal.x * vIn0.x + normal.y * vIn0.y - offset;
var distance1 = normal.x * vIn1.x + normal.y * vIn1.y - offset;
if (distance0 <= 0.0) vOut[numOut++].Set(vIn[0]);
if (distance1 <= 0.0) vOut[numOut++].Set(vIn[1]);
if (distance0 * distance1 < 0.0) {
var interp = distance0 / (distance0 - distance1);
cv = vOut[numOut];
var tVec = cv.v;
tVec.x = vIn0.x + interp * (vIn1.x - vIn0.x);
tVec.y = vIn0.y + interp * (vIn1.y - vIn0.y);
cv = vOut[numOut];
var cv2;
if (distance0 > 0.0) {
cv2 = vIn[0];
cv.id = cv2.id;
}
else {
cv2 = vIn[1];
cv.id = cv2.id;
}++numOut;
}
return numOut;
}
b2Collision.ClipSegmentToLine = b2Collision.prototype.ClipSegmentToLine;
b2Collision.prototype.EdgeSeparation = function (poly1, xf1, edge1, poly2, xf2) {
if (edge1 === undefined) edge1 = 0;
var count1 = parseInt(poly1.m_vertexCount);
var vertices1 = poly1.m_vertices;
var normals1 = poly1.m_normals;
var count2 = parseInt(poly2.m_vertexCount);
var vertices2 = poly2.m_vertices;
var tMat;
var tVec;
tMat = xf1.R;
tVec = normals1[edge1];
var normal1WorldX = (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
var normal1WorldY = (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
tMat = xf2.R;
var normal1X = (tMat.col1.x * normal1WorldX + tMat.col1.y * normal1WorldY);
var normal1Y = (tMat.col2.x * normal1WorldX + tMat.col2.y * normal1WorldY);
var index = 0;
var minDot = Number.MAX_VALUE;
for (var i = 0; i < count2; ++i) {
tVec = vertices2[i];
var dot = tVec.x * normal1X + tVec.y * normal1Y;
if (dot < minDot) {
minDot = dot;
index = i;
}
}
tVec = vertices1[edge1];
tMat = xf1.R;
var v1X = xf1.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
var v1Y = xf1.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
tVec = vertices2[index];
tMat = xf2.R;
var v2X = xf2.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
var v2Y = xf2.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
v2X -= v1X;
v2Y -= v1Y;
var separation = v2X * normal1WorldX + v2Y * normal1WorldY;
return separation;
}
b2Collision.EdgeSeparation = b2Collision.prototype.EdgeSeparation;
b2Collision.prototype.FindMaxSeparation = function (edgeIndex, poly1, xf1, poly2, xf2) {
var count1 = parseInt(poly1.m_vertexCount);
var normals1 = poly1.m_normals;
var tVec;
var tMat;
tMat = xf2.R;
tVec = poly2.m_centroid;
var dX = xf2.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
var dY = xf2.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
tMat = xf1.R;
tVec = poly1.m_centroid;
dX -= xf1.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
dY -= xf1.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
var dLocal1X = (dX * xf1.R.col1.x + dY * xf1.R.col1.y);
var dLocal1Y = (dX * xf1.R.col2.x + dY * xf1.R.col2.y);
var edge = 0;
var maxDot = (-Number.MAX_VALUE);
for (var i = 0; i < count1; ++i) {
tVec = normals1[i];
var dot = (tVec.x * dLocal1X + tVec.y * dLocal1Y);
if (dot > maxDot) {
maxDot = dot;
edge = i;
}
}
var s = this.EdgeSeparation(poly1, xf1, edge, poly2, xf2);
var prevEdge = parseInt(edge - 1 >= 0 ? edge - 1 : count1 - 1);
var sPrev = this.EdgeSeparation(poly1, xf1, prevEdge, poly2, xf2);
var nextEdge = parseInt(edge + 1 < count1 ? edge + 1 : 0);
var sNext = this.EdgeSeparation(poly1, xf1, nextEdge, poly2, xf2);
var bestEdge = 0;
var bestSeparation = 0;
var increment = 0;
if (sPrev > s && sPrev > sNext) {
increment = (-1);
bestEdge = prevEdge;
bestSeparation = sPrev;
}
else if (sNext > s) {
increment = 1;
bestEdge = nextEdge;
bestSeparation = sNext;
}
else {
edgeIndex[0] = edge;
return s;
}
while (true) {
if (increment == (-1)) edge = bestEdge - 1 >= 0 ? bestEdge - 1 : count1 - 1;
else edge = bestEdge + 1 < count1 ? bestEdge + 1 : 0;s = this.EdgeSeparation(poly1, xf1, edge, poly2, xf2);
if (s > bestSeparation) {
bestEdge = edge;
bestSeparation = s;
}
else {
break;
}
}
edgeIndex[0] = bestEdge;
return bestSeparation;
}
b2Collision.FindMaxSeparation = b2Collision.prototype.FindMaxSeparation;
b2Collision.prototype.FindIncidentEdge = function (c, poly1, xf1, edge1, poly2, xf2) {
if (edge1 === undefined) edge1 = 0;
var count1 = parseInt(poly1.m_vertexCount);
var normals1 = poly1.m_normals;
var count2 = parseInt(poly2.m_vertexCount);
var vertices2 = poly2.m_vertices;
var normals2 = poly2.m_normals;
var tMat;
var tVec;
tMat = xf1.R;
tVec = normals1[edge1];
var normal1X = (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
var normal1Y = (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
tMat = xf2.R;
var tX = (tMat.col1.x * normal1X + tMat.col1.y * normal1Y);
normal1Y = (tMat.col2.x * normal1X + tMat.col2.y * normal1Y);
normal1X = tX;
var index = 0;
var minDot = Number.MAX_VALUE;
for (var i = 0; i < count2; ++i) {
tVec = normals2[i];
var dot = (normal1X * tVec.x + normal1Y * tVec.y);
if (dot < minDot) {
minDot = dot;
index = i;
}
}
var tClip;
var i1 = parseInt(index);
var i2 = parseInt(i1 + 1 < count2 ? i1 + 1 : 0);
tClip = c[0];
tVec = vertices2[i1];
tMat = xf2.R;
tClip.v.x = xf2.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
tClip.v.y = xf2.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
tClip.id.features.referenceEdge = edge1;
tClip.id.features.incidentEdge = i1;
tClip.id.features.incidentVertex = 0;
tClip = c[1];
tVec = vertices2[i2];
tMat = xf2.R;
tClip.v.x = xf2.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
tClip.v.y = xf2.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
tClip.id.features.referenceEdge = edge1;
tClip.id.features.incidentEdge = i2;
tClip.id.features.incidentVertex = 1;
}
b2Collision.FindIncidentEdge = b2Collision.prototype.FindIncidentEdge;
b2Collision.prototype.MakeClipPointVector = function () {
var r = new Vector(2);
r[0] = new ClipVertex();
r[1] = new ClipVertex();
return r;
}
b2Collision.MakeClipPointVector = b2Collision.prototype.MakeClipPointVector;
b2Collision.prototype.CollidePolygons = function (manifold, polyA, xfA, polyB, xfB) {
var cv;
manifold.m_pointCount = 0;
var totalRadius = polyA.m_radius + polyB.m_radius;
var edgeA = 0;
b2Collision.s_edgeAO[0] = edgeA;
var separationA = this.FindMaxSeparation(b2Collision.s_edgeAO, polyA, xfA, polyB, xfB);
edgeA = b2Collision.s_edgeAO[0];
if (separationA > totalRadius) return;
var edgeB = 0;
b2Collision.s_edgeBO[0] = edgeB;
var separationB = this.FindMaxSeparation(b2Collision.s_edgeBO, polyB, xfB, polyA, xfA);
edgeB = b2Collision.s_edgeBO[0];
if (separationB > totalRadius) return;
var poly1;
var poly2;
var xf1;
var xf2;
var edge1 = 0;
var flip = 0;
var k_relativeTol = 0.98;
var k_absoluteTol = 0.001;
var tMat;
if (separationB > k_relativeTol * separationA + k_absoluteTol) {
poly1 = polyB;
poly2 = polyA;
xf1 = xfB;
xf2 = xfA;
edge1 = edgeB;
manifold.m_type = b2Manifold.e_faceB;
flip = 1;
}
else {
poly1 = polyA;
poly2 = polyB;
xf1 = xfA;
xf2 = xfB;
edge1 = edgeA;
manifold.m_type = b2Manifold.e_faceA;
flip = 0;
}
var incidentEdge = b2Collision.s_incidentEdge;
this.FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2);
var count1 = parseInt(poly1.m_vertexCount);
var vertices1 = poly1.m_vertices;
var local_v11 = vertices1[edge1];
var local_v12;
if (edge1 + 1 < count1) {
local_v12 = vertices1[parseInt(edge1 + 1)];
}
else {
local_v12 = vertices1[0];
}
var localTangent = b2Collision.s_localTangent;
localTangent.Set(local_v12.x - local_v11.x, local_v12.y - local_v11.y);
localTangent.Normalize();
var localNormal = b2Collision.s_localNormal;
localNormal.x = localTangent.y;
localNormal.y = (-localTangent.x);
var planePoint = b2Collision.s_planePoint;
planePoint.Set(0.5 * (local_v11.x + local_v12.x), 0.5 * (local_v11.y + local_v12.y));
var tangent = b2Collision.s_tangent;
tMat = xf1.R;
tangent.x = (tMat.col1.x * localTangent.x + tMat.col2.x * localTangent.y);
tangent.y = (tMat.col1.y * localTangent.x + tMat.col2.y * localTangent.y);
var tangent2 = b2Collision.s_tangent2;
tangent2.x = (-tangent.x);
tangent2.y = (-tangent.y);
var normal = b2Collision.s_normal;
normal.x = tangent.y;
normal.y = (-tangent.x);
var v11 = b2Collision.s_v11;
var v12 = b2Collision.s_v12;
v11.x = xf1.position.x + (tMat.col1.x * local_v11.x + tMat.col2.x * local_v11.y);
v11.y = xf1.position.y + (tMat.col1.y * local_v11.x + tMat.col2.y * local_v11.y);
v12.x = xf1.position.x + (tMat.col1.x * local_v12.x + tMat.col2.x * local_v12.y);
v12.y = xf1.position.y + (tMat.col1.y * local_v12.x + tMat.col2.y * local_v12.y);
var frontOffset = normal.x * v11.x + normal.y * v11.y;
var sideOffset1 = (-tangent.x * v11.x) - tangent.y * v11.y + totalRadius;
var sideOffset2 = tangent.x * v12.x + tangent.y * v12.y + totalRadius;
var clipPoints1 = b2Collision.s_clipPoints1;
var clipPoints2 = b2Collision.s_clipPoints2;
var np = 0;
np = this.ClipSegmentToLine(clipPoints1, incidentEdge, tangent2, sideOffset1);
if (np < 2) return;
np = this.ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2);
if (np < 2) return;
manifold.m_localPlaneNormal.SetV(localNormal);
manifold.m_localPoint.SetV(planePoint);
var pointCount = 0;
for (var i = 0; i < b2Settings.b2_maxManifoldPoints; ++i) {
cv = clipPoints2[i];
var separation = normal.x * cv.v.x + normal.y * cv.v.y - frontOffset;
if (separation <= totalRadius) {
var cp = manifold.m_points[pointCount];
tMat = xf2.R;
var tX = cv.v.x - xf2.position.x;
var tY = cv.v.y - xf2.position.y;
cp.m_localPoint.x = (tX * tMat.col1.x + tY * tMat.col1.y);
cp.m_localPoint.y = (tX * tMat.col2.x + tY * tMat.col2.y);
cp.m_id.Set(cv.id);
cp.m_id.features.flip = flip;
++pointCount;
}
}
manifold.m_pointCount = pointCount;
}
b2Collision.CollidePolygons = b2Collision.prototype.CollidePolygons;
b2Collision.prototype.CollideCircles = function (manifold, circle1, xf1, circle2, xf2) {
manifold.m_pointCount = 0;
var tMat;
var tVec;
tMat = xf1.R;
tVec = circle1.m_p;
var p1X = xf1.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
var p1Y = xf1.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
tMat = xf2.R;
tVec = circle2.m_p;
var p2X = xf2.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
var p2Y = xf2.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
var dX = p2X - p1X;
var dY = p2Y - p1Y;
var distSqr = dX * dX + dY * dY;
var radius = circle1.m_radius + circle2.m_radius;
if (distSqr > radius * radius) {
return;
}
manifold.m_type = b2Manifold.e_circles;
manifold.m_localPoint.SetV(circle1.m_p);
manifold.m_localPlaneNormal.SetZero();
manifold.m_pointCount = 1;
manifold.m_points[0].m_localPoint.SetV(circle2.m_p);
manifold.m_points[0].m_id.key = 0;
}
b2Collision.CollideCircles = b2Collision.prototype.CollideCircles;
b2Collision.prototype.CollidePolygonAndCircle = function (manifold, polygon, xf1, circle, xf2) {
manifold.m_pointCount = 0;
var tPoint;
var dX = 0;
var dY = 0;
var positionX = 0;
var positionY = 0;
var tVec;
var tMat;
tMat = xf2.R;
tVec = circle.m_p;
var cX = xf2.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
var cY = xf2.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
dX = cX - xf1.position.x;
dY = cY - xf1.position.y;
tMat = xf1.R;
var cLocalX = (dX * tMat.col1.x + dY * tMat.col1.y);
var cLocalY = (dX * tMat.col2.x + dY * tMat.col2.y);
var dist = 0;
var normalIndex = 0;
var separation = (-Number.MAX_VALUE);
var radius = polygon.m_radius + circle.m_radius;
var vertexCount = parseInt(polygon.m_vertexCount);
var vertices = polygon.m_vertices;
var normals = polygon.m_normals;
for (var i = 0; i < vertexCount; ++i) {
tVec = vertices[i];
dX = cLocalX - tVec.x;
dY = cLocalY - tVec.y;
tVec = normals[i];
var s = tVec.x * dX + tVec.y * dY;
if (s > radius) {
return;
}
if (s > separation) {
separation = s;
normalIndex = i;
}
}
var vertIndex1 = parseInt(normalIndex);
var vertIndex2 = parseInt(vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0);
var v1 = vertices[vertIndex1];
var v2 = vertices[vertIndex2];
if (separation < Number.MIN_VALUE) {
manifold.m_pointCount = 1;
manifold.m_type = b2Manifold.e_faceA;
manifold.m_localPlaneNormal.SetV(normals[normalIndex]);
manifold.m_localPoint.x = 0.5 * (v1.x + v2.x);
manifold.m_localPoint.y = 0.5 * (v1.y + v2.y);
manifold.m_points[0].m_localPoint.SetV(circle.m_p);
manifold.m_points[0].m_id.key = 0;
return;
}
var u1 = (cLocalX - v1.x) * (v2.x - v1.x) + (cLocalY - v1.y) * (v2.y - v1.y);
var u2 = (cLocalX - v2.x) * (v1.x - v2.x) + (cLocalY - v2.y) * (v1.y - v2.y);
if (u1 <= 0.0) {
if ((cLocalX - v1.x) * (cLocalX - v1.x) + (cLocalY - v1.y) * (cLocalY - v1.y) > radius * radius) return;
manifold.m_pointCount = 1;
manifold.m_type = b2Manifold.e_faceA;
manifold.m_localPlaneNormal.x = cLocalX - v1.x;
manifold.m_localPlaneNormal.y = cLocalY - v1.y;
manifold.m_localPlaneNormal.Normalize();
manifold.m_localPoint.SetV(v1);
manifold.m_points[0].m_localPoint.SetV(circle.m_p);
manifold.m_points[0].m_id.key = 0;
}
else if (u2 <= 0) {
if ((cLocalX - v2.x) * (cLocalX - v2.x) + (cLocalY - v2.y) * (cLocalY - v2.y) > radius * radius) return;
manifold.m_pointCount = 1;
manifold.m_type = b2Manifold.e_faceA;
manifold.m_localPlaneNormal.x = cLocalX - v2.x;
manifold.m_localPlaneNormal.y = cLocalY - v2.y;
manifold.m_localPlaneNormal.Normalize();
manifold.m_localPoint.SetV(v2);
manifold.m_points[0].m_localPoint.SetV(circle.m_p);
manifold.m_points[0].m_id.key = 0;
}
else {
var faceCenterX = 0.5 * (v1.x + v2.x);
var faceCenterY = 0.5 * (v1.y + v2.y);
separation = (cLocalX - faceCenterX) * normals[vertIndex1].x + (cLocalY - faceCenterY) * normals[vertIndex1].y;
if (separation > radius) return;
manifold.m_pointCount = 1;
manifold.m_type = b2Manifold.e_faceA;
manifold.m_localPlaneNormal.x = normals[vertIndex1].x;
manifold.m_localPlaneNormal.y = normals[vertIndex1].y;
manifold.m_localPlaneNormal.Normalize();
manifold.m_localPoint.Set(faceCenterX, faceCenterY);
manifold.m_points[0].m_localPoint.SetV(circle.m_p);
manifold.m_points[0].m_id.key = 0;
}
}
b2Collision.CollidePolygonAndCircle = b2Collision.prototype.CollidePolygonAndCircle;
b2Collision.prototype.TestOverlap = function (a, b) {
var t1 = b.lowerBound;
var t2 = a.upperBound;
var d1X = t1.x - t2.x;
var d1Y = t1.y - t2.y;
t1 = a.lowerBound;
t2 = b.upperBound;
var d2X = t1.x - t2.x;
var d2Y = t1.y - t2.y;
if (d1X > 0.0 || d1Y > 0.0) return false;
if (d2X > 0.0 || d2Y > 0.0) return false;
return true;
}
b2Collision.TestOverlap = b2Collision.prototype.TestOverlap;
_A2J_postDefs.push(function () {
Box2D.Collision.b2Collision.s_incidentEdge = b2Collision.MakeClipPointVector();
Box2D.Collision.b2Collision.prototype.s_incidentEdge = Box2D.Collision.b2Collision.s_incidentEdge;
Box2D.Collision.b2Collision.s_clipPoints1 = b2Collision.MakeClipPointVector();
Box2D.Collision.b2Collision.prototype.s_clipPoints1 = Box2D.Collision.b2Collision.s_clipPoints1;
Box2D.Collision.b2Collision.s_clipPoints2 = b2Collision.MakeClipPointVector();
Box2D.Collision.b2Collision.prototype.s_clipPoints2 = Box2D.Collision.b2Collision.s_clipPoints2;
Box2D.Collision.b2Collision.s_edgeAO = new Vector_a2j_Number(1);
Box2D.Collision.b2Collision.prototype.s_edgeAO = Box2D.Collision.b2Collision.s_edgeAO;
Box2D.Collision.b2Collision.s_edgeBO = new Vector_a2j_Number(1);
Box2D.Collision.b2Collision.prototype.s_edgeBO = Box2D.Collision.b2Collision.s_edgeBO;
Box2D.Collision.b2Collision.s_localTangent = new b2Vec2();
Box2D.Collision.b2Collision.prototype.s_localTangent = Box2D.Collision.b2Collision.s_localTangent;
Box2D.Collision.b2Collision.s_localNormal = new b2Vec2();
Box2D.Collision.b2Collision.prototype.s_localNormal = Box2D.Collision.b2Collision.s_localNormal;
Box2D.Collision.b2Collision.s_planePoint = new b2Vec2();
Box2D.Collision.b2Collision.prototype.s_planePoint = Box2D.Collision.b2Collision.s_planePoint;
Box2D.Collision.b2Collision.s_normal = new b2Vec2();
Box2D.Collision.b2Collision.prototype.s_normal = Box2D.Collision.b2Collision.s_normal;
Box2D.Collision.b2Collision.s_tangent = new b2Vec2();
Box2D.Collision.b2Collision.prototype.s_tangent = Box2D.Collision.b2Collision.s_tangent;
Box2D.Collision.b2Collision.s_tangent2 = new b2Vec2();
Box2D.Collision.b2Collision.prototype.s_tangent2 = Box2D.Collision.b2Collision.s_tangent2;
Box2D.Collision.b2Collision.s_v11 = new b2Vec2();
Box2D.Collision.b2Collision.prototype.s_v11 = Box2D.Collision.b2Collision.s_v11;
Box2D.Collision.b2Collision.s_v12 = new b2Vec2();
Box2D.Collision.b2Collision.prototype.s_v12 = Box2D.Collision.b2Collision.s_v12;
Box2D.Collision.b2Collision.b2CollidePolyTempVec = new b2Vec2();
Box2D.Collision.b2Collision.prototype.b2CollidePolyTempVec = Box2D.Collision.b2Collision.b2CollidePolyTempVec;
Box2D.Collision.b2Collision.b2_nullFeature = 0x000000ff;
Box2D.Collision.b2Collision.prototype.b2_nullFeature = Box2D.Collision.b2Collision.b2_nullFeature;
});
b2ContactID.b2ContactID = function () {
this.features = new Features();
};
b2ContactID.prototype.b2ContactID = function () {
this.features._m_id = this;
}
b2ContactID.prototype.Set = function (id) {
this.key = id._key;
}
b2ContactID.prototype.Copy = function () {
var id = new b2ContactID();
id.key = this.key;
return id;
}
b2ContactID.prototype.__defineGetter__('key', function () {
return this._key;
});
b2ContactID.prototype.__defineSetter__('key', function (value) {
if (value === undefined) value = 0;
this._key = value;
this.features._referenceEdge = this._key & 0x000000ff;
this.features._incidentEdge = ((this._key & 0x0000ff00) >> 8) & 0x000000ff;
this.features._incidentVertex = ((this._key & 0x00ff0000) >> 16) & 0x000000ff;
this.features._flip = ((this._key & 0xff000000) >> 24) & 0x000000ff;
});
b2ContactPoint.b2ContactPoint = function () {
this.position = new b2Vec2();
this.velocity = new b2Vec2();
this.normal = new b2Vec2();
this.id = new b2ContactID();
};
b2Distance.b2Distance = function () {};
b2Distance.prototype.Distance = function (output, cache, input) {
++b2Distance.b2_gjkCalls;
var proxyA = input.proxyA;
var proxyB = input.proxyB;
var transformA = input.transformA;
var transformB = input.transformB;
var simplex = b2Distance.s_simplex;
simplex.ReadCache(cache, proxyA, transformA, proxyB, transformB);
var vertices = simplex.m_vertices;
var k_maxIters = 20;
var saveA = b2Distance.s_saveA;
var saveB = b2Distance.s_saveB;
var saveCount = 0;
var closestPoint = simplex.GetClosestPoint();
var distanceSqr1 = closestPoint.LengthSquared();
var distanceSqr2 = distanceSqr1;
var i = 0;
var p;
var iter = 0;
while (iter < k_maxIters) {
saveCount = simplex.m_count;
for (i = 0;
i < saveCount; i++) {
saveA[i] = vertices[i].indexA;
saveB[i] = vertices[i].indexB;
}
switch (simplex.m_count) {
case 1:
break;
case 2:
simplex.Solve2();
break;
case 3:
simplex.Solve3();
break;
default:
b2Settings.b2Assert(false);
}
if (simplex.m_count == 3) {
break;
}
p = simplex.GetClosestPoint();
distanceSqr2 = p.LengthSquared();
if (distanceSqr2 > distanceSqr1) {}
distanceSqr1 = distanceSqr2;
var d = simplex.GetSearchDirection();
if (d.LengthSquared() < Number.MIN_VALUE * Number.MIN_VALUE) {
break;
}
var vertex = vertices[simplex.m_count];
vertex.indexA = proxyA.GetSupport(b2Math.MulTMV(transformA.R, d.GetNegative()));
vertex.wA = b2Math.MulX(transformA, proxyA.GetVertex(vertex.indexA));
vertex.indexB = proxyB.GetSupport(b2Math.MulTMV(transformB.R, d));
vertex.wB = b2Math.MulX(transformB, proxyB.GetVertex(vertex.indexB));
vertex.w = b2Math.SubtractVV(vertex.wB, vertex.wA);
++iter;
++b2Distance.b2_gjkIters;
var duplicate = false;
for (i = 0;
i < saveCount; i++) {
if (vertex.indexA == saveA[i] && vertex.indexB == saveB[i]) {
duplicate = true;
break;
}
}
if (duplicate) {
break;
}++simplex.m_count;
}
b2Distance.b2_gjkMaxIters = b2Math.Max(b2Distance.b2_gjkMaxIters, iter);
simplex.GetWitnessPoints(output.pointA, output.pointB);
output.distance = b2Math.SubtractVV(output.pointA, output.pointB).Length();
output.iterations = iter;
simplex.WriteCache(cache);
if (input.useRadii) {
var rA = proxyA.m_radius;
var rB = proxyB.m_radius;
if (output.distance > rA + rB && output.distance > Number.MIN_VALUE) {
output.distance -= rA + rB;
var normal = b2Math.SubtractVV(output.pointB, output.pointA);
normal.Normalize();
output.pointA.x += rA * normal.x;
output.pointA.y += rA * normal.y;
output.pointB.x -= rB * normal.x;
output.pointB.y -= rB * normal.y;
}
else {
p = new b2Vec2();
p.x = .5 * (output.pointA.x + output.pointB.x);
p.y = .5 * (output.pointA.y + output.pointB.y);
output.pointA.x = output.pointB.x = p.x;
output.pointA.y = output.pointB.y = p.y;
output.distance = 0.0;
}
}
}
b2Distance.Distance = b2Distance.prototype.Distance;
_A2J_postDefs.push(function () {
Box2D.Collision.b2Distance.s_simplex = new b2Simplex();
Box2D.Collision.b2Distance.prototype.s_simplex = Box2D.Collision.b2Distance.s_simplex;
Box2D.Collision.b2Distance.s_saveA = new Vector_a2j_Number(3);
Box2D.Collision.b2Distance.prototype.s_saveA = Box2D.Collision.b2Distance.s_saveA;
Box2D.Collision.b2Distance.s_saveB = new Vector_a2j_Number(3);
Box2D.Collision.b2Distance.prototype.s_saveB = Box2D.Collision.b2Distance.s_saveB;
});
b2DistanceInput.b2DistanceInput = function () {};
b2DistanceOutput.b2DistanceOutput = function () {
this.pointA = new b2Vec2();
this.pointB = new b2Vec2();
};
b2DistanceProxy.b2DistanceProxy = function () {};
b2DistanceProxy.prototype.Set = function (shape) {
switch (shape.GetType()) {
case b2Shape.e_circleShape:
{
var circle = (shape instanceof b2CircleShape ? shape : null);
this.m_vertices = new Vector(1, true);
this.m_vertices[0] = circle.m_p;
this.m_count = 1;
this.m_radius = circle.m_radius;
}
break;
case b2Shape.e_polygonShape:
{
var polygon = (shape instanceof b2PolygonShape ? shape : null);
this.m_vertices = polygon.m_vertices;
this.m_count = polygon.m_vertexCount;
this.m_radius = polygon.m_radius;
}
break;
default:
b2Settings.b2Assert(false);
}
}
b2DistanceProxy.prototype.GetSupport = function (d) {
var bestIndex = 0;
var bestValue = this.m_vertices[0].x * d.x + this.m_vertices[0].y * d.y;
for (var i = 1; i < this.m_count; ++i) {
var value = this.m_vertices[i].x * d.x + this.m_vertices[i].y * d.y;
if (value > bestValue) {
bestIndex = i;
bestValue = value;
}
}
return bestIndex;
}
b2DistanceProxy.prototype.GetSupportVertex = function (d) {
var bestIndex = 0;
var bestValue = this.m_vertices[0].x * d.x + this.m_vertices[0].y * d.y;
for (var i = 1; i < this.m_count; ++i) {
var value = this.m_vertices[i].x * d.x + this.m_vertices[i].y * d.y;
if (value > bestValue) {
bestIndex = i;
bestValue = value;
}
}
return this.m_vertices[bestIndex];
}
b2DistanceProxy.prototype.GetVertexCount = function () {
return this.m_count;
}
b2DistanceProxy.prototype.GetVertex = function (index) {
if (index === undefined) index = 0;
b2Settings.b2Assert(0 <= index && index < this.m_count);
return this.m_vertices[index];
}
b2DynamicTree.b2DynamicTree = function () {};
b2DynamicTree.prototype.b2DynamicTree = function () {
this.m_root = null;
this.m_freeList = null;
this.m_path = 0;
this.m_insertionCount = 0;
}
b2DynamicTree.prototype.CreateProxy = function (aabb, userData) {
var node = this.AllocateNode();
var extendX = b2Settings.b2_aabbExtension;
var extendY = b2Settings.b2_aabbExtension;
node.aabb.lowerBound.x = aabb.lowerBound.x - extendX;
node.aabb.lowerBound.y = aabb.lowerBound.y - extendY;
node.aabb.upperBound.x = aabb.upperBound.x + extendX;
node.aabb.upperBound.y = aabb.upperBound.y + extendY;
node.userData = userData;
this.InsertLeaf(node);
return node;
}
b2DynamicTree.prototype.DestroyProxy = function (proxy) {
this.RemoveLeaf(proxy);
this.FreeNode(proxy);
}
b2DynamicTree.prototype.MoveProxy = function (proxy, aabb, displacement) {
b2Settings.b2Assert(proxy.IsLeaf());
if (proxy.aabb.Contains(aabb)) {
return false;
}
this.RemoveLeaf(proxy);
var extendX = b2Settings.b2_aabbExtension + b2Settings.b2_aabbMultiplier * (displacement.x > 0 ? displacement.x : (-displacement.x));
var extendY = b2Settings.b2_aabbExtension + b2Settings.b2_aabbMultiplier * (displacement.y > 0 ? displacement.y : (-displacement.y));
proxy.aabb.lowerBound.x = aabb.lowerBound.x - extendX;
proxy.aabb.lowerBound.y = aabb.lowerBound.y - extendY;
proxy.aabb.upperBound.x = aabb.upperBound.x + extendX;
proxy.aabb.upperBound.y = aabb.upperBound.y + extendY;
this.InsertLeaf(proxy);
return true;
}
b2DynamicTree.prototype.Rebalance = function (iterations) {
if (iterations === undefined) iterations = 0;
if (this.m_root == null) return;
for (var i = 0; i < iterations; i++) {
var node = this.m_root;
var bit = 0;
while (node.IsLeaf() == false) {
node = (this.m_path >> bit) & 1 ? node.child2 : node.child1;
bit = (bit + 1) & 31;
}++this.m_path;
this.RemoveLeaf(node);
this.InsertLeaf(node);
}
}
b2DynamicTree.prototype.GetFatAABB = function (proxy) {
return proxy.aabb;
}
b2DynamicTree.prototype.GetUserData = function (proxy) {
return proxy.userData;
}
b2DynamicTree.prototype.Query = function (callback, aabb) {
if (this.m_root == null) return;
var stack = new Vector();
var count = 0;
stack[count++] = this.m_root;
while (count > 0) {
var node = stack[--count];
if (node.aabb.TestOverlap(aabb)) {
if (node.IsLeaf()) {
var proceed = callback(node);
if (!proceed) return;
}
else {
stack[count++] = node.child1;
stack[count++] = node.child2;
}
}
}
}
b2DynamicTree.prototype.RayCast = function (callback, input) {
if (this.m_root == null) return;
var p1 = input.p1;
var p2 = input.p2;
var r = b2Math.SubtractVV(p1, p2);
r.Normalize();
var v = b2Math.CrossFV(1.0, r);
var abs_v = b2Math.AbsV(v);
var maxFraction = input.maxFraction;
var segmentAABB = new b2AABB();
var tX = 0;
var tY = 0; {
tX = p1.x + maxFraction * (p2.x - p1.x);
tY = p1.y + maxFraction * (p2.y - p1.y);
segmentAABB.lowerBound.x = Math.min(p1.x, tX);
segmentAABB.lowerBound.y = Math.min(p1.y, tY);
segmentAABB.upperBound.x = Math.max(p1.x, tX);
segmentAABB.upperBound.y = Math.max(p1.y, tY);
}
var stack = new Vector();
var count = 0;
stack[count++] = this.m_root;
while (count > 0) {
var node = stack[--count];
if (node.aabb.TestOverlap(segmentAABB) == false) {
continue;
}
var c = node.aabb.GetCenter();
var h = node.aabb.GetExtents();
var separation = Math.abs(v.x * (p1.x - c.x) + v.y * (p1.y - c.y)) - abs_v.x * h.x - abs_v.y * h.y;
if (separation > 0.0) continue;
if (node.IsLeaf()) {
var subInput = new b2RayCastInput();
subInput.p1 = input.p1;
subInput.p2 = input.p2;
subInput.maxFraction = input.maxFraction;
maxFraction = callback(subInput, node);
if (maxFraction == 0.0) return;
if (maxFraction > 0.0) {
tX = p1.x + maxFraction * (p2.x - p1.x);
tY = p1.y + maxFraction * (p2.y - p1.y);
segmentAABB.lowerBound.x = Math.min(p1.x, tX);
segmentAABB.lowerBound.y = Math.min(p1.y, tY);
segmentAABB.upperBound.x = Math.max(p1.x, tX);
segmentAABB.upperBound.y = Math.max(p1.y, tY);
}
}
else {
stack[count++] = node.child1;
stack[count++] = node.child2;
}
}
}
b2DynamicTree.prototype.AllocateNode = function () {
if (this.m_freeList) {
var node = this.m_freeList;
this.m_freeList = node.parent;
node.parent = null;
node.child1 = null;
node.child2 = null;
return node;
}
return new b2DynamicTreeNode();
}
b2DynamicTree.prototype.FreeNode = function (node) {
node.parent = this.m_freeList;
this.m_freeList = node;
}
b2DynamicTree.prototype.InsertLeaf = function (leaf) {
++this.m_insertionCount;
if (this.m_root == null) {
this.m_root = leaf;
this.m_root.parent = null;
return;
}
var center = leaf.aabb.GetCenter();
var sibling = this.m_root;
if (sibling.IsLeaf() == false) {
do {
var child1 = sibling.child1;
var child2 = sibling.child2;
var norm1 = Math.abs((child1.aabb.lowerBound.x + child1.aabb.upperBound.x) / 2 - center.x) + Math.abs((child1.aabb.lowerBound.y + child1.aabb.upperBound.y) / 2 - center.y);
var norm2 = Math.abs((child2.aabb.lowerBound.x + child2.aabb.upperBound.x) / 2 - center.x) + Math.abs((child2.aabb.lowerBound.y + child2.aabb.upperBound.y) / 2 - center.y);
if (norm1 < norm2) {
sibling = child1;
}
else {
sibling = child2;
}
}
while (sibling.IsLeaf() == false)
}
var node1 = sibling.parent;
var node2 = this.AllocateNode();
node2.parent = node1;
node2.userData = null;
node2.aabb.Combine(leaf.aabb, sibling.aabb);
if (node1) {
if (sibling.parent.child1 == sibling) {
node1.child1 = node2;
}
else {
node1.child2 = node2;
}
node2.child1 = sibling;
node2.child2 = leaf;
sibling.parent = node2;
leaf.parent = node2;
do {
if (node1.aabb.Contains(node2.aabb)) break;
node1.aabb.Combine(node1.child1.aabb, node1.child2.aabb);
node2 = node1;
node1 = node1.parent;
}
while (node1)
}
else {
node2.child1 = sibling;
node2.child2 = leaf;
sibling.parent = node2;
leaf.parent = node2;
this.m_root = node2;
}
}
b2DynamicTree.prototype.RemoveLeaf = function (leaf) {
if (leaf == this.m_root) {
this.m_root = null;
return;
}
var node2 = leaf.parent;
var node1 = node2.parent;
var sibling;
if (node2.child1 == leaf) {
sibling = node2.child2;
}
else {
sibling = node2.child1;
}
if (node1) {
if (node1.child1 == node2) {
node1.child1 = sibling;
}
else {
node1.child2 = sibling;
}
sibling.parent = node1;
this.FreeNode(node2);
while (node1) {
var oldAABB = node1.aabb;
node1.aabb = b2AABB.Combine(node1.child1.aabb, node1.child2.aabb);
if (oldAABB.Contains(node1.aabb)) break;
node1 = node1.parent;
}
}
else {
this.m_root = sibling;
sibling.parent = null;
this.FreeNode(node2);
}
}
b2DynamicTreeBroadPhase.b2DynamicTreeBroadPhase = function () {
this.m_tree = new b2DynamicTree();
this.m_moveBuffer = new Vector();
this.m_pairBuffer = new Vector();
this.m_pairCount = 0;
};
b2DynamicTreeBroadPhase.prototype.CreateProxy = function (aabb, userData) {
var proxy = this.m_tree.CreateProxy(aabb, userData);
++this.m_proxyCount;
this.BufferMove(proxy);
return proxy;
}
b2DynamicTreeBroadPhase.prototype.DestroyProxy = function (proxy) {
this.UnBufferMove(proxy);
--this.m_proxyCount;
this.m_tree.DestroyProxy(proxy);
}
b2DynamicTreeBroadPhase.prototype.MoveProxy = function (proxy, aabb, displacement) {
var buffer = this.m_tree.MoveProxy(proxy, aabb, displacement);
if (buffer) {
this.BufferMove(proxy);
}
}
b2DynamicTreeBroadPhase.prototype.TestOverlap = function (proxyA, proxyB) {
var aabbA = this.m_tree.GetFatAABB(proxyA);
var aabbB = this.m_tree.GetFatAABB(proxyB);
return aabbA.TestOverlap(aabbB);
}
b2DynamicTreeBroadPhase.prototype.GetUserData = function (proxy) {
return this.m_tree.GetUserData(proxy);
}
b2DynamicTreeBroadPhase.prototype.GetFatAABB = function (proxy) {
return this.m_tree.GetFatAABB(proxy);
}
b2DynamicTreeBroadPhase.prototype.GetProxyCount = function () {
return this.m_proxyCount;
}
b2DynamicTreeBroadPhase.prototype.UpdatePairs = function (callback) {
var __this = this;
__this.m_pairCount = 0;
var queryProxy;
for (var each in __this.m_moveBuffer) {
queryProxy = __this.m_moveBuffer[each]; {
function QueryCallback(proxy) {
if (proxy == queryProxy) return true;
if (__this.m_pairCount == __this.m_pairBuffer.length) {
__this.m_pairBuffer[__this.m_pairCount] = new b2DynamicTreePair();
}
var pair = __this.m_pairBuffer[__this.m_pairCount];
pair.proxyA = proxy < queryProxy ? proxy : queryProxy;
pair.proxyB = proxy >= queryProxy ? proxy : queryProxy;++__this.m_pairCount;
return true;
};
var fatAABB = __this.m_tree.GetFatAABB(queryProxy);
__this.m_tree.Query(QueryCallback, fatAABB);
}
}
__this.m_moveBuffer.length = 0;
for (var i = 0; i < __this.m_pairCount;) {
var primaryPair = __this.m_pairBuffer[i];
var userDataA = __this.m_tree.GetUserData(primaryPair.proxyA);
var userDataB = __this.m_tree.GetUserData(primaryPair.proxyB);
callback(userDataA, userDataB);
++i;
while (i < __this.m_pairCount) {
var pair = __this.m_pairBuffer[i];
if (pair.proxyA != primaryPair.proxyA || pair.proxyB != primaryPair.proxyB) {
break;
}++i;
}
}
}
b2DynamicTreeBroadPhase.prototype.Query = function (callback, aabb) {
this.m_tree.Query(callback, aabb);
}
b2DynamicTreeBroadPhase.prototype.RayCast = function (callback, input) {
this.m_tree.RayCast(callback, input);
}
b2DynamicTreeBroadPhase.prototype.Validate = function () {}
b2DynamicTreeBroadPhase.prototype.Rebalance = function (iterations) {
if (iterations === undefined) iterations = 0;
this.m_tree.Rebalance(iterations);
}
b2DynamicTreeBroadPhase.prototype.BufferMove = function (proxy) {
this.m_moveBuffer[this.m_moveBuffer.length] = proxy;
}
b2DynamicTreeBroadPhase.prototype.UnBufferMove = function (proxy) {
var i = parseInt(this.m_moveBuffer.indexOf(proxy));
this.m_moveBuffer.splice(i, 1);
}
b2DynamicTreeBroadPhase.prototype.ComparePairs = function (pair1, pair2) {
return 0;
}
b2DynamicTreeBroadPhase.__implements = {};
b2DynamicTreeBroadPhase.__implements[IBroadPhase] = true;
b2DynamicTreeNode.b2DynamicTreeNode = function () {
this.aabb = new b2AABB();
};
b2DynamicTreeNode.prototype.IsLeaf = function () {
return this.child1 == null;
}
b2DynamicTreePair.b2DynamicTreePair = function () {};
b2Manifold.b2Manifold = function () {
this.m_pointCount = 0;
};
b2Manifold.prototype.b2Manifold = function () {
this.m_points = new Vector(b2Settings.b2_maxManifoldPoints);
for (var i = 0; i < b2Settings.b2_maxManifoldPoints; i++) {
this.m_points[i] = new b2ManifoldPoint();
}
this.m_localPlaneNormal = new b2Vec2();
this.m_localPoint = new b2Vec2();
}
b2Manifold.prototype.Reset = function () {
for (var i = 0; i < b2Settings.b2_maxManifoldPoints; i++) {
((this.m_points[i] instanceof b2ManifoldPoint ? this.m_points[i] : null)).Reset();
}
this.m_localPlaneNormal.SetZero();
this.m_localPoint.SetZero();
this.m_type = 0;
this.m_pointCount = 0;
}
b2Manifold.prototype.Set = function (m) {
this.m_pointCount = m.m_pointCount;
for (var i = 0; i < b2Settings.b2_maxManifoldPoints; i++) {
((this.m_points[i] instanceof b2ManifoldPoint ? this.m_points[i] : null)).Set(m.m_points[i]);
}
this.m_localPlaneNormal.SetV(m.m_localPlaneNormal);
this.m_localPoint.SetV(m.m_localPoint);
this.m_type = m.m_type;
}
b2Manifold.prototype.Copy = function () {
var copy = new b2Manifold();
copy.Set(this);
return copy;
}
_A2J_postDefs.push(function () {
Box2D.Collision.b2Manifold.e_circles = 0x0001;
Box2D.Collision.b2Manifold.prototype.e_circles = Box2D.Collision.b2Manifold.e_circles;
Box2D.Collision.b2Manifold.e_faceA = 0x0002;
Box2D.Collision.b2Manifold.prototype.e_faceA = Box2D.Collision.b2Manifold.e_faceA;
Box2D.Collision.b2Manifold.e_faceB = 0x0004;
Box2D.Collision.b2Manifold.prototype.e_faceB = Box2D.Collision.b2Manifold.e_faceB;
});
b2ManifoldPoint.b2ManifoldPoint = function () {
this.m_localPoint = new b2Vec2();
this.m_id = new b2ContactID();
};
b2ManifoldPoint.prototype.b2ManifoldPoint = function () {
this.Reset();
}
b2ManifoldPoint.prototype.Reset = function () {
this.m_localPoint.SetZero();
this.m_normalImpulse = 0.0;
this.m_tangentImpulse = 0.0;
this.m_id.key = 0;
}
b2ManifoldPoint.prototype.Set = function (m) {
this.m_localPoint.SetV(m.m_localPoint);
this.m_normalImpulse = m.m_normalImpulse;
this.m_tangentImpulse = m.m_tangentImpulse;
this.m_id.Set(m.m_id);
}
b2OBB.b2OBB = function () {
this.R = new b2Mat22();
this.center = new b2Vec2();
this.extents = new b2Vec2();
};
b2Pair.b2Pair = function () {
this.userData = null;
};
b2Pair.prototype.SetBuffered = function () {
this.status |= b2Pair.e_pairBuffered;
}
b2Pair.prototype.ClearBuffered = function () {
this.status &= ~b2Pair.e_pairBuffered;
}
b2Pair.prototype.IsBuffered = function () {
return (this.status & b2Pair.e_pairBuffered) == b2Pair.e_pairBuffered;
}
b2Pair.prototype.SetRemoved = function () {
this.status |= b2Pair.e_pairRemoved;
}
b2Pair.prototype.ClearRemoved = function () {
this.status &= ~b2Pair.e_pairRemoved;
}
b2Pair.prototype.IsRemoved = function () {
return (this.status & b2Pair.e_pairRemoved) == b2Pair.e_pairRemoved;
}
b2Pair.prototype.SetFinal = function () {
this.status |= b2Pair.e_pairFinal;
}
b2Pair.prototype.IsFinal = function () {
return (this.status & b2Pair.e_pairFinal) == b2Pair.e_pairFinal;
}
_A2J_postDefs.push(function () {
Box2D.Collision.b2Pair.b2_nullProxy = parseInt(b2Settings.USHRT_MAX);
Box2D.Collision.b2Pair.prototype.b2_nullProxy = Box2D.Collision.b2Pair.b2_nullProxy;
Box2D.Collision.b2Pair.e_pairBuffered = 0x0001;
Box2D.Collision.b2Pair.prototype.e_pairBuffered = Box2D.Collision.b2Pair.e_pairBuffered;
Box2D.Collision.b2Pair.e_pairRemoved = 0x0002;
Box2D.Collision.b2Pair.prototype.e_pairRemoved = Box2D.Collision.b2Pair.e_pairRemoved;
Box2D.Collision.b2Pair.e_pairFinal = 0x0004;
Box2D.Collision.b2Pair.prototype.e_pairFinal = Box2D.Collision.b2Pair.e_pairFinal;
});
b2PairManager.b2PairManager = function () {};
b2PairManager.prototype.b2PairManager = function () {
this.m_pairs = new Array();
this.m_pairBuffer = new Array();
this.m_pairCount = 0;
this.m_pairBufferCount = 0;
this.m_freePair = null;
}
b2PairManager.prototype.Initialize = function (broadPhase) {
this.m_broadPhase = broadPhase;
}
b2PairManager.prototype.AddBufferedPair = function (proxy1, proxy2) {
var pair = this.AddPair(proxy1, proxy2);
if (pair.IsBuffered() == false) {
pair.SetBuffered();
this.m_pairBuffer[this.m_pairBufferCount] = pair;
++this.m_pairBufferCount;
}
pair.ClearRemoved();
if (b2BroadPhase.s_validate) {
this.ValidateBuffer();
}
}
b2PairManager.prototype.RemoveBufferedPair = function (proxy1, proxy2) {
var pair = this.Find(proxy1, proxy2);
if (pair == null) {
return;
}
if (pair.IsBuffered() == false) {
pair.SetBuffered();
this.m_pairBuffer[this.m_pairBufferCount] = pair;
++this.m_pairBufferCount;
}
pair.SetRemoved();
if (b2BroadPhase.s_validate) {
this.ValidateBuffer();
}
}
b2PairManager.prototype.Commit = function (callback) {
var i = 0;
var removeCount = 0;
for (i = 0;
i < this.m_pairBufferCount; ++i) {
var pair = this.m_pairBuffer[i];
pair.ClearBuffered();
var proxy1 = pair.proxy1;
var proxy2 = pair.proxy2;
if (pair.IsRemoved()) {} else {
if (pair.IsFinal() == false) {
callback(proxy1.userData, proxy2.userData);
}
}
}
this.m_pairBufferCount = 0;
if (b2BroadPhase.s_validate) {
this.ValidateTable();
}
}
b2PairManager.prototype.AddPair = function (proxy1, proxy2) {
var pair = proxy1.pairs[proxy2];
if (pair != null) return pair;
if (this.m_freePair == null) {
this.m_freePair = new b2Pair();
this.m_pairs.push(this.m_freePair);
}
pair = this.m_freePair;
this.m_freePair = pair.next;
pair.proxy1 = proxy1;
pair.proxy2 = proxy2;
pair.status = 0;
pair.userData = null;
pair.next = null;
proxy1.pairs[proxy2] = pair;
proxy2.pairs[proxy1] = pair;
++this.m_pairCount;
return pair;
}
b2PairManager.prototype.RemovePair = function (proxy1, proxy2) {
var pair = proxy1.pairs[proxy2];
if (pair == null) {
return null;
}
var userData = pair.userData;
delete proxy1.pairs[proxy2];
delete proxy2.pairs[proxy1];
pair.next = this.m_freePair;
pair.proxy1 = null;
pair.proxy2 = null;
pair.userData = null;
pair.status = 0;
this.m_freePair = pair;
--this.m_pairCount;
return userData;
}
b2PairManager.prototype.Find = function (proxy1, proxy2) {
return proxy1.pairs[proxy2];
}
b2PairManager.prototype.ValidateBuffer = function () {}
b2PairManager.prototype.ValidateTable = function () {}
b2Point.b2Point = function () {
this.p = new b2Vec2();
};
b2Point.prototype.Support = function (xf, vX, vY) {
if (vX === undefined) vX = 0;
if (vY === undefined) vY = 0;
return this.p;
}
b2Point.prototype.GetFirstVertex = function (xf) {
return this.p;
}
b2Proxy.b2Proxy = function () {
this.lowerBounds = new Vector_a2j_Number(2);
this.upperBounds = new Vector_a2j_Number(2);
this.pairs = new Dictionary();
this.userData = null;
};
b2Proxy.prototype.IsValid = function () {
return this.overlapCount != b2BroadPhase.b2_invalid;
}
b2RayCastInput.b2RayCastInput = function () {
this.p1 = new b2Vec2();
this.p2 = new b2Vec2();
};
b2RayCastInput.prototype.b2RayCastInput = function (p1, p2, maxFraction) {
if (p1 === undefined) p1 = null;
if (p2 === undefined) p2 = null;
if (maxFraction === undefined) maxFraction = 1;
if (p1) this.p1.SetV(p1);
if (p2) this.p2.SetV(p2);
this.maxFraction = maxFraction;
}
b2RayCastOutput.b2RayCastOutput = function () {
this.normal = new b2Vec2();
};
b2Segment.b2Segment = function () {
this.p1 = new b2Vec2();
this.p2 = new b2Vec2();
};
b2Segment.prototype.TestSegment = function (lambda, normal, segment, maxLambda) {
if (maxLambda === undefined) maxLambda = 0;
var s = segment.p1;
var rX = segment.p2.x - s.x;
var rY = segment.p2.y - s.y;
var dX = this.p2.x - this.p1.x;
var dY = this.p2.y - this.p1.y;
var nX = dY;
var nY = (-dX);
var k_slop = 100.0 * Number.MIN_VALUE;
var denom = (-(rX * nX + rY * nY));
if (denom > k_slop) {
var bX = s.x - this.p1.x;
var bY = s.y - this.p1.y;
var a = (bX * nX + bY * nY);
if (0.0 <= a && a <= maxLambda * denom) {
var mu2 = (-rX * bY) + rY * bX;
if ((-k_slop * denom) <= mu2 && mu2 <= denom * (1.0 + k_slop)) {
a /= denom;
var nLen = Math.sqrt(nX * nX + nY * nY);
nX /= nLen;
nY /= nLen;
lambda[0] = a;
normal.Set(nX, nY);
return true;
}
}
}
return false;
}
b2Segment.prototype.Extend = function (aabb) {
this.ExtendForward(aabb);
this.ExtendBackward(aabb);
}
b2Segment.prototype.ExtendForward = function (aabb) {
var dX = this.p2.x - this.p1.x;
var dY = this.p2.y - this.p1.y;
var lambda = Math.min(dX > 0 ? (aabb.upperBound.x - this.p1.x) / dX : dX < 0 ? (aabb.lowerBound.x - this.p1.x) / dX : Number.POSITIVE_INFINITY,
dY > 0 ? (aabb.upperBound.y - this.p1.y) / dY : dY < 0 ? (aabb.lowerBound.y - this.p1.y) / dY : Number.POSITIVE_INFINITY);
this.p2.x = this.p1.x + dX * lambda;
this.p2.y = this.p1.y + dY * lambda;
}
b2Segment.prototype.ExtendBackward = function (aabb) {
var dX = (-this.p2.x) + this.p1.x;
var dY = (-this.p2.y) + this.p1.y;
var lambda = Math.min(dX > 0 ? (aabb.upperBound.x - this.p2.x) / dX : dX < 0 ? (aabb.lowerBound.x - this.p2.x) / dX : Number.POSITIVE_INFINITY,
dY > 0 ? (aabb.upperBound.y - this.p2.y) / dY : dY < 0 ? (aabb.lowerBound.y - this.p2.y) / dY : Number.POSITIVE_INFINITY);
this.p1.x = this.p2.x + dX * lambda;
this.p1.y = this.p2.y + dY * lambda;
}
b2SeparationFunction.b2SeparationFunction = function () {
this.m_localPoint = new b2Vec2();
this.m_axis = new b2Vec2();
};
b2SeparationFunction.prototype.Initialize = function (cache, proxyA, transformA, proxyB, transformB) {
this.m_proxyA = proxyA;
this.m_proxyB = proxyB;
var count = parseInt(cache.count);
b2Settings.b2Assert(0 < count && count < 3);
var localPointA;
var localPointA1;
var localPointA2;
var localPointB;
var localPointB1;
var localPointB2;
var pointAX = 0;
var pointAY = 0;
var pointBX = 0;
var pointBY = 0;
var normalX = 0;
var normalY = 0;
var tMat;
var tVec;
var s = 0;
var sgn = 0;
if (count == 1) {
this.m_type = b2SeparationFunction.e_points;
localPointA = this.m_proxyA.GetVertex(cache.indexA[0]);
localPointB = this.m_proxyB.GetVertex(cache.indexB[0]);
tVec = localPointA;
tMat = transformA.R;
pointAX = transformA.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
pointAY = transformA.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
tVec = localPointB;
tMat = transformB.R;
pointBX = transformB.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
pointBY = transformB.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
this.m_axis.x = pointBX - pointAX;
this.m_axis.y = pointBY - pointAY;
this.m_axis.Normalize();
}
else if (cache.indexB[0] == cache.indexB[1]) {
this.m_type = b2SeparationFunction.e_faceA;
localPointA1 = this.m_proxyA.GetVertex(cache.indexA[0]);
localPointA2 = this.m_proxyA.GetVertex(cache.indexA[1]);
localPointB = this.m_proxyB.GetVertex(cache.indexB[0]);
this.m_localPoint.x = 0.5 * (localPointA1.x + localPointA2.x);
this.m_localPoint.y = 0.5 * (localPointA1.y + localPointA2.y);
this.m_axis = b2Math.CrossVF(b2Math.SubtractVV(localPointA2, localPointA1), 1.0);
this.m_axis.Normalize();
tVec = this.m_axis;
tMat = transformA.R;
normalX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
normalY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
tVec = this.m_localPoint;
tMat = transformA.R;
pointAX = transformA.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
pointAY = transformA.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
tVec = localPointB;
tMat = transformB.R;
pointBX = transformB.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
pointBY = transformB.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
s = (pointBX - pointAX) * normalX + (pointBY - pointAY) * normalY;
if (s < 0.0) {
this.m_axis.NegativeSelf();
}
}
else if (cache.indexA[0] == cache.indexA[0]) {
this.m_type = b2SeparationFunction.e_faceB;
localPointB1 = this.m_proxyB.GetVertex(cache.indexB[0]);
localPointB2 = this.m_proxyB.GetVertex(cache.indexB[1]);
localPointA = this.m_proxyA.GetVertex(cache.indexA[0]);
this.m_localPoint.x = 0.5 * (localPointB1.x + localPointB2.x);
this.m_localPoint.y = 0.5 * (localPointB1.y + localPointB2.y);
this.m_axis = b2Math.CrossVF(b2Math.SubtractVV(localPointB2, localPointB1), 1.0);
this.m_axis.Normalize();
tVec = this.m_axis;
tMat = transformB.R;
normalX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
normalY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
tVec = this.m_localPoint;
tMat = transformB.R;
pointBX = transformB.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
pointBY = transformB.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
tVec = localPointA;
tMat = transformA.R;
pointAX = transformA.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
pointAY = transformA.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
s = (pointAX - pointBX) * normalX + (pointAY - pointBY) * normalY;
if (s < 0.0) {
this.m_axis.NegativeSelf();
}
}
else {
localPointA1 = this.m_proxyA.GetVertex(cache.indexA[0]);
localPointA2 = this.m_proxyA.GetVertex(cache.indexA[1]);
localPointB1 = this.m_proxyB.GetVertex(cache.indexB[0]);
localPointB2 = this.m_proxyB.GetVertex(cache.indexB[1]);
var pA = b2Math.MulX(transformA, localPointA);
var dA = b2Math.MulMV(transformA.R, b2Math.SubtractVV(localPointA2, localPointA1));
var pB = b2Math.MulX(transformB, localPointB);
var dB = b2Math.MulMV(transformB.R, b2Math.SubtractVV(localPointB2, localPointB1));
var a = dA.x * dA.x + dA.y * dA.y;
var e = dB.x * dB.x + dB.y * dB.y;
var r = b2Math.SubtractVV(dB, dA);
var c = dA.x * r.x + dA.y * r.y;
var f = dB.x * r.x + dB.y * r.y;
var b = dA.x * dB.x + dA.y * dB.y;
var denom = a * e - b * b;
s = 0.0;
if (denom != 0.0) {
s = b2Math.Clamp((b * f - c * e) / denom, 0.0, 1.0);
}
var t = (b * s + f) / e;
if (t < 0.0) {
t = 0.0;
s = b2Math.Clamp((b - c) / a, 0.0, 1.0);
}
localPointA = new b2Vec2();
localPointA.x = localPointA1.x + s * (localPointA2.x - localPointA1.x);
localPointA.y = localPointA1.y + s * (localPointA2.y - localPointA1.y);
localPointB = new b2Vec2();
localPointB.x = localPointB1.x + s * (localPointB2.x - localPointB1.x);
localPointB.y = localPointB1.y + s * (localPointB2.y - localPointB1.y);
if (s == 0.0 || s == 1.0) {
this.m_type = b2SeparationFunction.e_faceB;
this.m_axis = b2Math.CrossVF(b2Math.SubtractVV(localPointB2, localPointB1), 1.0);
this.m_axis.Normalize();
this.m_localPoint = localPointB;
tVec = this.m_axis;
tMat = transformB.R;
normalX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
normalY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
tVec = this.m_localPoint;
tMat = transformB.R;
pointBX = transformB.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
pointBY = transformB.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
tVec = localPointA;
tMat = transformA.R;
pointAX = transformA.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
pointAY = transformA.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
sgn = (pointAX - pointBX) * normalX + (pointAY - pointBY) * normalY;
if (s < 0.0) {
this.m_axis.NegativeSelf();
}
}
else {
this.m_type = b2SeparationFunction.e_faceA;
this.m_axis = b2Math.CrossVF(b2Math.SubtractVV(localPointA2, localPointA1), 1.0);
this.m_localPoint = localPointA;
tVec = this.m_axis;
tMat = transformA.R;
normalX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
normalY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
tVec = this.m_localPoint;
tMat = transformA.R;
pointAX = transformA.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
pointAY = transformA.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
tVec = localPointB;
tMat = transformB.R;
pointBX = transformB.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
pointBY = transformB.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
sgn = (pointBX - pointAX) * normalX + (pointBY - pointAY) * normalY;
if (s < 0.0) {
this.m_axis.NegativeSelf();
}
}
}
}
b2SeparationFunction.prototype.Evaluate = function (transformA, transformB) {
var axisA;
var axisB;
var localPointA;
var localPointB;
var pointA;
var pointB;
var seperation = 0;
var normal;
switch (this.m_type) {
case b2SeparationFunction.e_points:
{
axisA = b2Math.MulTMV(transformA.R, this.m_axis);
axisB = b2Math.MulTMV(transformB.R, this.m_axis.GetNegative());
localPointA = this.m_proxyA.GetSupportVertex(axisA);
localPointB = this.m_proxyB.GetSupportVertex(axisB);
pointA = b2Math.MulX(transformA, localPointA);
pointB = b2Math.MulX(transformB, localPointB);
seperation = (pointB.x - pointA.x) * this.m_axis.x + (pointB.y - pointA.y) * this.m_axis.y;
return seperation;
}
case b2SeparationFunction.e_faceA:
{
normal = b2Math.MulMV(transformA.R, this.m_axis);
pointA = b2Math.MulX(transformA, this.m_localPoint);
axisB = b2Math.MulTMV(transformB.R, normal.GetNegative());
localPointB = this.m_proxyB.GetSupportVertex(axisB);
pointB = b2Math.MulX(transformB, localPointB);
seperation = (pointB.x - pointA.x) * normal.x + (pointB.y - pointA.y) * normal.y;
return seperation;
}
case b2SeparationFunction.e_faceB:
{
normal = b2Math.MulMV(transformB.R, this.m_axis);
pointB = b2Math.MulX(transformB, this.m_localPoint);
axisA = b2Math.MulTMV(transformA.R, normal.GetNegative());
localPointA = this.m_proxyA.GetSupportVertex(axisA);
pointA = b2Math.MulX(transformA, localPointA);
seperation = (pointA.x - pointB.x) * normal.x + (pointA.y - pointB.y) * normal.y;
return seperation;
}
default:
b2Settings.b2Assert(false);
return 0.0;
}
}
_A2J_postDefs.push(function () {
Box2D.Collision.b2SeparationFunction.e_points = 0x01;
Box2D.Collision.b2SeparationFunction.prototype.e_points = Box2D.Collision.b2SeparationFunction.e_points;
Box2D.Collision.b2SeparationFunction.e_faceA = 0x02;
Box2D.Collision.b2SeparationFunction.prototype.e_faceA = Box2D.Collision.b2SeparationFunction.e_faceA;
Box2D.Collision.b2SeparationFunction.e_faceB = 0x04;
Box2D.Collision.b2SeparationFunction.prototype.e_faceB = Box2D.Collision.b2SeparationFunction.e_faceB;
});
b2Simplex.b2Simplex = function () {
this.m_v1 = new b2SimplexVertex();
this.m_v2 = new b2SimplexVertex();
this.m_v3 = new b2SimplexVertex();
this.m_vertices = new Vector(3);
};
b2Simplex.prototype.b2Simplex = function () {
this.m_vertices[0] = this.m_v1;
this.m_vertices[1] = this.m_v2;
this.m_vertices[2] = this.m_v3;
}
b2Simplex.prototype.ReadCache = function (cache, proxyA, transformA, proxyB, transformB) {
b2Settings.b2Assert(0 <= cache.count && cache.count <= 3);
var wALocal;
var wBLocal;
this.m_count = cache.count;
var vertices = this.m_vertices;
for (var i = 0; i < this.m_count; i++) {
var v = vertices[i];
v.indexA = cache.indexA[i];
v.indexB = cache.indexB[i];
wALocal = proxyA.GetVertex(v.indexA);
wBLocal = proxyB.GetVertex(v.indexB);
v.wA = b2Math.MulX(transformA, wALocal);
v.wB = b2Math.MulX(transformB, wBLocal);
v.w = b2Math.SubtractVV(v.wB, v.wA);
v.a = 0;
}
if (this.m_count > 1) {
var metric1 = cache.metric;
var metric2 = this.GetMetric();
if (metric2 < .5 * metric1 || 2.0 * metric1 < metric2 || metric2 < Number.MIN_VALUE) {
this.m_count = 0;
}
}
if (this.m_count == 0) {
v = vertices[0];
v.indexA = 0;
v.indexB = 0;
wALocal = proxyA.GetVertex(0);
wBLocal = proxyB.GetVertex(0);
v.wA = b2Math.MulX(transformA, wALocal);
v.wB = b2Math.MulX(transformB, wBLocal);
v.w = b2Math.SubtractVV(v.wB, v.wA);
this.m_count = 1;
}
}
b2Simplex.prototype.WriteCache = function (cache) {
cache.metric = this.GetMetric();
cache.count = a2j.parseUInt(this.m_count);
var vertices = this.m_vertices;
for (var i = 0; i < this.m_count; i++) {
cache.indexA[i] = a2j.parseUInt(vertices[i].indexA);
cache.indexB[i] = a2j.parseUInt(vertices[i].indexB);
}
}
b2Simplex.prototype.GetSearchDirection = function () {
switch (this.m_count) {
case 1:
return this.m_v1.w.GetNegative();
case 2:
{
var e12 = b2Math.SubtractVV(this.m_v2.w, this.m_v1.w);
var sgn = b2Math.CrossVV(e12, this.m_v1.w.GetNegative());
if (sgn > 0.0) {
return b2Math.CrossFV(1.0, e12);
}
else {
return b2Math.CrossVF(e12, 1.0);
}
}
default:
b2Settings.b2Assert(false);
return new b2Vec2();
}
}
b2Simplex.prototype.GetClosestPoint = function () {
switch (this.m_count) {
case 0:
b2Settings.b2Assert(false);
return new b2Vec2();
case 1:
return this.m_v1.w;
case 2:
return new b2Vec2(this.m_v1.a * this.m_v1.w.x + this.m_v2.a * this.m_v2.w.x, this.m_v1.a * this.m_v1.w.y + this.m_v2.a * this.m_v2.w.y);
default:
b2Settings.b2Assert(false);
return new b2Vec2();
}
}
b2Simplex.prototype.GetWitnessPoints = function (pA, pB) {
switch (this.m_count) {
case 0:
b2Settings.b2Assert(false);
break;
case 1:
pA.SetV(this.m_v1.wA);
pB.SetV(this.m_v1.wB);
break;
case 2:
pA.x = this.m_v1.a * this.m_v1.wA.x + this.m_v2.a * this.m_v2.wA.x;
pA.y = this.m_v1.a * this.m_v1.wA.y + this.m_v2.a * this.m_v2.wA.y;
pB.x = this.m_v1.a * this.m_v1.wB.x + this.m_v2.a * this.m_v2.wB.x;
pB.y = this.m_v1.a * this.m_v1.wB.y + this.m_v2.a * this.m_v2.wB.y;
break;
case 3:
pB.x = pA.x = this.m_v1.a * this.m_v1.wA.x + this.m_v2.a * this.m_v2.wA.x + this.m_v3.a * this.m_v3.wA.x;
pB.y = pA.y = this.m_v1.a * this.m_v1.wA.y + this.m_v2.a * this.m_v2.wA.y + this.m_v3.a * this.m_v3.wA.y;
break;
default:
b2Settings.b2Assert(false);
break;
}
}
b2Simplex.prototype.GetMetric = function () {
switch (this.m_count) {
case 0:
b2Settings.b2Assert(false);
return 0.0;
case 1:
return 0.0;
case 2:
return b2Math.SubtractVV(this.m_v1.w, this.m_v2.w).Length();
case 3:
return b2Math.CrossVV(b2Math.SubtractVV(this.m_v2.w, this.m_v1.w), b2Math.SubtractVV(this.m_v3.w, this.m_v1.w));
default:
b2Settings.b2Assert(false);
return 0.0;
}
}
b2Simplex.prototype.Solve2 = function () {
var w1 = this.m_v1.w;
var w2 = this.m_v2.w;
var e12 = b2Math.SubtractVV(w2, w1);
var d12_2 = (-(w1.x * e12.x + w1.y * e12.y));
if (d12_2 <= 0.0) {
this.m_v1.a = 1.0;
this.m_count = 1;
return;
}
var d12_1 = (w2.x * e12.x + w2.y * e12.y);
if (d12_1 <= 0.0) {
this.m_v2.a = 1.0;
this.m_count = 1;
this.m_v1.Set(this.m_v2);
return;
}
var inv_d12 = 1.0 / (d12_1 + d12_2);
this.m_v1.a = d12_1 * inv_d12;
this.m_v2.a = d12_2 * inv_d12;
this.m_count = 2;
}
b2Simplex.prototype.Solve3 = function () {
var w1 = this.m_v1.w;
var w2 = this.m_v2.w;
var w3 = this.m_v3.w;
var e12 = b2Math.SubtractVV(w2, w1);
var w1e12 = b2Math.Dot(w1, e12);
var w2e12 = b2Math.Dot(w2, e12);
var d12_1 = w2e12;
var d12_2 = (-w1e12);
var e13 = b2Math.SubtractVV(w3, w1);
var w1e13 = b2Math.Dot(w1, e13);
var w3e13 = b2Math.Dot(w3, e13);
var d13_1 = w3e13;
var d13_2 = (-w1e13);
var e23 = b2Math.SubtractVV(w3, w2);
var w2e23 = b2Math.Dot(w2, e23);
var w3e23 = b2Math.Dot(w3, e23);
var d23_1 = w3e23;
var d23_2 = (-w2e23);
var n123 = b2Math.CrossVV(e12, e13);
var d123_1 = n123 * b2Math.CrossVV(w2, w3);
var d123_2 = n123 * b2Math.CrossVV(w3, w1);
var d123_3 = n123 * b2Math.CrossVV(w1, w2);
if (d12_2 <= 0.0 && d13_2 <= 0.0) {
this.m_v1.a = 1.0;
this.m_count = 1;
return;
}
if (d12_1 > 0.0 && d12_2 > 0.0 && d123_3 <= 0.0) {
var inv_d12 = 1.0 / (d12_1 + d12_2);
this.m_v1.a = d12_1 * inv_d12;
this.m_v2.a = d12_2 * inv_d12;
this.m_count = 2;
return;
}
if (d13_1 > 0.0 && d13_2 > 0.0 && d123_2 <= 0.0) {
var inv_d13 = 1.0 / (d13_1 + d13_2);
this.m_v1.a = d13_1 * inv_d13;
this.m_v3.a = d13_2 * inv_d13;
this.m_count = 2;
this.m_v2.Set(this.m_v3);
return;
}
if (d12_1 <= 0.0 && d23_2 <= 0.0) {
this.m_v2.a = 1.0;
this.m_count = 1;
this.m_v1.Set(this.m_v2);
return;
}
if (d13_1 <= 0.0 && d23_1 <= 0.0) {
this.m_v3.a = 1.0;
this.m_count = 1;
this.m_v1.Set(this.m_v3);
return;
}
if (d23_1 > 0.0 && d23_2 > 0.0 && d123_1 <= 0.0) {
var inv_d23 = 1.0 / (d23_1 + d23_2);
this.m_v2.a = d23_1 * inv_d23;
this.m_v3.a = d23_2 * inv_d23;
this.m_count = 2;
this.m_v1.Set(this.m_v3);
return;
}
var inv_d123 = 1.0 / (d123_1 + d123_2 + d123_3);
this.m_v1.a = d123_1 * inv_d123;
this.m_v2.a = d123_2 * inv_d123;
this.m_v3.a = d123_3 * inv_d123;
this.m_count = 3;
}
b2SimplexCache.b2SimplexCache = function () {
this.indexA = new Vector_a2j_Number(3);
this.indexB = new Vector_a2j_Number(3);
};
b2SimplexVertex.b2SimplexVertex = function () {};
b2SimplexVertex.prototype.Set = function (other) {
this.wA.SetV(other.wA);
this.wB.SetV(other.wB);
this.w.SetV(other.w);
this.a = other.a;
this.indexA = other.indexA;
this.indexB = other.indexB;
}
b2TimeOfImpact.b2TimeOfImpact = function () {};
b2TimeOfImpact.prototype.TimeOfImpact = function (input) {
++b2TimeOfImpact.b2_toiCalls;
var proxyA = input.proxyA;
var proxyB = input.proxyB;
var sweepA = input.sweepA;
var sweepB = input.sweepB;
b2Settings.b2Assert(sweepA.t0 == sweepB.t0);
b2Settings.b2Assert(1.0 - sweepA.t0 > Number.MIN_VALUE);
var radius = proxyA.m_radius + proxyB.m_radius;
var tolerance = input.tolerance;
var alpha = 0.0;
var k_maxIterations = 1000;
var iter = 0;
var target = 0.0;
b2TimeOfImpact.s_cache.count = 0;
b2TimeOfImpact.s_distanceInput.useRadii = false;
for (;;) {
sweepA.GetTransform(b2TimeOfImpact.s_xfA, alpha);
sweepB.GetTransform(b2TimeOfImpact.s_xfB, alpha);
b2TimeOfImpact.s_distanceInput.proxyA = proxyA;
b2TimeOfImpact.s_distanceInput.proxyB = proxyB;
b2TimeOfImpact.s_distanceInput.transformA = b2TimeOfImpact.s_xfA;
b2TimeOfImpact.s_distanceInput.transformB = b2TimeOfImpact.s_xfB;
b2Distance.Distance(b2TimeOfImpact.s_distanceOutput, b2TimeOfImpact.s_cache, b2TimeOfImpact.s_distanceInput);
if (b2TimeOfImpact.s_distanceOutput.distance <= 0.0) {
alpha = 1.0;
break;
}
b2TimeOfImpact.s_fcn.Initialize(b2TimeOfImpact.s_cache, proxyA, b2TimeOfImpact.s_xfA, proxyB, b2TimeOfImpact.s_xfB);
var separation = b2TimeOfImpact.s_fcn.Evaluate(b2TimeOfImpact.s_xfA, b2TimeOfImpact.s_xfB);
if (separation <= 0.0) {
alpha = 1.0;
break;
}
if (iter == 0) {
if (separation > radius) {
target = b2Math.Max(radius - tolerance, 0.75 * radius);
}
else {
target = b2Math.Max(separation - tolerance, 0.02 * radius);
}
}
if (separation - target < 0.5 * tolerance) {
if (iter == 0) {
alpha = 1.0;
break;
}
break;
}
var newAlpha = alpha; {
var x1 = alpha;
var x2 = 1.0;
var f1 = separation;
sweepA.GetTransform(b2TimeOfImpact.s_xfA, x2);
sweepB.GetTransform(b2TimeOfImpact.s_xfB, x2);
var f2 = b2TimeOfImpact.s_fcn.Evaluate(b2TimeOfImpact.s_xfA, b2TimeOfImpact.s_xfB);
if (f2 >= target) {
alpha = 1.0;
break;
}
var rootIterCount = 0;
for (;;) {
var x = 0;
if (rootIterCount & 1) {
x = x1 + (target - f1) * (x2 - x1) / (f2 - f1);
}
else {
x = 0.5 * (x1 + x2);
}
sweepA.GetTransform(b2TimeOfImpact.s_xfA, x);
sweepB.GetTransform(b2TimeOfImpact.s_xfB, x);
var f = b2TimeOfImpact.s_fcn.Evaluate(b2TimeOfImpact.s_xfA, b2TimeOfImpact.s_xfB);
if (b2Math.Abs(f - target) < 0.025 * tolerance) {
newAlpha = x;
break;
}
if (f > target) {
x1 = x;
f1 = f;
}
else {
x2 = x;
f2 = f;
}++rootIterCount;
++b2TimeOfImpact.b2_toiRootIters;
if (rootIterCount == 50) {
break;
}
}
b2TimeOfImpact.b2_toiMaxRootIters = b2Math.Max(b2TimeOfImpact.b2_toiMaxRootIters, rootIterCount);
}
if (newAlpha < (1.0 + 100.0 * Number.MIN_VALUE) * alpha) {
break;
}
alpha = newAlpha;
iter++;
++b2TimeOfImpact.b2_toiIters;
if (iter == k_maxIterations) {
break;
}
}
b2TimeOfImpact.b2_toiMaxIters = b2Math.Max(b2TimeOfImpact.b2_toiMaxIters, iter);
return alpha;
}
b2TimeOfImpact.TimeOfImpact = b2TimeOfImpact.prototype.TimeOfImpact;
_A2J_postDefs.push(function () {
Box2D.Collision.b2TimeOfImpact.b2_toiCalls = 0;
Box2D.Collision.b2TimeOfImpact.prototype.b2_toiCalls = Box2D.Collision.b2TimeOfImpact.b2_toiCalls;
Box2D.Collision.b2TimeOfImpact.b2_toiIters = 0;
Box2D.Collision.b2TimeOfImpact.prototype.b2_toiIters = Box2D.Collision.b2TimeOfImpact.b2_toiIters;
Box2D.Collision.b2TimeOfImpact.b2_toiMaxIters = 0;
Box2D.Collision.b2TimeOfImpact.prototype.b2_toiMaxIters = Box2D.Collision.b2TimeOfImpact.b2_toiMaxIters;
Box2D.Collision.b2TimeOfImpact.b2_toiRootIters = 0;
Box2D.Collision.b2TimeOfImpact.prototype.b2_toiRootIters = Box2D.Collision.b2TimeOfImpact.b2_toiRootIters;
Box2D.Collision.b2TimeOfImpact.b2_toiMaxRootIters = 0;
Box2D.Collision.b2TimeOfImpact.prototype.b2_toiMaxRootIters = Box2D.Collision.b2TimeOfImpact.b2_toiMaxRootIters;
Box2D.Collision.b2TimeOfImpact.s_cache = new b2SimplexCache();
Box2D.Collision.b2TimeOfImpact.prototype.s_cache = Box2D.Collision.b2TimeOfImpact.s_cache;
Box2D.Collision.b2TimeOfImpact.s_distanceInput = new b2DistanceInput();
Box2D.Collision.b2TimeOfImpact.prototype.s_distanceInput = Box2D.Collision.b2TimeOfImpact.s_distanceInput;
Box2D.Collision.b2TimeOfImpact.s_xfA = new b2Transform();
Box2D.Collision.b2TimeOfImpact.prototype.s_xfA = Box2D.Collision.b2TimeOfImpact.s_xfA;
Box2D.Collision.b2TimeOfImpact.s_xfB = new b2Transform();
Box2D.Collision.b2TimeOfImpact.prototype.s_xfB = Box2D.Collision.b2TimeOfImpact.s_xfB;
Box2D.Collision.b2TimeOfImpact.s_fcn = new b2SeparationFunction();
Box2D.Collision.b2TimeOfImpact.prototype.s_fcn = Box2D.Collision.b2TimeOfImpact.s_fcn;
Box2D.Collision.b2TimeOfImpact.s_distanceOutput = new b2DistanceOutput();
Box2D.Collision.b2TimeOfImpact.prototype.s_distanceOutput = Box2D.Collision.b2TimeOfImpact.s_distanceOutput;
});
b2TOIInput.b2TOIInput = function () {
this.proxyA = new b2DistanceProxy();
this.proxyB = new b2DistanceProxy();
this.sweepA = new b2Sweep();
this.sweepB = new b2Sweep();
};
b2WorldManifold.b2WorldManifold = function () {
this.m_normal = new b2Vec2();
};
b2WorldManifold.prototype.b2WorldManifold = function () {
this.m_points = new Vector(b2Settings.b2_maxManifoldPoints);
for (var i = 0; i < b2Settings.b2_maxManifoldPoints; i++) {
this.m_points[i] = new b2Vec2();
}
}
b2WorldManifold.prototype.Initialize = function (manifold, xfA, radiusA, xfB, radiusB) {
if (radiusA === undefined) radiusA = 0;
if (radiusB === undefined) radiusB = 0;
if (manifold.m_pointCount == 0) {
return;
}
var i = 0;
var tVec;
var tMat;
var normalX = 0;
var normalY = 0;
var planePointX = 0;
var planePointY = 0;
var clipPointX = 0;
var clipPointY = 0;
switch (manifold.m_type) {
case b2Manifold.e_circles:
{
tMat = xfA.R;
tVec = manifold.m_localPoint;
var pointAX = xfA.position.x + tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
var pointAY = xfA.position.y + tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
tMat = xfB.R;
tVec = manifold.m_points[0].m_localPoint;
var pointBX = xfB.position.x + tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
var pointBY = xfB.position.y + tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
var dX = pointBX - pointAX;
var dY = pointBY - pointAY;
var d2 = dX * dX + dY * dY;
if (d2 > Number.MIN_VALUE * Number.MIN_VALUE) {
var d = Math.sqrt(d2);
this.m_normal.x = dX / d;
this.m_normal.y = dY / d;
}
else {
this.m_normal.x = 1;
this.m_normal.y = 0;
}
var cAX = pointAX + radiusA * this.m_normal.x;
var cAY = pointAY + radiusA * this.m_normal.y;
var cBX = pointBX - radiusB * this.m_normal.x;
var cBY = pointBY - radiusB * this.m_normal.y;
this.m_points[0].x = 0.5 * (cAX + cBX);
this.m_points[0].y = 0.5 * (cAY + cBY);
}
break;
case b2Manifold.e_faceA:
{
tMat = xfA.R;
tVec = manifold.m_localPlaneNormal;
normalX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
normalY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
tMat = xfA.R;
tVec = manifold.m_localPoint;
planePointX = xfA.position.x + tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
planePointY = xfA.position.y + tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
this.m_normal.x = normalX;
this.m_normal.y = normalY;
for (i = 0;
i < manifold.m_pointCount; i++) {
tMat = xfB.R;
tVec = manifold.m_points[i].m_localPoint;
clipPointX = xfB.position.x + tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
clipPointY = xfB.position.y + tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
this.m_points[i].x = clipPointX + 0.5 * (radiusA - (clipPointX - planePointX) * normalX - (clipPointY - planePointY) * normalY - radiusB) * normalX;
this.m_points[i].y = clipPointY + 0.5 * (radiusA - (clipPointX - planePointX) * normalX - (clipPointY - planePointY) * normalY - radiusB) * normalY;
}
}
break;
case b2Manifold.e_faceB:
{
tMat = xfB.R;
tVec = manifold.m_localPlaneNormal;
normalX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
normalY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
tMat = xfB.R;
tVec = manifold.m_localPoint;
planePointX = xfB.position.x + tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
planePointY = xfB.position.y + tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
this.m_normal.x = (-normalX);
this.m_normal.y = (-normalY);
for (i = 0;
i < manifold.m_pointCount; i++) {
tMat = xfA.R;
tVec = manifold.m_points[i].m_localPoint;
clipPointX = xfA.position.x + tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
clipPointY = xfA.position.y + tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
this.m_points[i].x = clipPointX + 0.5 * (radiusB - (clipPointX - planePointX) * normalX - (clipPointY - planePointY) * normalY - radiusA) * normalX;
this.m_points[i].y = clipPointY + 0.5 * (radiusB - (clipPointX - planePointX) * normalX - (clipPointY - planePointY) * normalY - radiusA) * normalY;
}
}
break;
}
}
ClipVertex.ClipVertex = function () {
this.v = new b2Vec2();
this.id = new b2ContactID();
};
ClipVertex.prototype.Set = function (other) {
this.v.SetV(other.v);
this.id.Set(other.id);
}
Features.Features = function () {};
Features.prototype.__defineGetter__('referenceEdge', function () {
return this._referenceEdge;
});
Features.prototype.__defineSetter__('referenceEdge', function (value) {
if (value === undefined) value = 0;
this._referenceEdge = value;
this._m_id._key = (this._m_id._key & 0xffffff00) | (this._referenceEdge & 0x000000ff);
});
Features.prototype.__defineGetter__('incidentEdge', function () {
return this._incidentEdge;
});
Features.prototype.__defineSetter__('incidentEdge', function (value) {
if (value === undefined) value = 0;
this._incidentEdge = value;
this._m_id._key = (this._m_id._key & 0xffff00ff) | ((this._incidentEdge << 8) & 0x0000ff00);
});
Features.prototype.__defineGetter__('incidentVertex', function () {
return this._incidentVertex;
});
Features.prototype.__defineSetter__('incidentVertex', function (value) {
if (value === undefined) value = 0;
this._incidentVertex = value;
this._m_id._key = (this._m_id._key & 0xff00ffff) | ((this._incidentVertex << 16) & 0x00ff0000);
});
Features.prototype.__defineGetter__('flip', function () {
return this._flip;
});
Features.prototype.__defineSetter__('flip', function (value) {
if (value === undefined) value = 0;
this._flip = value;
this._m_id._key = (this._m_id._key & 0x00ffffff) | ((this._flip << 24) & 0xff000000);
});
})(); /* source: disabled*/
(function () {
var b2Color = Box2D.Common.b2Color;
var b2internal = Box2D.Common.b2internal;
var b2Settings = Box2D.Common.b2Settings;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2EdgeChainDef = Box2D.Collision.Shapes.b2EdgeChainDef;
var b2EdgeShape = Box2D.Collision.Shapes.b2EdgeShape;
var b2MassData = Box2D.Collision.Shapes.b2MassData;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2Shape = Box2D.Collision.Shapes.b2Shape;
var b2Mat22 = Box2D.Common.Math.b2Mat22;
var b2Mat33 = Box2D.Common.Math.b2Mat33;
var b2Math = Box2D.Common.Math.b2Math;
var b2Sweep = Box2D.Common.Math.b2Sweep;
var b2Transform = Box2D.Common.Math.b2Transform;
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2Vec3 = Box2D.Common.Math.b2Vec3;
var b2Color = Box2D.Common.b2Color;
var b2internal = Box2D.Common.b2internal;
var b2Settings = Box2D.Common.b2Settings;
var b2Body = Box2D.Dynamics.b2Body;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2ContactFilter = Box2D.Dynamics.b2ContactFilter;
var b2ContactImpulse = Box2D.Dynamics.b2ContactImpulse;
var b2ContactListener = Box2D.Dynamics.b2ContactListener;
var b2ContactManager = Box2D.Dynamics.b2ContactManager;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var b2DestructionListener = Box2D.Dynamics.b2DestructionListener;
var b2FilterData = Box2D.Dynamics.b2FilterData;
var b2Fixture = Box2D.Dynamics.b2Fixture;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2Island = Box2D.Dynamics.b2Island;
var b2TimeStep = Box2D.Dynamics.b2TimeStep;
var b2World = Box2D.Dynamics.b2World;
var b2AABB = Box2D.Collision.b2AABB;
var b2Bound = Box2D.Collision.b2Bound;
var b2BoundValues = Box2D.Collision.b2BoundValues;
var b2BroadPhase = Box2D.Collision.b2BroadPhase;
var b2Collision = Box2D.Collision.b2Collision;
var b2ContactID = Box2D.Collision.b2ContactID;
var b2ContactPoint = Box2D.Collision.b2ContactPoint;
var b2Distance = Box2D.Collision.b2Distance;
var b2DistanceInput = Box2D.Collision.b2DistanceInput;
var b2DistanceOutput = Box2D.Collision.b2DistanceOutput;
var b2DistanceProxy = Box2D.Collision.b2DistanceProxy;
var b2DynamicTree = Box2D.Collision.b2DynamicTree;
var b2DynamicTreeBroadPhase = Box2D.Collision.b2DynamicTreeBroadPhase;
var b2DynamicTreeNode = Box2D.Collision.b2DynamicTreeNode;
var b2DynamicTreePair = Box2D.Collision.b2DynamicTreePair;
var b2Manifold = Box2D.Collision.b2Manifold;
var b2ManifoldPoint = Box2D.Collision.b2ManifoldPoint;
var b2OBB = Box2D.Collision.b2OBB;
var b2Pair = Box2D.Collision.b2Pair;
var b2PairManager = Box2D.Collision.b2PairManager;
var b2Point = Box2D.Collision.b2Point;
var b2Proxy = Box2D.Collision.b2Proxy;
var b2RayCastInput = Box2D.Collision.b2RayCastInput;
var b2RayCastOutput = Box2D.Collision.b2RayCastOutput;
var b2Segment = Box2D.Collision.b2Segment;
var b2SeparationFunction = Box2D.Collision.b2SeparationFunction;
var b2Simplex = Box2D.Collision.b2Simplex;
var b2SimplexCache = Box2D.Collision.b2SimplexCache;
var b2SimplexVertex = Box2D.Collision.b2SimplexVertex;
var b2TimeOfImpact = Box2D.Collision.b2TimeOfImpact;
var b2TOIInput = Box2D.Collision.b2TOIInput;
var b2WorldManifold = Box2D.Collision.b2WorldManifold;
var ClipVertex = Box2D.Collision.ClipVertex;
var Features = Box2D.Collision.Features;
var IBroadPhase = Box2D.Collision.IBroadPhase;
var b2internal = Box2D.Common.b2internal;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2EdgeChainDef = Box2D.Collision.Shapes.b2EdgeChainDef;
var b2EdgeShape = Box2D.Collision.Shapes.b2EdgeShape;
var b2MassData = Box2D.Collision.Shapes.b2MassData;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2Shape = Box2D.Collision.Shapes.b2Shape;
b2CircleShape.inherit(Box2D.Collision.Shapes.b2Shape);
b2CircleShape.prototype.__super = Box2D.Collision.Shapes.b2Shape.prototype;
b2CircleShape.b2CircleShape = function () {
Box2D.Collision.Shapes.b2Shape.b2Shape.apply(this, arguments);
this.m_p = new b2Vec2();
};
b2CircleShape.prototype.Copy = function () {
var s = new b2CircleShape();
s.Set(this);
return s;
}
b2CircleShape.prototype.Set = function (other) {
this.__super.Set.call(this, other);
if (a2j.is(other, b2CircleShape)) {
var other2 = (other instanceof b2CircleShape ? other : null);
this.m_p.SetV(other2.m_p);
}
}
b2CircleShape.prototype.TestPoint = function (transform, p) {
var tMat = transform.R;
var dX = transform.position.x + (tMat.col1.x * this.m_p.x + tMat.col2.x * this.m_p.y);
var dY = transform.position.y + (tMat.col1.y * this.m_p.x + tMat.col2.y * this.m_p.y);
dX = p.x - dX;
dY = p.y - dY;
return (dX * dX + dY * dY) <= this.m_radius * this.m_radius;
}
b2CircleShape.prototype.RayCast = function (output, input, transform) {
var tMat = transform.R;
var positionX = transform.position.x + (tMat.col1.x * this.m_p.x + tMat.col2.x * this.m_p.y);
var positionY = transform.position.y + (tMat.col1.y * this.m_p.x + tMat.col2.y * this.m_p.y);
var sX = input.p1.x - positionX;
var sY = input.p1.y - positionY;
var b = (sX * sX + sY * sY) - this.m_radius * this.m_radius;
var rX = input.p2.x - input.p1.x;
var rY = input.p2.y - input.p1.y;
var c = (sX * rX + sY * rY);
var rr = (rX * rX + rY * rY);
var sigma = c * c - rr * b;
if (sigma < 0.0 || rr < Number.MIN_VALUE) {
return false;
}
var a = (-(c + Math.sqrt(sigma)));
if (0.0 <= a && a <= input.maxFraction * rr) {
a /= rr;
output.fraction = a;
output.normal.x = sX + a * rX;
output.normal.y = sY + a * rY;
output.normal.Normalize();
return true;
}
return false;
}
b2CircleShape.prototype.ComputeAABB = function (aabb, transform) {
var tMat = transform.R;
var pX = transform.position.x + (tMat.col1.x * this.m_p.x + tMat.col2.x * this.m_p.y);
var pY = transform.position.y + (tMat.col1.y * this.m_p.x + tMat.col2.y * this.m_p.y);
aabb.lowerBound.Set(pX - this.m_radius, pY - this.m_radius);
aabb.upperBound.Set(pX + this.m_radius, pY + this.m_radius);
}
b2CircleShape.prototype.ComputeMass = function (massData, density) {
if (density === undefined) density = 0;
massData.mass = density * b2Settings.b2_pi * this.m_radius * this.m_radius;
massData.center.SetV(this.m_p);
massData.I = massData.mass * (0.5 * this.m_radius * this.m_radius + (this.m_p.x * this.m_p.x + this.m_p.y * this.m_p.y));
}
b2CircleShape.prototype.ComputeSubmergedArea = function (normal, offset, xf, c) {
if (offset === undefined) offset = 0;
var p = b2Math.MulX(xf, this.m_p);
var l = (-(b2Math.Dot(normal, p) - offset));
if (l < (-this.m_radius) + Number.MIN_VALUE) {
return 0;
}
if (l > this.m_radius) {
c.SetV(p);
return Math.PI * this.m_radius * this.m_radius;
}
var r2 = this.m_radius * this.m_radius;
var l2 = l * l;
var area = r2 * (Math.asin(l / this.m_radius) + Math.PI / 2) + l * Math.sqrt(r2 - l2);
var com = (-2 / 3 * Math.pow(r2 - l2, 1.5) / area);
c.x = p.x + normal.x * com;
c.y = p.y + normal.y * com;
return area;
}
b2CircleShape.prototype.GetLocalPosition = function () {
return this.m_p;
}
b2CircleShape.prototype.SetLocalPosition = function (position) {
this.m_p.SetV(position);
}
b2CircleShape.prototype.GetRadius = function () {
return this.m_radius;
}
b2CircleShape.prototype.SetRadius = function (radius) {
if (radius === undefined) radius = 0;
this.m_radius = radius;
}
b2CircleShape.prototype.b2CircleShape = function (radius) {
if (radius === undefined) radius = 0;
this.__super.b2Shape.call(this);
this.m_type = this.e_circleShape;
this.m_radius = radius;
}
b2EdgeChainDef.b2EdgeChainDef = function () {};
b2EdgeChainDef.prototype.b2EdgeChainDef = function () {
this.vertexCount = 0;
this.isALoop = true;
this.vertices = [];
}
b2EdgeShape.inherit(Box2D.Collision.Shapes.b2Shape);
b2EdgeShape.prototype.__super = Box2D.Collision.Shapes.b2Shape.prototype;
b2EdgeShape.b2EdgeShape = function () {
Box2D.Collision.Shapes.b2Shape.b2Shape.apply(this, arguments);
this.s_supportVec = new b2Vec2();
this.m_v1 = new b2Vec2();
this.m_v2 = new b2Vec2();
this.m_coreV1 = new b2Vec2();
this.m_coreV2 = new b2Vec2();
this.m_normal = new b2Vec2();
this.m_direction = new b2Vec2();
this.m_cornerDir1 = new b2Vec2();
this.m_cornerDir2 = new b2Vec2();
};
b2EdgeShape.prototype.TestPoint = function (transform, p) {
return false;
}
b2EdgeShape.prototype.RayCast = function (output, input, transform) {
var tMat;
var rX = input.p2.x - input.p1.x;
var rY = input.p2.y - input.p1.y;
tMat = transform.R;
var v1X = transform.position.x + (tMat.col1.x * this.m_v1.x + tMat.col2.x * this.m_v1.y);
var v1Y = transform.position.y + (tMat.col1.y * this.m_v1.x + tMat.col2.y * this.m_v1.y);
var nX = transform.position.y + (tMat.col1.y * this.m_v2.x + tMat.col2.y * this.m_v2.y) - v1Y;
var nY = (-(transform.position.x + (tMat.col1.x * this.m_v2.x + tMat.col2.x * this.m_v2.y) - v1X));
var k_slop = 100.0 * Number.MIN_VALUE;
var denom = (-(rX * nX + rY * nY));
if (denom > k_slop) {
var bX = input.p1.x - v1X;
var bY = input.p1.y - v1Y;
var a = (bX * nX + bY * nY);
if (0.0 <= a && a <= input.maxFraction * denom) {
var mu2 = (-rX * bY) + rY * bX;
if ((-k_slop * denom) <= mu2 && mu2 <= denom * (1.0 + k_slop)) {
a /= denom;
output.fraction = a;
var nLen = Math.sqrt(nX * nX + nY * nY);
output.normal.x = nX / nLen;
output.normal.y = nY / nLen;
return true;
}
}
}
return false;
}
b2EdgeShape.prototype.ComputeAABB = function (aabb, transform) {
var tMat = transform.R;
var v1X = transform.position.x + (tMat.col1.x * this.m_v1.x + tMat.col2.x * this.m_v1.y);
var v1Y = transform.position.y + (tMat.col1.y * this.m_v1.x + tMat.col2.y * this.m_v1.y);
var v2X = transform.position.x + (tMat.col1.x * this.m_v2.x + tMat.col2.x * this.m_v2.y);
var v2Y = transform.position.y + (tMat.col1.y * this.m_v2.x + tMat.col2.y * this.m_v2.y);
if (v1X < v2X) {
aabb.lowerBound.x = v1X;
aabb.upperBound.x = v2X;
}
else {
aabb.lowerBound.x = v2X;
aabb.upperBound.x = v1X;
}
if (v1Y < v2Y) {
aabb.lowerBound.y = v1Y;
aabb.upperBound.y = v2Y;
}
else {
aabb.lowerBound.y = v2Y;
aabb.upperBound.y = v1Y;
}
}
b2EdgeShape.prototype.ComputeMass = function (massData, density) {
if (density === undefined) density = 0;
massData.mass = 0;
massData.center.SetV(this.m_v1);
massData.I = 0;
}
b2EdgeShape.prototype.ComputeSubmergedArea = function (normal, offset, xf, c) {
if (offset === undefined) offset = 0;
var v0 = new b2Vec2(normal.x * offset, normal.y * offset);
var v1 = b2Math.MulX(xf, this.m_v1);
var v2 = b2Math.MulX(xf, this.m_v2);
var d1 = b2Math.Dot(normal, v1) - offset;
var d2 = b2Math.Dot(normal, v2) - offset;
if (d1 > 0) {
if (d2 > 0) {
return 0;
}
else {
v1.x = (-d2 / (d1 - d2) * v1.x) + d1 / (d1 - d2) * v2.x;
v1.y = (-d2 / (d1 - d2) * v1.y) + d1 / (d1 - d2) * v2.y;
}
}
else {
if (d2 > 0) {
v2.x = (-d2 / (d1 - d2) * v1.x) + d1 / (d1 - d2) * v2.x;
v2.y = (-d2 / (d1 - d2) * v1.y) + d1 / (d1 - d2) * v2.y;
}
else {}
}
c.x = (v0.x + v1.x + v2.x) / 3;
c.y = (v0.y + v1.y + v2.y) / 3;
return 0.5 * ((v1.x - v0.x) * (v2.y - v0.y) - (v1.y - v0.y) * (v2.x - v0.x));
}
b2EdgeShape.prototype.GetLength = function () {
return this.m_length;
}
b2EdgeShape.prototype.GetVertex1 = function () {
return this.m_v1;
}
b2EdgeShape.prototype.GetVertex2 = function () {
return this.m_v2;
}
b2EdgeShape.prototype.GetCoreVertex1 = function () {
return this.m_coreV1;
}
b2EdgeShape.prototype.GetCoreVertex2 = function () {
return this.m_coreV2;
}
b2EdgeShape.prototype.GetNormalVector = function () {
return this.m_normal;
}
b2EdgeShape.prototype.GetDirectionVector = function () {
return this.m_direction;
}
b2EdgeShape.prototype.GetCorner1Vector = function () {
return this.m_cornerDir1;
}
b2EdgeShape.prototype.GetCorner2Vector = function () {
return this.m_cornerDir2;
}
b2EdgeShape.prototype.Corner1IsConvex = function () {
return this.m_cornerConvex1;
}
b2EdgeShape.prototype.Corner2IsConvex = function () {
return this.m_cornerConvex2;
}
b2EdgeShape.prototype.GetFirstVertex = function (xf) {
var tMat = xf.R;
return new b2Vec2(xf.position.x + (tMat.col1.x * this.m_coreV1.x + tMat.col2.x * this.m_coreV1.y), xf.position.y + (tMat.col1.y * this.m_coreV1.x + tMat.col2.y * this.m_coreV1.y));
}
b2EdgeShape.prototype.GetNextEdge = function () {
return this.m_nextEdge;
}
b2EdgeShape.prototype.GetPrevEdge = function () {
return this.m_prevEdge;
}
b2EdgeShape.prototype.Support = function (xf, dX, dY) {
if (dX === undefined) dX = 0;
if (dY === undefined) dY = 0;
var tMat = xf.R;
var v1X = xf.position.x + (tMat.col1.x * this.m_coreV1.x + tMat.col2.x * this.m_coreV1.y);
var v1Y = xf.position.y + (tMat.col1.y * this.m_coreV1.x + tMat.col2.y * this.m_coreV1.y);
var v2X = xf.position.x + (tMat.col1.x * this.m_coreV2.x + tMat.col2.x * this.m_coreV2.y);
var v2Y = xf.position.y + (tMat.col1.y * this.m_coreV2.x + tMat.col2.y * this.m_coreV2.y);
if ((v1X * dX + v1Y * dY) > (v2X * dX + v2Y * dY)) {
this.s_supportVec.x = v1X;
this.s_supportVec.y = v1Y;
}
else {
this.s_supportVec.x = v2X;
this.s_supportVec.y = v2Y;
}
return this.s_supportVec;
}
b2EdgeShape.prototype.b2EdgeShape = function (v1, v2) {
this.__super.b2Shape.call(this);
this.m_type = this.e_edgeShape;
this.m_prevEdge = null;
this.m_nextEdge = null;
this.m_v1 = v1;
this.m_v2 = v2;
this.m_direction.Set(this.m_v2.x - this.m_v1.x, this.m_v2.y - this.m_v1.y);
this.m_length = this.m_direction.Normalize();
this.m_normal.Set(this.m_direction.y, (-this.m_direction.x));
this.m_coreV1.Set((-b2Settings.b2_toiSlop * (this.m_normal.x - this.m_direction.x)) + this.m_v1.x, (-b2Settings.b2_toiSlop * (this.m_normal.y - this.m_direction.y)) + this.m_v1.y);
this.m_coreV2.Set((-b2Settings.b2_toiSlop * (this.m_normal.x + this.m_direction.x)) + this.m_v2.x, (-b2Settings.b2_toiSlop * (this.m_normal.y + this.m_direction.y)) + this.m_v2.y);
this.m_cornerDir1 = this.m_normal;
this.m_cornerDir2.Set((-this.m_normal.x), (-this.m_normal.y));
}
b2EdgeShape.prototype.SetPrevEdge = function (edge, core, cornerDir, convex) {
this.m_prevEdge = edge;
this.m_coreV1 = core;
this.m_cornerDir1 = cornerDir;
this.m_cornerConvex1 = convex;
}
b2EdgeShape.prototype.SetNextEdge = function (edge, core, cornerDir, convex) {
this.m_nextEdge = edge;
this.m_coreV2 = core;
this.m_cornerDir2 = cornerDir;
this.m_cornerConvex2 = convex;
}
b2MassData.b2MassData = function () {
this.mass = 0.0;
this.center = new b2Vec2(0, 0);
this.I = 0.0;
};
b2PolygonShape.inherit(Box2D.Collision.Shapes.b2Shape);
b2PolygonShape.prototype.__super = Box2D.Collision.Shapes.b2Shape.prototype;
b2PolygonShape.b2PolygonShape = function () {
Box2D.Collision.Shapes.b2Shape.b2Shape.apply(this, arguments);
};
b2PolygonShape.prototype.Copy = function () {
var s = new b2PolygonShape();
s.Set(this);
return s;
}
b2PolygonShape.prototype.Set = function (other) {
this.__super.Set.call(this, other);
if (a2j.is(other, b2PolygonShape)) {
var other2 = (other instanceof b2PolygonShape ? other : null);
this.m_centroid.SetV(other2.m_centroid);
this.m_vertexCount = other2.m_vertexCount;
this.Reserve(this.m_vertexCount);
for (var i = 0; i < this.m_vertexCount; i++) {
this.m_vertices[i].SetV(other2.m_vertices[i]);
this.m_normals[i].SetV(other2.m_normals[i]);
}
}
}
b2PolygonShape.prototype.SetAsArray = function (vertices, vertexCount) {
if (vertexCount === undefined) vertexCount = 0;
var v = new Vector();
var tVec;
for (var each in vertices) {
tVec = vertices[each]; {
v.push(tVec);
}
}
this.SetAsVector(v, vertexCount);
}
b2PolygonShape.prototype.AsArray = function (vertices, vertexCount) {
if (vertexCount === undefined) vertexCount = 0;
var polygonShape = new b2PolygonShape();
polygonShape.SetAsArray(vertices, vertexCount);
return polygonShape;
}
b2PolygonShape.AsArray = b2PolygonShape.prototype.AsArray;
b2PolygonShape.prototype.SetAsVector = function (vertices, vertexCount) {
if (vertexCount === undefined) vertexCount = 0;
if (vertexCount == 0) vertexCount = vertices.length;
b2Settings.b2Assert(2 <= vertexCount);
this.m_vertexCount = vertexCount;
this.Reserve(vertexCount);
var i = 0;
for (i = 0;
i < this.m_vertexCount; i++) {
this.m_vertices[i].SetV(vertices[i]);
}
for (i = 0;
i < this.m_vertexCount; ++i) {
var i1 = parseInt(i);
var i2 = parseInt(i + 1 < this.m_vertexCount ? i + 1 : 0);
var edge = b2Math.SubtractVV(this.m_vertices[i2], this.m_vertices[i1]);
b2Settings.b2Assert(edge.LengthSquared() > Number.MIN_VALUE);
this.m_normals[i].SetV(b2Math.CrossVF(edge, 1.0));
this.m_normals[i].Normalize();
}
this.m_centroid = this.ComputeCentroid(this.m_vertices, this.m_vertexCount);
}
b2PolygonShape.prototype.AsVector = function (vertices, vertexCount) {
if (vertexCount === undefined) vertexCount = 0;
var polygonShape = new b2PolygonShape();
polygonShape.SetAsVector(vertices, vertexCount);
return polygonShape;
}
b2PolygonShape.AsVector = b2PolygonShape.prototype.AsVector;
b2PolygonShape.prototype.SetAsBox = function (hx, hy) {
if (hx === undefined) hx = 0;
if (hy === undefined) hy = 0;
this.m_vertexCount = 4;
this.Reserve(4);
this.m_vertices[0].Set((-hx), (-hy));
this.m_vertices[1].Set(hx, (-hy));
this.m_vertices[2].Set(hx, hy);
this.m_vertices[3].Set((-hx), hy);
this.m_normals[0].Set(0.0, (-1.0));
this.m_normals[1].Set(1.0, 0.0);
this.m_normals[2].Set(0.0, 1.0);
this.m_normals[3].Set((-1.0), 0.0);
this.m_centroid.SetZero();
}
b2PolygonShape.prototype.AsBox = function (hx, hy) {
if (hx === undefined) hx = 0;
if (hy === undefined) hy = 0;
var polygonShape = new b2PolygonShape();
polygonShape.SetAsBox(hx, hy);
return polygonShape;
}
b2PolygonShape.AsBox = b2PolygonShape.prototype.AsBox;
b2PolygonShape.prototype.SetAsOrientedBox = function (hx, hy, center, angle) {
if (hx === undefined) hx = 0;
if (hy === undefined) hy = 0;
if (center === undefined) center = null;
if (angle === undefined) angle = 0.0;
this.m_vertexCount = 4;
this.Reserve(4);
this.m_vertices[0].Set((-hx), (-hy));
this.m_vertices[1].Set(hx, (-hy));
this.m_vertices[2].Set(hx, hy);
this.m_vertices[3].Set((-hx), hy);
this.m_normals[0].Set(0.0, (-1.0));
this.m_normals[1].Set(1.0, 0.0);
this.m_normals[2].Set(0.0, 1.0);
this.m_normals[3].Set((-1.0), 0.0);
this.m_centroid = center;
var xf = new b2Transform();
xf.position = center;
xf.R.Set(angle);
for (var i = 0; i < this.m_vertexCount; ++i) {
this.m_vertices[i] = b2Math.MulX(xf, this.m_vertices[i]);
this.m_normals[i] = b2Math.MulMV(xf.R, this.m_normals[i]);
}
}
b2PolygonShape.prototype.AsOrientedBox = function (hx, hy, center, angle) {
if (hx === undefined) hx = 0;
if (hy === undefined) hy = 0;
if (center === undefined) center = null;
if (angle === undefined) angle = 0.0;
var polygonShape = new b2PolygonShape();
polygonShape.SetAsOrientedBox(hx, hy, center, angle);
return polygonShape;
}
b2PolygonShape.AsOrientedBox = b2PolygonShape.prototype.AsOrientedBox;
b2PolygonShape.prototype.SetAsEdge = function (v1, v2) {
this.m_vertexCount = 2;
this.Reserve(2);
this.m_vertices[0].SetV(v1);
this.m_vertices[1].SetV(v2);
this.m_centroid.x = 0.5 * (v1.x + v2.x);
this.m_centroid.y = 0.5 * (v1.y + v2.y);
this.m_normals[0] = b2Math.CrossVF(b2Math.SubtractVV(v2, v1), 1.0);
this.m_normals[0].Normalize();
this.m_normals[1].x = (-this.m_normals[0].x);
this.m_normals[1].y = (-this.m_normals[0].y);
}
b2PolygonShape.prototype.AsEdge = function (v1, v2) {
var polygonShape = new b2PolygonShape();
polygonShape.SetAsEdge(v1, v2);
return polygonShape;
}
b2PolygonShape.AsEdge = b2PolygonShape.prototype.AsEdge;
b2PolygonShape.prototype.TestPoint = function (xf, p) {
var tVec;
var tMat = xf.R;
var tX = p.x - xf.position.x;
var tY = p.y - xf.position.y;
var pLocalX = (tX * tMat.col1.x + tY * tMat.col1.y);
var pLocalY = (tX * tMat.col2.x + tY * tMat.col2.y);
for (var i = 0; i < this.m_vertexCount; ++i) {
tVec = this.m_vertices[i];
tX = pLocalX - tVec.x;
tY = pLocalY - tVec.y;
tVec = this.m_normals[i];
var dot = (tVec.x * tX + tVec.y * tY);
if (dot > 0.0) {
return false;
}
}
return true;
}
b2PolygonShape.prototype.RayCast = function (output, input, transform) {
var lower = 0.0;
var upper = input.maxFraction;
var tX = 0;
var tY = 0;
var tMat;
var tVec;
tX = input.p1.x - transform.position.x;
tY = input.p1.y - transform.position.y;
tMat = transform.R;
var p1X = (tX * tMat.col1.x + tY * tMat.col1.y);
var p1Y = (tX * tMat.col2.x + tY * tMat.col2.y);
tX = input.p2.x - transform.position.x;
tY = input.p2.y - transform.position.y;
tMat = transform.R;
var p2X = (tX * tMat.col1.x + tY * tMat.col1.y);
var p2Y = (tX * tMat.col2.x + tY * tMat.col2.y);
var dX = p2X - p1X;
var dY = p2Y - p1Y;
var index = parseInt((-1));
for (var i = 0; i < this.m_vertexCount; ++i) {
tVec = this.m_vertices[i];
tX = tVec.x - p1X;
tY = tVec.y - p1Y;
tVec = this.m_normals[i];
var numerator = (tVec.x * tX + tVec.y * tY);
var denominator = (tVec.x * dX + tVec.y * dY);
if (denominator == 0.0) {
if (numerator < 0.0) {
return false;
}
}
else {
if (denominator < 0.0 && numerator < lower * denominator) {
lower = numerator / denominator;
index = i;
}
else if (denominator > 0.0 && numerator < upper * denominator) {
upper = numerator / denominator;
}
}
if (upper < lower - Number.MIN_VALUE) {
return false;
}
}
if (index >= 0) {
output.fraction = lower;
tMat = transform.R;
tVec = this.m_normals[index];
output.normal.x = (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
output.normal.y = (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
return true;
}
return false;
}
b2PolygonShape.prototype.ComputeAABB = function (aabb, xf) {
var tMat = xf.R;
var tVec = this.m_vertices[0];
var lowerX = xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
var lowerY = xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
var upperX = lowerX;
var upperY = lowerY;
for (var i = 1; i < this.m_vertexCount; ++i) {
tVec = this.m_vertices[i];
var vX = xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
var vY = xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
lowerX = lowerX < vX ? lowerX : vX;
lowerY = lowerY < vY ? lowerY : vY;
upperX = upperX > vX ? upperX : vX;
upperY = upperY > vY ? upperY : vY;
}
aabb.lowerBound.x = lowerX - this.m_radius;
aabb.lowerBound.y = lowerY - this.m_radius;
aabb.upperBound.x = upperX + this.m_radius;
aabb.upperBound.y = upperY + this.m_radius;
}
b2PolygonShape.prototype.ComputeMass = function (massData, density) {
if (density === undefined) density = 0;
if (this.m_vertexCount == 2) {
massData.center.x = 0.5 * (this.m_vertices[0].x + this.m_vertices[1].x);
massData.center.y = 0.5 * (this.m_vertices[0].y + this.m_vertices[1].y);
massData.mass = 0.0;
massData.I = 0.0;
return;
}
var centerX = 0.0;
var centerY = 0.0;
var area = 0.0;
var I = 0.0;
var p1X = 0.0;
var p1Y = 0.0;
var k_inv3 = 1.0 / 3.0;
for (var i = 0; i < this.m_vertexCount; ++i) {
var p2 = this.m_vertices[i];
var p3 = i + 1 < this.m_vertexCount ? this.m_vertices[parseInt(i + 1)] : this.m_vertices[0];
var e1X = p2.x - p1X;
var e1Y = p2.y - p1Y;
var e2X = p3.x - p1X;
var e2Y = p3.y - p1Y;
var D = e1X * e2Y - e1Y * e2X;
var triangleArea = 0.5 * D;area += triangleArea;
centerX += triangleArea * k_inv3 * (p1X + p2.x + p3.x);
centerY += triangleArea * k_inv3 * (p1Y + p2.y + p3.y);
var px = p1X;
var py = p1Y;
var ex1 = e1X;
var ey1 = e1Y;
var ex2 = e2X;
var ey2 = e2Y;
var intx2 = k_inv3 * (0.25 * (ex1 * ex1 + ex2 * ex1 + ex2 * ex2) + (px * ex1 + px * ex2)) + 0.5 * px * px;
var inty2 = k_inv3 * (0.25 * (ey1 * ey1 + ey2 * ey1 + ey2 * ey2) + (py * ey1 + py * ey2)) + 0.5 * py * py;I += D * (intx2 + inty2);
}
massData.mass = density * area;
centerX *= 1.0 / area;
centerY *= 1.0 / area;
massData.center.Set(centerX, centerY);
massData.I = density * I;
}
b2PolygonShape.prototype.ComputeSubmergedArea = function (normal, offset, xf, c) {
if (offset === undefined) offset = 0;
var normalL = b2Math.MulTMV(xf.R, normal);
var offsetL = offset - b2Math.Dot(normal, xf.position);
var depths = new Vector_a2j_Number();
var diveCount = 0;
var intoIndex = parseInt((-1));
var outoIndex = parseInt((-1));
var lastSubmerged = false;
var i = 0;
for (i = 0;
i < this.m_vertexCount; ++i) {
depths[i] = b2Math.Dot(normalL, this.m_vertices[i]) - offsetL;
var isSubmerged = depths[i] < (-Number.MIN_VALUE);
if (i > 0) {
if (isSubmerged) {
if (!lastSubmerged) {
intoIndex = i - 1;
diveCount++;
}
}
else {
if (lastSubmerged) {
outoIndex = i - 1;
diveCount++;
}
}
}
lastSubmerged = isSubmerged;
}
switch (diveCount) {
case 0:
if (lastSubmerged) {
var md = new b2MassData();
this.ComputeMass(md, 1);
c.SetV(b2Math.MulX(xf, md.center));
return md.mass;
}
else {
return 0;
}
break;
case 1:
if (intoIndex == (-1)) {
intoIndex = this.m_vertexCount - 1;
}
else {
outoIndex = this.m_vertexCount - 1;
}
break;
}
var intoIndex2 = parseInt((intoIndex + 1) % this.m_vertexCount);
var outoIndex2 = parseInt((outoIndex + 1) % this.m_vertexCount);
var intoLamdda = (0 - depths[intoIndex]) / (depths[intoIndex2] - depths[intoIndex]);
var outoLamdda = (0 - depths[outoIndex]) / (depths[outoIndex2] - depths[outoIndex]);
var intoVec = new b2Vec2(this.m_vertices[intoIndex].x * (1 - intoLamdda) + this.m_vertices[intoIndex2].x * intoLamdda, this.m_vertices[intoIndex].y * (1 - intoLamdda) + this.m_vertices[intoIndex2].y * intoLamdda);
var outoVec = new b2Vec2(this.m_vertices[outoIndex].x * (1 - outoLamdda) + this.m_vertices[outoIndex2].x * outoLamdda, this.m_vertices[outoIndex].y * (1 - outoLamdda) + this.m_vertices[outoIndex2].y * outoLamdda);
var area = 0;
var center = new b2Vec2();
var p2 = this.m_vertices[intoIndex2];
var p3;
i = intoIndex2;
while (i != outoIndex2) {
i = (i + 1) % this.m_vertexCount;
if (i == outoIndex2) p3 = outoVec;
else p3 = this.m_vertices[i];
var triangleArea = 0.5 * ((p2.x - intoVec.x) * (p3.y - intoVec.y) - (p2.y - intoVec.y) * (p3.x - intoVec.x));
area += triangleArea;
center.x += triangleArea * (intoVec.x + p2.x + p3.x) / 3;
center.y += triangleArea * (intoVec.y + p2.y + p3.y) / 3;
p2 = p3;
}
center.Multiply(1 / area);
c.SetV(b2Math.MulX(xf, center));
return area;
}
b2PolygonShape.prototype.GetVertexCount = function () {
return this.m_vertexCount;
}
b2PolygonShape.prototype.GetVertices = function () {
return this.m_vertices;
}
b2PolygonShape.prototype.GetNormals = function () {
return this.m_normals;
}
b2PolygonShape.prototype.GetSupport = function (d) {
var bestIndex = 0;
var bestValue = this.m_vertices[0].x * d.x + this.m_vertices[0].y * d.y;
for (var i = 1; i < this.m_vertexCount; ++i) {
var value = this.m_vertices[i].x * d.x + this.m_vertices[i].y * d.y;
if (value > bestValue) {
bestIndex = i;
bestValue = value;
}
}
return bestIndex;
}
b2PolygonShape.prototype.GetSupportVertex = function (d) {
var bestIndex = 0;
var bestValue = this.m_vertices[0].x * d.x + this.m_vertices[0].y * d.y;
for (var i = 1; i < this.m_vertexCount; ++i) {
var value = this.m_vertices[i].x * d.x + this.m_vertices[i].y * d.y;
if (value > bestValue) {
bestIndex = i;
bestValue = value;
}
}
return this.m_vertices[bestIndex];
}
b2PolygonShape.prototype.Validate = function () {
return false;
}
b2PolygonShape.prototype.b2PolygonShape = function () {
this.__super.b2Shape.call(this);
this.m_type = this.e_polygonShape;
this.m_centroid = new b2Vec2();
this.m_vertices = new Vector();
this.m_normals = new Vector();
}
b2PolygonShape.prototype.Reserve = function (count) {
if (count === undefined) count = 0;
for (var i = parseInt(this.m_vertices.length); i < count; i++) {
this.m_vertices[i] = new b2Vec2();
this.m_normals[i] = new b2Vec2();
}
}
b2PolygonShape.prototype.ComputeCentroid = function (vs, count) {
if (count === undefined) count = 0;
var c = new b2Vec2();
var area = 0.0;
var p1X = 0.0;
var p1Y = 0.0;
var inv3 = 1.0 / 3.0;
for (var i = 0; i < count; ++i) {
var p2 = vs[i];
var p3 = i + 1 < count ? vs[parseInt(i + 1)] : vs[0];
var e1X = p2.x - p1X;
var e1Y = p2.y - p1Y;
var e2X = p3.x - p1X;
var e2Y = p3.y - p1Y;
var D = (e1X * e2Y - e1Y * e2X);
var triangleArea = 0.5 * D;area += triangleArea;
c.x += triangleArea * inv3 * (p1X + p2.x + p3.x);
c.y += triangleArea * inv3 * (p1Y + p2.y + p3.y);
}
c.x *= 1.0 / area;
c.y *= 1.0 / area;
return c;
}
b2PolygonShape.ComputeCentroid = b2PolygonShape.prototype.ComputeCentroid;
b2PolygonShape.prototype.ComputeOBB = function (obb, vs, count) {
if (count === undefined) count = 0;
var i = 0;
var p = new Vector(count + 1);
for (i = 0;
i < count; ++i) {
p[i] = vs[i];
}
p[count] = p[0];
var minArea = Number.MAX_VALUE;
for (i = 1;
i <= count; ++i) {
var root = p[parseInt(i - 1)];
var uxX = p[i].x - root.x;
var uxY = p[i].y - root.y;
var length = Math.sqrt(uxX * uxX + uxY * uxY);
uxX /= length;
uxY /= length;
var uyX = (-uxY);
var uyY = uxX;
var lowerX = Number.MAX_VALUE;
var lowerY = Number.MAX_VALUE;
var upperX = (-Number.MAX_VALUE);
var upperY = (-Number.MAX_VALUE);
for (var j = 0; j < count; ++j) {
var dX = p[j].x - root.x;
var dY = p[j].y - root.y;
var rX = (uxX * dX + uxY * dY);
var rY = (uyX * dX + uyY * dY);
if (rX < lowerX) lowerX = rX;
if (rY < lowerY) lowerY = rY;
if (rX > upperX) upperX = rX;
if (rY > upperY) upperY = rY;
}
var area = (upperX - lowerX) * (upperY - lowerY);
if (area < 0.95 * minArea) {
minArea = area;
obb.R.col1.x = uxX;
obb.R.col1.y = uxY;
obb.R.col2.x = uyX;
obb.R.col2.y = uyY;
var centerX = 0.5 * (lowerX + upperX);
var centerY = 0.5 * (lowerY + upperY);
var tMat = obb.R;
obb.center.x = root.x + (tMat.col1.x * centerX + tMat.col2.x * centerY);
obb.center.y = root.y + (tMat.col1.y * centerX + tMat.col2.y * centerY);
obb.extents.x = 0.5 * (upperX - lowerX);
obb.extents.y = 0.5 * (upperY - lowerY);
}
}
}
b2PolygonShape.ComputeOBB = b2PolygonShape.prototype.ComputeOBB;
_A2J_postDefs.push(function () {
Box2D.Collision.Shapes.b2PolygonShape.s_mat = new b2Mat22();
Box2D.Collision.Shapes.b2PolygonShape.prototype.s_mat = Box2D.Collision.Shapes.b2PolygonShape.s_mat;
});
b2Shape.b2Shape = function () {};
b2Shape.prototype.Copy = function () {
return null;
}
b2Shape.prototype.Set = function (other) {
this.m_radius = other.m_radius;
}
b2Shape.prototype.GetType = function () {
return this.m_type;
}
b2Shape.prototype.TestPoint = function (xf, p) {
return false;
}
b2Shape.prototype.RayCast = function (output, input, transform) {
return false;
}
b2Shape.prototype.ComputeAABB = function (aabb, xf) {}
b2Shape.prototype.ComputeMass = function (massData, density) {
if (density === undefined) density = 0;
}
b2Shape.prototype.ComputeSubmergedArea = function (normal, offset, xf, c) {
if (offset === undefined) offset = 0;
return 0;
}
b2Shape.prototype.TestOverlap = function (shape1, transform1, shape2, transform2) {
var input = new b2DistanceInput();
input.proxyA = new b2DistanceProxy();
input.proxyA.Set(shape1);
input.proxyB = new b2DistanceProxy();
input.proxyB.Set(shape2);
input.transformA = transform1;
input.transformB = transform2;
input.useRadii = true;
var simplexCache = new b2SimplexCache();
simplexCache.count = 0;
var output = new b2DistanceOutput();
b2Distance.Distance(output, simplexCache, input);
return output.distance < 10.0 * Number.MIN_VALUE;
}
b2Shape.TestOverlap = b2Shape.prototype.TestOverlap;
b2Shape.prototype.b2Shape = function () {
this.m_type = b2Shape.e_unknownShape;
this.m_radius = b2Settings.b2_linearSlop;
}
_A2J_postDefs.push(function () {
Box2D.Collision.Shapes.b2Shape.e_unknownShape = parseInt((-1));
Box2D.Collision.Shapes.b2Shape.prototype.e_unknownShape = Box2D.Collision.Shapes.b2Shape.e_unknownShape;
Box2D.Collision.Shapes.b2Shape.e_circleShape = 0;
Box2D.Collision.Shapes.b2Shape.prototype.e_circleShape = Box2D.Collision.Shapes.b2Shape.e_circleShape;
Box2D.Collision.Shapes.b2Shape.e_polygonShape = 1;
Box2D.Collision.Shapes.b2Shape.prototype.e_polygonShape = Box2D.Collision.Shapes.b2Shape.e_polygonShape;
Box2D.Collision.Shapes.b2Shape.e_edgeShape = 2;
Box2D.Collision.Shapes.b2Shape.prototype.e_edgeShape = Box2D.Collision.Shapes.b2Shape.e_edgeShape;
Box2D.Collision.Shapes.b2Shape.e_shapeTypeCount = 3;
Box2D.Collision.Shapes.b2Shape.prototype.e_shapeTypeCount = Box2D.Collision.Shapes.b2Shape.e_shapeTypeCount;
Box2D.Collision.Shapes.b2Shape.e_hitCollide = 1;
Box2D.Collision.Shapes.b2Shape.prototype.e_hitCollide = Box2D.Collision.Shapes.b2Shape.e_hitCollide;
Box2D.Collision.Shapes.b2Shape.e_missCollide = 0;
Box2D.Collision.Shapes.b2Shape.prototype.e_missCollide = Box2D.Collision.Shapes.b2Shape.e_missCollide;
Box2D.Collision.Shapes.b2Shape.e_startsInsideCollide = parseInt((-1));
Box2D.Collision.Shapes.b2Shape.prototype.e_startsInsideCollide = Box2D.Collision.Shapes.b2Shape.e_startsInsideCollide;
});
})(); /* source: disabled*/
(function () {
var b2Color = Box2D.Common.b2Color;
var b2internal = Box2D.Common.b2internal;
var b2Settings = Box2D.Common.b2Settings;
var b2Mat22 = Box2D.Common.Math.b2Mat22;
var b2Mat33 = Box2D.Common.Math.b2Mat33;
var b2Math = Box2D.Common.Math.b2Math;
var b2Sweep = Box2D.Common.Math.b2Sweep;
var b2Transform = Box2D.Common.Math.b2Transform;
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2Vec3 = Box2D.Common.Math.b2Vec3;
var b2Color = Box2D.Common.b2Color;
var b2internal = Box2D.Common.b2internal;
var b2Settings = Box2D.Common.b2Settings;
var b2internal = Box2D.Common.b2internal;
b2Color.b2Color = function () {
this._r = 0;
this._g = 0;
this._b = 0;
};
b2Color.prototype.b2Color = function (rr, gg, bb) {
if (rr === undefined) rr = 0;
if (gg === undefined) gg = 0;
if (bb === undefined) bb = 0;
this._r = a2j.parseUInt(255 * b2Math.Clamp(rr, 0.0, 1.0));
this._g = a2j.parseUInt(255 * b2Math.Clamp(gg, 0.0, 1.0));
this._b = a2j.parseUInt(255 * b2Math.Clamp(bb, 0.0, 1.0));
}
b2Color.prototype.Set = function (rr, gg, bb) {
if (rr === undefined) rr = 0;
if (gg === undefined) gg = 0;
if (bb === undefined) bb = 0;
this._r = a2j.parseUInt(255 * b2Math.Clamp(rr, 0.0, 1.0));
this._g = a2j.parseUInt(255 * b2Math.Clamp(gg, 0.0, 1.0));
this._b = a2j.parseUInt(255 * b2Math.Clamp(bb, 0.0, 1.0));
}
b2Color.prototype.__defineSetter__('r', function (rr) {
if (rr === undefined) rr = 0;
this._r = a2j.parseUInt(255 * b2Math.Clamp(rr, 0.0, 1.0));
});
b2Color.prototype.__defineSetter__('g', function (gg) {
if (gg === undefined) gg = 0;
this._g = a2j.parseUInt(255 * b2Math.Clamp(gg, 0.0, 1.0));
});
b2Color.prototype.__defineSetter__('b', function (bb) {
if (bb === undefined) bb = 0;
this._b = a2j.parseUInt(255 * b2Math.Clamp(bb, 0.0, 1.0));
});
b2Color.prototype.__defineGetter__('color', function () {
return (this._r << 16) | (this._g << 8) | (this._b);
});
b2Settings.b2Settings = function () {};
b2Settings.prototype.b2MixFriction = function (friction1, friction2) {
if (friction1 === undefined) friction1 = 0;
if (friction2 === undefined) friction2 = 0;
return Math.sqrt(friction1 * friction2);
}
b2Settings.b2MixFriction = b2Settings.prototype.b2MixFriction;
b2Settings.prototype.b2MixRestitution = function (restitution1, restitution2) {
if (restitution1 === undefined) restitution1 = 0;
if (restitution2 === undefined) restitution2 = 0;
return restitution1 > restitution2 ? restitution1 : restitution2;
}
b2Settings.b2MixRestitution = b2Settings.prototype.b2MixRestitution;
b2Settings.prototype.b2Assert = function (a) {
if (!a) {
throw "Assertion Failed";
}
}
b2Settings.b2Assert = b2Settings.prototype.b2Assert;
_A2J_postDefs.push(function () {
Box2D.Common.b2Settings.VERSION = "2.1alpha";
Box2D.Common.b2Settings.prototype.VERSION = Box2D.Common.b2Settings.VERSION;
Box2D.Common.b2Settings.USHRT_MAX = 0x0000ffff;
Box2D.Common.b2Settings.prototype.USHRT_MAX = Box2D.Common.b2Settings.USHRT_MAX;
Box2D.Common.b2Settings.b2_pi = Math.PI;
Box2D.Common.b2Settings.prototype.b2_pi = Box2D.Common.b2Settings.b2_pi;
Box2D.Common.b2Settings.b2_maxManifoldPoints = 2;
Box2D.Common.b2Settings.prototype.b2_maxManifoldPoints = Box2D.Common.b2Settings.b2_maxManifoldPoints;
Box2D.Common.b2Settings.b2_aabbExtension = 0.1;
Box2D.Common.b2Settings.prototype.b2_aabbExtension = Box2D.Common.b2Settings.b2_aabbExtension;
Box2D.Common.b2Settings.b2_aabbMultiplier = 2.0;
Box2D.Common.b2Settings.prototype.b2_aabbMultiplier = Box2D.Common.b2Settings.b2_aabbMultiplier;
Box2D.Common.b2Settings.b2_polygonRadius = 2.0 * b2Settings.b2_linearSlop;
Box2D.Common.b2Settings.prototype.b2_polygonRadius = Box2D.Common.b2Settings.b2_polygonRadius;
Box2D.Common.b2Settings.b2_linearSlop = 0.005;
Box2D.Common.b2Settings.prototype.b2_linearSlop = Box2D.Common.b2Settings.b2_linearSlop;
Box2D.Common.b2Settings.b2_angularSlop = 2.0 / 180.0 * b2Settings.b2_pi;
Box2D.Common.b2Settings.prototype.b2_angularSlop = Box2D.Common.b2Settings.b2_angularSlop;
Box2D.Common.b2Settings.b2_toiSlop = 8.0 * b2Settings.b2_linearSlop;
Box2D.Common.b2Settings.prototype.b2_toiSlop = Box2D.Common.b2Settings.b2_toiSlop;
Box2D.Common.b2Settings.b2_maxTOIContactsPerIsland = 32;
Box2D.Common.b2Settings.prototype.b2_maxTOIContactsPerIsland = Box2D.Common.b2Settings.b2_maxTOIContactsPerIsland;
Box2D.Common.b2Settings.b2_maxTOIJointsPerIsland = 32;
Box2D.Common.b2Settings.prototype.b2_maxTOIJointsPerIsland = Box2D.Common.b2Settings.b2_maxTOIJointsPerIsland;
Box2D.Common.b2Settings.b2_velocityThreshold = 1.0;
Box2D.Common.b2Settings.prototype.b2_velocityThreshold = Box2D.Common.b2Settings.b2_velocityThreshold;
Box2D.Common.b2Settings.b2_maxLinearCorrection = 0.2;
Box2D.Common.b2Settings.prototype.b2_maxLinearCorrection = Box2D.Common.b2Settings.b2_maxLinearCorrection;
Box2D.Common.b2Settings.b2_maxAngularCorrection = 8.0 / 180.0 * b2Settings.b2_pi;
Box2D.Common.b2Settings.prototype.b2_maxAngularCorrection = Box2D.Common.b2Settings.b2_maxAngularCorrection;
Box2D.Common.b2Settings.b2_maxTranslation = 2.0;
Box2D.Common.b2Settings.prototype.b2_maxTranslation = Box2D.Common.b2Settings.b2_maxTranslation;
Box2D.Common.b2Settings.b2_maxTranslationSquared = b2Settings.b2_maxTranslation * b2Settings.b2_maxTranslation;
Box2D.Common.b2Settings.prototype.b2_maxTranslationSquared = Box2D.Common.b2Settings.b2_maxTranslationSquared;
Box2D.Common.b2Settings.b2_maxRotation = 0.5 * b2Settings.b2_pi;
Box2D.Common.b2Settings.prototype.b2_maxRotation = Box2D.Common.b2Settings.b2_maxRotation;
Box2D.Common.b2Settings.b2_maxRotationSquared = b2Settings.b2_maxRotation * b2Settings.b2_maxRotation;
Box2D.Common.b2Settings.prototype.b2_maxRotationSquared = Box2D.Common.b2Settings.b2_maxRotationSquared;
Box2D.Common.b2Settings.b2_contactBaumgarte = 0.2;
Box2D.Common.b2Settings.prototype.b2_contactBaumgarte = Box2D.Common.b2Settings.b2_contactBaumgarte;
Box2D.Common.b2Settings.b2_timeToSleep = 0.5;
Box2D.Common.b2Settings.prototype.b2_timeToSleep = Box2D.Common.b2Settings.b2_timeToSleep;
Box2D.Common.b2Settings.b2_linearSleepTolerance = 0.01;
Box2D.Common.b2Settings.prototype.b2_linearSleepTolerance = Box2D.Common.b2Settings.b2_linearSleepTolerance;
Box2D.Common.b2Settings.b2_angularSleepTolerance = 2.0 / 180.0 * b2Settings.b2_pi;
Box2D.Common.b2Settings.prototype.b2_angularSleepTolerance = Box2D.Common.b2Settings.b2_angularSleepTolerance;
});
})(); /* source: disabled*/
(function () {
var b2AABB = Box2D.Collision.b2AABB;
var b2Color = Box2D.Common.b2Color;
var b2internal = Box2D.Common.b2internal;
var b2Settings = Box2D.Common.b2Settings;
var b2Mat22 = Box2D.Common.Math.b2Mat22;
var b2Mat33 = Box2D.Common.Math.b2Mat33;
var b2Math = Box2D.Common.Math.b2Math;
var b2Sweep = Box2D.Common.Math.b2Sweep;
var b2Transform = Box2D.Common.Math.b2Transform;
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2Vec3 = Box2D.Common.Math.b2Vec3;
b2Mat22.b2Mat22 = function () {
this.col1 = new b2Vec2();
this.col2 = new b2Vec2();
};
b2Mat22.prototype.b2Mat22 = function () {
this.SetIdentity();
}
b2Mat22.prototype.FromAngle = function (angle) {
if (angle === undefined) angle = 0;
var mat = new b2Mat22();
mat.Set(angle);
return mat;
}
b2Mat22.FromAngle = b2Mat22.prototype.FromAngle;
b2Mat22.prototype.FromVV = function (c1, c2) {
var mat = new b2Mat22();
mat.SetVV(c1, c2);
return mat;
}
b2Mat22.FromVV = b2Mat22.prototype.FromVV;
b2Mat22.prototype.Set = function (angle) {
if (angle === undefined) angle = 0;
var c = Math.cos(angle);
var s = Math.sin(angle);
this.col1.x = c;
this.col2.x = (-s);
this.col1.y = s;
this.col2.y = c;
}
b2Mat22.prototype.SetVV = function (c1, c2) {
this.col1.SetV(c1);
this.col2.SetV(c2);
}
b2Mat22.prototype.Copy = function () {
var mat = new b2Mat22();
mat.SetM(this);
return mat;
}
b2Mat22.prototype.SetM = function (m) {
this.col1.SetV(m.col1);
this.col2.SetV(m.col2);
}
b2Mat22.prototype.AddM = function (m) {
this.col1.x += m.col1.x;
this.col1.y += m.col1.y;
this.col2.x += m.col2.x;
this.col2.y += m.col2.y;
}
b2Mat22.prototype.SetIdentity = function () {
this.col1.x = 1.0;
this.col2.x = 0.0;
this.col1.y = 0.0;
this.col2.y = 1.0;
}
b2Mat22.prototype.SetZero = function () {
this.col1.x = 0.0;
this.col2.x = 0.0;
this.col1.y = 0.0;
this.col2.y = 0.0;
}
b2Mat22.prototype.GetAngle = function () {
return Math.atan2(this.col1.y, this.col1.x);
}
b2Mat22.prototype.GetInverse = function (out) {
var a = this.col1.x;
var b = this.col2.x;
var c = this.col1.y;
var d = this.col2.y;
var det = a * d - b * c;
if (det != 0.0) {
det = 1.0 / det;
}
out.col1.x = det * d;
out.col2.x = (-det * b);
out.col1.y = (-det * c);
out.col2.y = det * a;
return out;
}
b2Mat22.prototype.Solve = function (out, bX, bY) {
if (bX === undefined) bX = 0;
if (bY === undefined) bY = 0;
var a11 = this.col1.x;
var a12 = this.col2.x;
var a21 = this.col1.y;
var a22 = this.col2.y;
var det = a11 * a22 - a12 * a21;
if (det != 0.0) {
det = 1.0 / det;
}
out.x = det * (a22 * bX - a12 * bY);
out.y = det * (a11 * bY - a21 * bX);
return out;
}
b2Mat22.prototype.Abs = function () {
this.col1.Abs();
this.col2.Abs();
}
b2Mat33.b2Mat33 = function () {
this.col1 = new b2Vec3();
this.col2 = new b2Vec3();
this.col3 = new b2Vec3();
};
b2Mat33.prototype.b2Mat33 = function (c1, c2, c3) {
if (c1 === undefined) c1 = null;
if (c2 === undefined) c2 = null;
if (c3 === undefined) c3 = null;
if (!c1 && !c2 && !c3) {
this.col1.SetZero();
this.col2.SetZero();
this.col3.SetZero();
}
else {
this.col1.SetV(c1);
this.col2.SetV(c2);
this.col3.SetV(c3);
}
}
b2Mat33.prototype.SetVVV = function (c1, c2, c3) {
this.col1.SetV(c1);
this.col2.SetV(c2);
this.col3.SetV(c3);
}
b2Mat33.prototype.Copy = function () {
return new b2Mat33(this.col1, this.col2, this.col3);
}
b2Mat33.prototype.SetM = function (m) {
this.col1.SetV(m.col1);
this.col2.SetV(m.col2);
this.col3.SetV(m.col3);
}
b2Mat33.prototype.AddM = function (m) {
this.col1.x += m.col1.x;
this.col1.y += m.col1.y;
this.col1.z += m.col1.z;
this.col2.x += m.col2.x;
this.col2.y += m.col2.y;
this.col2.z += m.col2.z;
this.col3.x += m.col3.x;
this.col3.y += m.col3.y;
this.col3.z += m.col3.z;
}
b2Mat33.prototype.SetIdentity = function () {
this.col1.x = 1.0;
this.col2.x = 0.0;
this.col3.x = 0.0;
this.col1.y = 0.0;
this.col2.y = 1.0;
this.col3.y = 0.0;
this.col1.z = 0.0;
this.col2.z = 0.0;
this.col3.z = 1.0;
}
b2Mat33.prototype.SetZero = function () {
this.col1.x = 0.0;
this.col2.x = 0.0;
this.col3.x = 0.0;
this.col1.y = 0.0;
this.col2.y = 0.0;
this.col3.y = 0.0;
this.col1.z = 0.0;
this.col2.z = 0.0;
this.col3.z = 0.0;
}
b2Mat33.prototype.Solve22 = function (out, bX, bY) {
if (bX === undefined) bX = 0;
if (bY === undefined) bY = 0;
var a11 = this.col1.x;
var a12 = this.col2.x;
var a21 = this.col1.y;
var a22 = this.col2.y;
var det = a11 * a22 - a12 * a21;
if (det != 0.0) {
det = 1.0 / det;
}
out.x = det * (a22 * bX - a12 * bY);
out.y = det * (a11 * bY - a21 * bX);
return out;
}
b2Mat33.prototype.Solve33 = function (out, bX, bY, bZ) {
if (bX === undefined) bX = 0;
if (bY === undefined) bY = 0;
if (bZ === undefined) bZ = 0;
var a11 = this.col1.x;
var a21 = this.col1.y;
var a31 = this.col1.z;
var a12 = this.col2.x;
var a22 = this.col2.y;
var a32 = this.col2.z;
var a13 = this.col3.x;
var a23 = this.col3.y;
var a33 = this.col3.z;
var det = a11 * (a22 * a33 - a32 * a23) + a21 * (a32 * a13 - a12 * a33) + a31 * (a12 * a23 - a22 * a13);
if (det != 0.0) {
det = 1.0 / det;
}
out.x = det * (bX * (a22 * a33 - a32 * a23) + bY * (a32 * a13 - a12 * a33) + bZ * (a12 * a23 - a22 * a13));
out.y = det * (a11 * (bY * a33 - bZ * a23) + a21 * (bZ * a13 - bX * a33) + a31 * (bX * a23 - bY * a13));
out.z = det * (a11 * (a22 * bZ - a32 * bY) + a21 * (a32 * bX - a12 * bZ) + a31 * (a12 * bY - a22 * bX));
return out;
}
b2Math.b2Math = function () {};
b2Math.prototype.IsValid = function (x) {
if (x === undefined) x = 0;
return isFinite(x);
}
b2Math.IsValid = b2Math.prototype.IsValid;
b2Math.prototype.Dot = function (a, b) {
return a.x * b.x + a.y * b.y;
}
b2Math.Dot = b2Math.prototype.Dot;
b2Math.prototype.CrossVV = function (a, b) {
return a.x * b.y - a.y * b.x;
}
b2Math.CrossVV = b2Math.prototype.CrossVV;
b2Math.prototype.CrossVF = function (a, s) {
if (s === undefined) s = 0;
var v = new b2Vec2(s * a.y, (-s * a.x));
return v;
}
b2Math.CrossVF = b2Math.prototype.CrossVF;
b2Math.prototype.CrossFV = function (s, a) {
if (s === undefined) s = 0;
var v = new b2Vec2((-s * a.y), s * a.x);
return v;
}
b2Math.CrossFV = b2Math.prototype.CrossFV;
b2Math.prototype.MulMV = function (A, v) {
var u = new b2Vec2(A.col1.x * v.x + A.col2.x * v.y, A.col1.y * v.x + A.col2.y * v.y);
return u;
}
b2Math.MulMV = b2Math.prototype.MulMV;
b2Math.prototype.MulTMV = function (A, v) {
var u = new b2Vec2(this.Dot(v, A.col1), this.Dot(v, A.col2));
return u;
}
b2Math.MulTMV = b2Math.prototype.MulTMV;
b2Math.prototype.MulX = function (T, v) {
var a = this.MulMV(T.R, v);
a.x += T.position.x;
a.y += T.position.y;
return a;
}
b2Math.MulX = b2Math.prototype.MulX;
b2Math.prototype.MulXT = function (T, v) {
var a = this.SubtractVV(v, T.position);
var tX = (a.x * T.R.col1.x + a.y * T.R.col1.y);
a.y = (a.x * T.R.col2.x + a.y * T.R.col2.y);
a.x = tX;
return a;
}
b2Math.MulXT = b2Math.prototype.MulXT;
b2Math.prototype.AddVV = function (a, b) {
var v = new b2Vec2(a.x + b.x, a.y + b.y);
return v;
}
b2Math.AddVV = b2Math.prototype.AddVV;
b2Math.prototype.SubtractVV = function (a, b) {
var v = new b2Vec2(a.x - b.x, a.y - b.y);
return v;
}
b2Math.SubtractVV = b2Math.prototype.SubtractVV;
b2Math.prototype.Distance = function (a, b) {
var cX = a.x - b.x;
var cY = a.y - b.y;
return Math.sqrt(cX * cX + cY * cY);
}
b2Math.Distance = b2Math.prototype.Distance;
b2Math.prototype.DistanceSquared = function (a, b) {
var cX = a.x - b.x;
var cY = a.y - b.y;
return (cX * cX + cY * cY);
}
b2Math.DistanceSquared = b2Math.prototype.DistanceSquared;
b2Math.prototype.MulFV = function (s, a) {
if (s === undefined) s = 0;
var v = new b2Vec2(s * a.x, s * a.y);
return v;
}
b2Math.MulFV = b2Math.prototype.MulFV;
b2Math.prototype.AddMM = function (A, B) {
var C = b2Mat22.FromVV(this.AddVV(A.col1, B.col1), this.AddVV(A.col2, B.col2));
return C;
}
b2Math.AddMM = b2Math.prototype.AddMM;
b2Math.prototype.MulMM = function (A, B) {
var C = b2Mat22.FromVV(this.MulMV(A, B.col1), this.MulMV(A, B.col2));
return C;
}
b2Math.MulMM = b2Math.prototype.MulMM;
b2Math.prototype.MulTMM = function (A, B) {
var c1 = new b2Vec2(this.Dot(A.col1, B.col1), this.Dot(A.col2, B.col1));
var c2 = new b2Vec2(this.Dot(A.col1, B.col2), this.Dot(A.col2, B.col2));
var C = b2Mat22.FromVV(c1, c2);
return C;
}
b2Math.MulTMM = b2Math.prototype.MulTMM;
b2Math.prototype.Abs = function (a) {
if (a === undefined) a = 0;
return a > 0.0 ? a : (-a);
}
b2Math.Abs = b2Math.prototype.Abs;
b2Math.prototype.AbsV = function (a) {
var b = new b2Vec2(this.Abs(a.x), this.Abs(a.y));
return b;
}
b2Math.AbsV = b2Math.prototype.AbsV;
b2Math.prototype.AbsM = function (A) {
var B = b2Mat22.FromVV(this.AbsV(A.col1), this.AbsV(A.col2));
return B;
}
b2Math.AbsM = b2Math.prototype.AbsM;
b2Math.prototype.Min = function (a, b) {
if (a === undefined) a = 0;
if (b === undefined) b = 0;
return a < b ? a : b;
}
b2Math.Min = b2Math.prototype.Min;
b2Math.prototype.MinV = function (a, b) {
var c = new b2Vec2(this.Min(a.x, b.x), this.Min(a.y, b.y));
return c;
}
b2Math.MinV = b2Math.prototype.MinV;
b2Math.prototype.Max = function (a, b) {
if (a === undefined) a = 0;
if (b === undefined) b = 0;
return a > b ? a : b;
}
b2Math.Max = b2Math.prototype.Max;
b2Math.prototype.MaxV = function (a, b) {
var c = new b2Vec2(this.Max(a.x, b.x), this.Max(a.y, b.y));
return c;
}
b2Math.MaxV = b2Math.prototype.MaxV;
b2Math.prototype.Clamp = function (a, low, high) {
if (a === undefined) a = 0;
if (low === undefined) low = 0;
if (high === undefined) high = 0;
return a < low ? low : a > high ? high : a;
}
b2Math.Clamp = b2Math.prototype.Clamp;
b2Math.prototype.ClampV = function (a, low, high) {
return this.MaxV(low, this.MinV(a, high));
}
b2Math.ClampV = b2Math.prototype.ClampV;
b2Math.prototype.Swap = function (a, b) {
var tmp = a[0];
a[0] = b[0];
b[0] = tmp;
}
b2Math.Swap = b2Math.prototype.Swap;
b2Math.prototype.Random = function () {
return Math.random() * 2 - 1;
}
b2Math.Random = b2Math.prototype.Random;
b2Math.prototype.RandomRange = function (lo, hi) {
if (lo === undefined) lo = 0;
if (hi === undefined) hi = 0;
var r = Math.random();
r = (hi - lo) * r + lo;
return r;
}
b2Math.RandomRange = b2Math.prototype.RandomRange;
b2Math.prototype.NextPowerOfTwo = function (x) {
if (x === undefined) x = 0;
x |= (x >> 1) & 0x7FFFFFFF;
x |= (x >> 2) & 0x3FFFFFFF;
x |= (x >> 4) & 0x0FFFFFFF;
x |= (x >> 8) & 0x00FFFFFF;
x |= (x >> 16) & 0x0000FFFF;
return x + 1;
}
b2Math.NextPowerOfTwo = b2Math.prototype.NextPowerOfTwo;
b2Math.prototype.IsPowerOfTwo = function (x) {
if (x === undefined) x = 0;
var result = x > 0 && (x & (x - 1)) == 0;
return result;
}
b2Math.IsPowerOfTwo = b2Math.prototype.IsPowerOfTwo;
_A2J_postDefs.push(function () {
Box2D.Common.Math.b2Math.b2Vec2_zero = new b2Vec2(0.0, 0.0);
Box2D.Common.Math.b2Math.prototype.b2Vec2_zero = Box2D.Common.Math.b2Math.b2Vec2_zero;
Box2D.Common.Math.b2Math.b2Mat22_identity = b2Mat22.FromVV(new b2Vec2(1.0, 0.0), new b2Vec2(0.0, 1.0));
Box2D.Common.Math.b2Math.prototype.b2Mat22_identity = Box2D.Common.Math.b2Math.b2Mat22_identity;
Box2D.Common.Math.b2Math.b2Transform_identity = new b2Transform(b2Math.b2Vec2_zero, b2Math.b2Mat22_identity);
Box2D.Common.Math.b2Math.prototype.b2Transform_identity = Box2D.Common.Math.b2Math.b2Transform_identity;
});
b2Sweep.b2Sweep = function () {
this.localCenter = new b2Vec2();
this.c0 = new b2Vec2;
this.c = new b2Vec2();
};
b2Sweep.prototype.Set = function (other) {
this.localCenter.SetV(other.localCenter);
this.c0.SetV(other.c0);
this.c.SetV(other.c);
this.a0 = other.a0;
this.a = other.a;
this.t0 = other.t0;
}
b2Sweep.prototype.Copy = function () {
var copy = new b2Sweep();
copy.localCenter.SetV(this.localCenter);
copy.c0.SetV(this.c0);
copy.c.SetV(this.c);
copy.a0 = this.a0;
copy.a = this.a;
copy.t0 = this.t0;
return copy;
}
b2Sweep.prototype.GetTransform = function (xf, alpha) {
if (alpha === undefined) alpha = 0;
xf.position.x = (1.0 - alpha) * this.c0.x + alpha * this.c.x;
xf.position.y = (1.0 - alpha) * this.c0.y + alpha * this.c.y;
var angle = (1.0 - alpha) * this.a0 + alpha * this.a;
xf.R.Set(angle);
var tMat = xf.R;
xf.position.x -= (tMat.col1.x * this.localCenter.x + tMat.col2.x * this.localCenter.y);
xf.position.y -= (tMat.col1.y * this.localCenter.x + tMat.col2.y * this.localCenter.y);
}
b2Sweep.prototype.Advance = function (t) {
if (t === undefined) t = 0;
if (this.t0 < t && 1.0 - this.t0 > Number.MIN_VALUE) {
var alpha = (t - this.t0) / (1.0 - this.t0);
this.c0.x = (1.0 - alpha) * this.c0.x + alpha * this.c.x;
this.c0.y = (1.0 - alpha) * this.c0.y + alpha * this.c.y;
this.a0 = (1.0 - alpha) * this.a0 + alpha * this.a;
this.t0 = t;
}
}
b2Transform.b2Transform = function () {
this.position = new b2Vec2;
this.R = new b2Mat22();
};
b2Transform.prototype.b2Transform = function (pos, r) {
if (pos === undefined) pos = null;
if (r === undefined) r = null;
if (pos) {
this.position.SetV(pos);
this.R.SetM(r);
}
}
b2Transform.prototype.Initialize = function (pos, r) {
this.position.SetV(pos);
this.R.SetM(r);
}
b2Transform.prototype.SetIdentity = function () {
this.position.SetZero();
this.R.SetIdentity();
}
b2Transform.prototype.Set = function (x) {
this.position.SetV(x.position);
this.R.SetM(x.R);
}
b2Transform.prototype.GetAngle = function () {
return Math.atan2(this.R.col1.y, this.R.col1.x);
}
b2Vec2.b2Vec2 = function () {};
b2Vec2.prototype.b2Vec2 = function (x_, y_) {
if (x_ === undefined) x_ = 0;
if (y_ === undefined) y_ = 0;
this.x = x_;
this.y = y_;
}
b2Vec2.prototype.SetZero = function () {
this.x = 0.0;
this.y = 0.0;
}
b2Vec2.prototype.Set = function (x_, y_) {
if (x_ === undefined) x_ = 0;
if (y_ === undefined) y_ = 0;
this.x = x_;
this.y = y_;
}
b2Vec2.prototype.SetV = function (v) {
this.x = v.x;
this.y = v.y;
}
b2Vec2.prototype.GetNegative = function () {
return new b2Vec2((-this.x), (-this.y));
}
b2Vec2.prototype.NegativeSelf = function () {
this.x = (-this.x);
this.y = (-this.y);
}
b2Vec2.prototype.Make = function (x_, y_) {
if (x_ === undefined) x_ = 0;
if (y_ === undefined) y_ = 0;
return new b2Vec2(x_, y_);
}
b2Vec2.Make = b2Vec2.prototype.Make;
b2Vec2.prototype.Copy = function () {
return new b2Vec2(this.x, this.y);
}
b2Vec2.prototype.Add = function (v) {
this.x += v.x;
this.y += v.y;
}
b2Vec2.prototype.Subtract = function (v) {
this.x -= v.x;
this.y -= v.y;
}
b2Vec2.prototype.Multiply = function (a) {
if (a === undefined) a = 0;
this.x *= a;
this.y *= a;
}
b2Vec2.prototype.MulM = function (A) {
var tX = this.x;
this.x = A.col1.x * tX + A.col2.x * this.y;
this.y = A.col1.y * tX + A.col2.y * this.y;
}
b2Vec2.prototype.MulTM = function (A) {
var tX = b2Math.Dot(this, A.col1);
this.y = b2Math.Dot(this, A.col2);
this.x = tX;
}
b2Vec2.prototype.CrossVF = function (s) {
if (s === undefined) s = 0;
var tX = this.x;
this.x = s * this.y;
this.y = (-s * tX);
}
b2Vec2.prototype.CrossFV = function (s) {
if (s === undefined) s = 0;
var tX = this.x;
this.x = (-s * this.y);
this.y = s * tX;
}
b2Vec2.prototype.MinV = function (b) {
this.x = this.x < b.x ? this.x : b.x;
this.y = this.y < b.y ? this.y : b.y;
}
b2Vec2.prototype.MaxV = function (b) {
this.x = this.x > b.x ? this.x : b.x;
this.y = this.y > b.y ? this.y : b.y;
}
b2Vec2.prototype.Abs = function () {
if (this.x < 0) this.x = (-this.x);
if (this.y < 0) this.y = (-this.y);
}
b2Vec2.prototype.Length = function () {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
b2Vec2.prototype.LengthSquared = function () {
return (this.x * this.x + this.y * this.y);
}
b2Vec2.prototype.Normalize = function () {
var length = Math.sqrt(this.x * this.x + this.y * this.y);
if (length < Number.MIN_VALUE) {
return 0.0;
}
var invLength = 1.0 / length;
this.x *= invLength;
this.y *= invLength;
return length;
}
b2Vec2.prototype.IsValid = function () {
return b2Math.IsValid(this.x) && b2Math.IsValid(this.y);
}
b2Vec3.b2Vec3 = function () {};
b2Vec3.prototype.b2Vec3 = function (x, y, z) {
if (x === undefined) x = 0;
if (y === undefined) y = 0;
if (z === undefined) z = 0;
this.x = x;
this.y = y;
this.z = z;
}
b2Vec3.prototype.SetZero = function () {
this.x = this.y = this.z = 0.0;
}
b2Vec3.prototype.Set = function (x, y, z) {
if (x === undefined) x = 0;
if (y === undefined) y = 0;
if (z === undefined) z = 0;
this.x = x;
this.y = y;
this.z = z;
}
b2Vec3.prototype.SetV = function (v) {
this.x = v.x;
this.y = v.y;
this.z = v.z;
}
b2Vec3.prototype.GetNegative = function () {
return new b2Vec3((-this.x), (-this.y), (-this.z));
}
b2Vec3.prototype.NegativeSelf = function () {
this.x = (-this.x);
this.y = (-this.y);
this.z = (-this.z);
}
b2Vec3.prototype.Copy = function () {
return new b2Vec3(this.x, this.y, this.z);
}
b2Vec3.prototype.Add = function (v) {
this.x += v.x;
this.y += v.y;
this.z += v.z;
}
b2Vec3.prototype.Subtract = function (v) {
this.x -= v.x;
this.y -= v.y;
this.z -= v.z;
}
b2Vec3.prototype.Multiply = function (a) {
if (a === undefined) a = 0;
this.x *= a;
this.y *= a;
this.z *= a;
}
})(); /* source: disabled*/
(function () {
var b2ControllerEdge = Box2D.Dynamics.Controllers.b2ControllerEdge;
var b2Mat22 = Box2D.Common.Math.b2Mat22;
var b2Mat33 = Box2D.Common.Math.b2Mat33;
var b2Math = Box2D.Common.Math.b2Math;
var b2Sweep = Box2D.Common.Math.b2Sweep;
var b2Transform = Box2D.Common.Math.b2Transform;
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2Vec3 = Box2D.Common.Math.b2Vec3;
var b2Color = Box2D.Common.b2Color;
var b2internal = Box2D.Common.b2internal;
var b2Settings = Box2D.Common.b2Settings;
var b2AABB = Box2D.Collision.b2AABB;
var b2Bound = Box2D.Collision.b2Bound;
var b2BoundValues = Box2D.Collision.b2BoundValues;
var b2BroadPhase = Box2D.Collision.b2BroadPhase;
var b2Collision = Box2D.Collision.b2Collision;
var b2ContactID = Box2D.Collision.b2ContactID;
var b2ContactPoint = Box2D.Collision.b2ContactPoint;
var b2Distance = Box2D.Collision.b2Distance;
var b2DistanceInput = Box2D.Collision.b2DistanceInput;
var b2DistanceOutput = Box2D.Collision.b2DistanceOutput;
var b2DistanceProxy = Box2D.Collision.b2DistanceProxy;
var b2DynamicTree = Box2D.Collision.b2DynamicTree;
var b2DynamicTreeBroadPhase = Box2D.Collision.b2DynamicTreeBroadPhase;
var b2DynamicTreeNode = Box2D.Collision.b2DynamicTreeNode;
var b2DynamicTreePair = Box2D.Collision.b2DynamicTreePair;
var b2Manifold = Box2D.Collision.b2Manifold;
var b2ManifoldPoint = Box2D.Collision.b2ManifoldPoint;
var b2OBB = Box2D.Collision.b2OBB;
var b2Pair = Box2D.Collision.b2Pair;
var b2PairManager = Box2D.Collision.b2PairManager;
var b2Point = Box2D.Collision.b2Point;
var b2Proxy = Box2D.Collision.b2Proxy;
var b2RayCastInput = Box2D.Collision.b2RayCastInput;
var b2RayCastOutput = Box2D.Collision.b2RayCastOutput;
var b2Segment = Box2D.Collision.b2Segment;
var b2SeparationFunction = Box2D.Collision.b2SeparationFunction;
var b2Simplex = Box2D.Collision.b2Simplex;
var b2SimplexCache = Box2D.Collision.b2SimplexCache;
var b2SimplexVertex = Box2D.Collision.b2SimplexVertex;
var b2TimeOfImpact = Box2D.Collision.b2TimeOfImpact;
var b2TOIInput = Box2D.Collision.b2TOIInput;
var b2WorldManifold = Box2D.Collision.b2WorldManifold;
var ClipVertex = Box2D.Collision.ClipVertex;
var Features = Box2D.Collision.Features;
var IBroadPhase = Box2D.Collision.IBroadPhase;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2EdgeChainDef = Box2D.Collision.Shapes.b2EdgeChainDef;
var b2EdgeShape = Box2D.Collision.Shapes.b2EdgeShape;
var b2MassData = Box2D.Collision.Shapes.b2MassData;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2Shape = Box2D.Collision.Shapes.b2Shape;
var b2Body = Box2D.Dynamics.b2Body;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2ContactFilter = Box2D.Dynamics.b2ContactFilter;
var b2ContactImpulse = Box2D.Dynamics.b2ContactImpulse;
var b2ContactListener = Box2D.Dynamics.b2ContactListener;
var b2ContactManager = Box2D.Dynamics.b2ContactManager;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var b2DestructionListener = Box2D.Dynamics.b2DestructionListener;
var b2FilterData = Box2D.Dynamics.b2FilterData;
var b2Fixture = Box2D.Dynamics.b2Fixture;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2Island = Box2D.Dynamics.b2Island;
var b2TimeStep = Box2D.Dynamics.b2TimeStep;
var b2World = Box2D.Dynamics.b2World;
var b2CircleContact = Box2D.Dynamics.Contacts.b2CircleContact;
var b2Contact = Box2D.Dynamics.Contacts.b2Contact;
var b2ContactConstraint = Box2D.Dynamics.Contacts.b2ContactConstraint;
var b2ContactConstraintPoint = Box2D.Dynamics.Contacts.b2ContactConstraintPoint;
var b2ContactEdge = Box2D.Dynamics.Contacts.b2ContactEdge;
var b2ContactFactory = Box2D.Dynamics.Contacts.b2ContactFactory;
var b2ContactRegister = Box2D.Dynamics.Contacts.b2ContactRegister;
var b2ContactResult = Box2D.Dynamics.Contacts.b2ContactResult;
var b2ContactSolver = Box2D.Dynamics.Contacts.b2ContactSolver;
var b2EdgeAndCircleContact = Box2D.Dynamics.Contacts.b2EdgeAndCircleContact;
var b2NullContact = Box2D.Dynamics.Contacts.b2NullContact;
var b2PolyAndCircleContact = Box2D.Dynamics.Contacts.b2PolyAndCircleContact;
var b2PolyAndEdgeContact = Box2D.Dynamics.Contacts.b2PolyAndEdgeContact;
var b2PolygonContact = Box2D.Dynamics.Contacts.b2PolygonContact;
var b2PositionSolverManifold = Box2D.Dynamics.Contacts.b2PositionSolverManifold;
var b2Controller = Box2D.Dynamics.Controllers.b2Controller;
var b2ControllerEdge = Box2D.Dynamics.Controllers.b2ControllerEdge;
var b2DistanceJoint = Box2D.Dynamics.Joints.b2DistanceJoint;
var b2DistanceJointDef = Box2D.Dynamics.Joints.b2DistanceJointDef;
var b2FrictionJoint = Box2D.Dynamics.Joints.b2FrictionJoint;
var b2FrictionJointDef = Box2D.Dynamics.Joints.b2FrictionJointDef;
var b2GearJoint = Box2D.Dynamics.Joints.b2GearJoint;
var b2GearJointDef = Box2D.Dynamics.Joints.b2GearJointDef;
var b2Jacobian = Box2D.Dynamics.Joints.b2Jacobian;
var b2Joint = Box2D.Dynamics.Joints.b2Joint;
var b2JointDef = Box2D.Dynamics.Joints.b2JointDef;
var b2JointEdge = Box2D.Dynamics.Joints.b2JointEdge;
var b2LineJoint = Box2D.Dynamics.Joints.b2LineJoint;
var b2LineJointDef = Box2D.Dynamics.Joints.b2LineJointDef;
var b2MouseJoint = Box2D.Dynamics.Joints.b2MouseJoint;
var b2MouseJointDef = Box2D.Dynamics.Joints.b2MouseJointDef;
var b2PrismaticJoint = Box2D.Dynamics.Joints.b2PrismaticJoint;
var b2PrismaticJointDef = Box2D.Dynamics.Joints.b2PrismaticJointDef;
var b2PulleyJoint = Box2D.Dynamics.Joints.b2PulleyJoint;
var b2PulleyJointDef = Box2D.Dynamics.Joints.b2PulleyJointDef;
var b2RevoluteJoint = Box2D.Dynamics.Joints.b2RevoluteJoint;
var b2RevoluteJointDef = Box2D.Dynamics.Joints.b2RevoluteJointDef;
var b2WeldJoint = Box2D.Dynamics.Joints.b2WeldJoint;
var b2WeldJointDef = Box2D.Dynamics.Joints.b2WeldJointDef;
var b2internal = Box2D.Common.b2internal;
var b2Body = Box2D.Dynamics.b2Body;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2ContactFilter = Box2D.Dynamics.b2ContactFilter;
var b2ContactImpulse = Box2D.Dynamics.b2ContactImpulse;
var b2ContactListener = Box2D.Dynamics.b2ContactListener;
var b2ContactManager = Box2D.Dynamics.b2ContactManager;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var b2DestructionListener = Box2D.Dynamics.b2DestructionListener;
var b2FilterData = Box2D.Dynamics.b2FilterData;
var b2Fixture = Box2D.Dynamics.b2Fixture;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2Island = Box2D.Dynamics.b2Island;
var b2TimeStep = Box2D.Dynamics.b2TimeStep;
var b2World = Box2D.Dynamics.b2World;
b2Body.b2Body = function () {
this.m_xf = new b2Transform();
this.m_sweep = new b2Sweep();
this.m_linearVelocity = new b2Vec2();
this.m_force = new b2Vec2();
};
b2Body.prototype.connectEdges = function (s1, s2, angle1) {
if (angle1 === undefined) angle1 = 0;
var angle2 = Math.atan2(s2.GetDirectionVector().y, s2.GetDirectionVector().x);
var coreOffset = Math.tan((angle2 - angle1) * 0.5);
var core = b2Math.MulFV(coreOffset, s2.GetDirectionVector());
core = b2Math.SubtractVV(core, s2.GetNormalVector());
core = b2Math.MulFV(b2Settings.b2_toiSlop, core);
core = b2Math.AddVV(core, s2.GetVertex1());
var cornerDir = b2Math.AddVV(s1.GetDirectionVector(), s2.GetDirectionVector());
cornerDir.Normalize();
var convex = b2Math.Dot(s1.GetDirectionVector(), s2.GetNormalVector()) > 0.0;
s1.SetNextEdge(s2, core, cornerDir, convex);
s2.SetPrevEdge(s1, core, cornerDir, convex);
return angle2;
}
b2Body.prototype.CreateFixture = function (def) {
if (this.m_world.IsLocked() == true) {
return null;
}
var fixture = new b2Fixture();
fixture.Create(this, this.m_xf, def);
if (this.m_flags & b2Body.e_activeFlag) {
var broadPhase = this.m_world.m_contactManager.m_broadPhase;
fixture.CreateProxy(broadPhase, this.m_xf);
}
fixture.m_next = this.m_fixtureList;
this.m_fixtureList = fixture;
++this.m_fixtureCount;
fixture.m_body = this;
if (fixture.m_density > 0.0) {
this.ResetMassData();
}
this.m_world.m_flags |= b2World.e_newFixture;
return fixture;
}
b2Body.prototype.CreateFixture2 = function (shape, density) {
if (density === undefined) density = 0.0;
var def = new b2FixtureDef();
def.shape = shape;
def.density = density;
return this.CreateFixture(def);
}
b2Body.prototype.DestroyFixture = function (fixture) {
if (this.m_world.IsLocked() == true) {
return;
}
var node = this.m_fixtureList;
var ppF = null;
var found = false;
while (node != null) {
if (node == fixture) {
if (ppF) ppF.m_next = fixture.m_next;
else this.m_fixtureList = fixture.m_next;
found = true;
break;
}
ppF = node;
node = node.m_next;
}
var edge = this.m_contactList;
while (edge) {
var c = edge.contact;
edge = edge.next;
var fixtureA = c.GetFixtureA();
var fixtureB = c.GetFixtureB();
if (fixture == fixtureA || fixture == fixtureB) {
this.m_world.m_contactManager.Destroy(c);
}
}
if (this.m_flags & b2Body.e_activeFlag) {
var broadPhase = this.m_world.m_contactManager.m_broadPhase;
fixture.DestroyProxy(broadPhase);
}
else {}
fixture.Destroy();
fixture.m_body = null;
fixture.m_next = null;
--this.m_fixtureCount;
this.ResetMassData();
}
b2Body.prototype.SetPositionAndAngle = function (position, angle) {
if (angle === undefined) angle = 0;
var f;
if (this.m_world.IsLocked() == true) {
return;
}
this.m_xf.R.Set(angle);
this.m_xf.position.SetV(position);
var tMat = this.m_xf.R;
var tVec = this.m_sweep.localCenter;
this.m_sweep.c.x = (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
this.m_sweep.c.y = (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
this.m_sweep.c.x += this.m_xf.position.x;
this.m_sweep.c.y += this.m_xf.position.y;
this.m_sweep.c0.SetV(this.m_sweep.c);
this.m_sweep.a0 = this.m_sweep.a = angle;
var broadPhase = this.m_world.m_contactManager.m_broadPhase;
for (f = this.m_fixtureList;
f; f = f.m_next) {
f.Synchronize(broadPhase, this.m_xf, this.m_xf);
}
this.m_world.m_contactManager.FindNewContacts();
}
b2Body.prototype.SetTransform = function (xf) {
this.SetPositionAndAngle(xf.position, xf.GetAngle());
}
b2Body.prototype.GetTransform = function () {
return this.m_xf;
}
b2Body.prototype.GetPosition = function () {
return this.m_xf.position;
}
b2Body.prototype.SetPosition = function (position) {
this.SetPositionAndAngle(position, this.GetAngle());
}
b2Body.prototype.GetAngle = function () {
return this.m_sweep.a;
}
b2Body.prototype.SetAngle = function (angle) {
if (angle === undefined) angle = 0;
this.SetPositionAndAngle(this.GetPosition(), angle);
}
b2Body.prototype.GetWorldCenter = function () {
return this.m_sweep.c;
}
b2Body.prototype.GetLocalCenter = function () {
return this.m_sweep.localCenter;
}
b2Body.prototype.SetLinearVelocity = function (v) {
if (this.m_type == b2Body.b2_staticBody) {
return;
}
this.m_linearVelocity.SetV(v);
}
b2Body.prototype.GetLinearVelocity = function () {
return this.m_linearVelocity;
}
b2Body.prototype.SetAngularVelocity = function (omega) {
if (omega === undefined) omega = 0;
if (this.m_type == b2Body.b2_staticBody) {
return;
}
this.m_angularVelocity = omega;
}
b2Body.prototype.GetAngularVelocity = function () {
return this.m_angularVelocity;
}
b2Body.prototype.GetDefinition = function () {
var bd = new b2BodyDef();
bd.type = this.GetType();
bd.allowSleep = (this.m_flags & b2Body.e_allowSleepFlag) == b2Body.e_allowSleepFlag;
bd.angle = this.GetAngle();
bd.angularDamping = this.m_angularDamping;
bd.angularVelocity = this.m_angularVelocity;
bd.fixedRotation = (this.m_flags & b2Body.e_fixedRotationFlag) == b2Body.e_fixedRotationFlag;
bd.bullet = (this.m_flags & b2Body.e_bulletFlag) == b2Body.e_bulletFlag;
bd.awake = (this.m_flags & b2Body.e_awakeFlag) == b2Body.e_awakeFlag;
bd.linearDamping = this.m_linearDamping;
bd.linearVelocity.SetV(this.GetLinearVelocity());
bd.position = this.GetPosition();
bd.userData = this.GetUserData();
return bd;
}
b2Body.prototype.ApplyForce = function (force, point) {
if (this.m_type != b2Body.b2_dynamicBody) {
return;
}
if (this.IsAwake() == false) {
this.SetAwake(true);
}
this.m_force.x += force.x;
this.m_force.y += force.y;
this.m_torque += ((point.x - this.m_sweep.c.x) * force.y - (point.y - this.m_sweep.c.y) * force.x);
}
b2Body.prototype.ApplyTorque = function (torque) {
if (torque === undefined) torque = 0;
if (this.m_type != b2Body.b2_dynamicBody) {
return;
}
if (this.IsAwake() == false) {
this.SetAwake(true);
}
this.m_torque += torque;
}
b2Body.prototype.ApplyImpulse = function (impulse, point) {
if (this.m_type != b2Body.b2_dynamicBody) {
return;
}
if (this.IsAwake() == false) {
this.SetAwake(true);
}
this.m_linearVelocity.x += this.m_invMass * impulse.x;
this.m_linearVelocity.y += this.m_invMass * impulse.y;
this.m_angularVelocity += this.m_invI * ((point.x - this.m_sweep.c.x) * impulse.y - (point.y - this.m_sweep.c.y) * impulse.x);
}
b2Body.prototype.Split = function (callback) {
var linearVelocity = this.GetLinearVelocity().Copy();
var angularVelocity = this.GetAngularVelocity();
var center = this.GetWorldCenter();
var body1 = this;
var body2 = this.m_world.CreateBody(this.GetDefinition());
var prev;
for (var f = body1.m_fixtureList; f;) {
if (callback(f)) {
var next = f.m_next;
if (prev) {
prev.m_next = next;
}
else {
body1.m_fixtureList = next;
}
body1.m_fixtureCount--;
f.m_next = body2.m_fixtureList;
body2.m_fixtureList = f;
body2.m_fixtureCount++;
f.m_body = body2;
f = next;
}
else {
prev = f;
f = f.m_next;
}
}
body1.ResetMassData();
body2.ResetMassData();
var center1 = body1.GetWorldCenter();
var center2 = body2.GetWorldCenter();
var velocity1 = b2Math.AddVV(linearVelocity, b2Math.CrossFV(angularVelocity, b2Math.SubtractVV(center1, center)));
var velocity2 = b2Math.AddVV(linearVelocity, b2Math.CrossFV(angularVelocity, b2Math.SubtractVV(center2, center)));
body1.SetLinearVelocity(velocity1);
body2.SetLinearVelocity(velocity2);
body1.SetAngularVelocity(angularVelocity);
body2.SetAngularVelocity(angularVelocity);
body1.SynchronizeFixtures();
body2.SynchronizeFixtures();
return body2;
}
b2Body.prototype.Merge = function (other) {
var f;
for (f = other.m_fixtureList;
f;) {
var next = f.m_next;
other.m_fixtureCount--;
f.m_next = this.m_fixtureList;
this.m_fixtureList = f;
this.m_fixtureCount++;
f.m_body = body2;
f = next;
}
body1.m_fixtureCount = 0;
var body1 = this;
var body2 = other;
var center1 = body1.GetWorldCenter();
var center2 = body2.GetWorldCenter();
var velocity1 = body1.GetLinearVelocity().Copy();
var velocity2 = body2.GetLinearVelocity().Copy();
var angular1 = body1.GetAngularVelocity();
var angular = body2.GetAngularVelocity();
body1.ResetMassData();
this.SynchronizeFixtures();
}
b2Body.prototype.GetMass = function () {
return this.m_mass;
}
b2Body.prototype.GetInertia = function () {
return this.m_I;
}
b2Body.prototype.GetMassData = function (data) {
data.mass = this.m_mass;
data.I = this.m_I;
data.center.SetV(this.m_sweep.localCenter);
}
b2Body.prototype.SetMassData = function (massData) {
b2Settings.b2Assert(this.m_world.IsLocked() == false);
if (this.m_world.IsLocked() == true) {
return;
}
if (this.m_type != b2Body.b2_dynamicBody) {
return;
}
this.m_invMass = 0.0;
this.m_I = 0.0;
this.m_invI = 0.0;
this.m_mass = massData.mass;
if (this.m_mass <= 0.0) {
this.m_mass = 1.0;
}
this.m_invMass = 1.0 / this.m_mass;
if (massData.I > 0.0 && (this.m_flags & b2Body.e_fixedRotationFlag) == 0) {
this.m_I = massData.I - this.m_mass * (massData.center.x * massData.center.x + massData.center.y * massData.center.y);
this.m_invI = 1.0 / this.m_I;
}
var oldCenter = this.m_sweep.c.Copy();
this.m_sweep.localCenter.SetV(massData.center);
this.m_sweep.c0.SetV(b2Math.MulX(this.m_xf, this.m_sweep.localCenter));
this.m_sweep.c.SetV(this.m_sweep.c0);
this.m_linearVelocity.x += this.m_angularVelocity * (-(this.m_sweep.c.y - oldCenter.y));
this.m_linearVelocity.y += this.m_angularVelocity * (+(this.m_sweep.c.x - oldCenter.x));
}
b2Body.prototype.ResetMassData = function () {
this.m_mass = 0.0;
this.m_invMass = 0.0;
this.m_I = 0.0;
this.m_invI = 0.0;
this.m_sweep.localCenter.SetZero();
if (this.m_type == b2Body.b2_staticBody || this.m_type == b2Body.b2_kinematicBody) {
return;
}
var center = b2Vec2.Make(0, 0);
for (var f = this.m_fixtureList; f; f = f.m_next) {
if (f.m_density == 0.0) {
continue;
}
var massData = f.GetMassData();
this.m_mass += massData.mass;
center.x += massData.center.x * massData.mass;
center.y += massData.center.y * massData.mass;
this.m_I += massData.I;
}
if (this.m_mass > 0.0) {
this.m_invMass = 1.0 / this.m_mass;
center.x *= this.m_invMass;
center.y *= this.m_invMass;
}
else {
this.m_mass = 1.0;
this.m_invMass = 1.0;
}
if (this.m_I > 0.0 && (this.m_flags & b2Body.e_fixedRotationFlag) == 0) {
this.m_I -= this.m_mass * (center.x * center.x + center.y * center.y);
this.m_I *= this.m_inertiaScale;
b2Settings.b2Assert(this.m_I > 0);
this.m_invI = 1.0 / this.m_I;
}
else {
this.m_I = 0.0;
this.m_invI = 0.0;
}
var oldCenter = this.m_sweep.c.Copy();
this.m_sweep.localCenter.SetV(center);
this.m_sweep.c0.SetV(b2Math.MulX(this.m_xf, this.m_sweep.localCenter));
this.m_sweep.c.SetV(this.m_sweep.c0);
this.m_linearVelocity.x += this.m_angularVelocity * (-(this.m_sweep.c.y - oldCenter.y));
this.m_linearVelocity.y += this.m_angularVelocity * (+(this.m_sweep.c.x - oldCenter.x));
}
b2Body.prototype.GetWorldPoint = function (localPoint) {
var A = this.m_xf.R;
var u = new b2Vec2(A.col1.x * localPoint.x + A.col2.x * localPoint.y, A.col1.y * localPoint.x + A.col2.y * localPoint.y);
u.x += this.m_xf.position.x;
u.y += this.m_xf.position.y;
return u;
}
b2Body.prototype.GetWorldVector = function (localVector) {
return b2Math.MulMV(this.m_xf.R, localVector);
}
b2Body.prototype.GetLocalPoint = function (worldPoint) {
return b2Math.MulXT(this.m_xf, worldPoint);
}
b2Body.prototype.GetLocalVector = function (worldVector) {
return b2Math.MulTMV(this.m_xf.R, worldVector);
}
b2Body.prototype.GetLinearVelocityFromWorldPoint = function (worldPoint) {
return new b2Vec2(this.m_linearVelocity.x - this.m_angularVelocity * (worldPoint.y - this.m_sweep.c.y), this.m_linearVelocity.y + this.m_angularVelocity * (worldPoint.x - this.m_sweep.c.x));
}
b2Body.prototype.GetLinearVelocityFromLocalPoint = function (localPoint) {
var A = this.m_xf.R;
var worldPoint = new b2Vec2(A.col1.x * localPoint.x + A.col2.x * localPoint.y, A.col1.y * localPoint.x + A.col2.y * localPoint.y);
worldPoint.x += this.m_xf.position.x;
worldPoint.y += this.m_xf.position.y;
return new b2Vec2(this.m_linearVelocity.x - this.m_angularVelocity * (worldPoint.y - this.m_sweep.c.y), this.m_linearVelocity.y + this.m_angularVelocity * (worldPoint.x - this.m_sweep.c.x));
}
b2Body.prototype.GetLinearDamping = function () {
return this.m_linearDamping;
}
b2Body.prototype.SetLinearDamping = function (linearDamping) {
if (linearDamping === undefined) linearDamping = 0;
this.m_linearDamping = linearDamping;
}
b2Body.prototype.GetAngularDamping = function () {
return this.m_angularDamping;
}
b2Body.prototype.SetAngularDamping = function (angularDamping) {
if (angularDamping === undefined) angularDamping = 0;
this.m_angularDamping = angularDamping;
}
b2Body.prototype.SetType = function (type) {
if (type === undefined) type = 0;
if (this.m_type == type) {
return;
}
this.m_type = type;
this.ResetMassData();
if (this.m_type == b2Body.b2_staticBody) {
this.m_linearVelocity.SetZero();
this.m_angularVelocity = 0.0;
}
this.SetAwake(true);
this.m_force.SetZero();
this.m_torque = 0.0;
for (var ce = this.m_contactList; ce; ce = ce.next) {
ce.contact.FlagForFiltering();
}
}
b2Body.prototype.GetType = function () {
return this.m_type;
}
b2Body.prototype.SetBullet = function (flag) {
if (flag) {
this.m_flags |= b2Body.e_bulletFlag;
}
else {
this.m_flags &= ~b2Body.e_bulletFlag;
}
}
b2Body.prototype.IsBullet = function () {
return (this.m_flags & b2Body.e_bulletFlag) == b2Body.e_bulletFlag;
}
b2Body.prototype.SetSleepingAllowed = function (flag) {
if (flag) {
this.m_flags |= b2Body.e_allowSleepFlag;
}
else {
this.m_flags &= ~b2Body.e_allowSleepFlag;
this.SetAwake(true);
}
}
b2Body.prototype.SetAwake = function (flag) {
if (flag) {
this.m_flags |= b2Body.e_awakeFlag;
this.m_sleepTime = 0.0;
}
else {
this.m_flags &= ~b2Body.e_awakeFlag;
this.m_sleepTime = 0.0;
this.m_linearVelocity.SetZero();
this.m_angularVelocity = 0.0;
this.m_force.SetZero();
this.m_torque = 0.0;
}
}
b2Body.prototype.IsAwake = function () {
return (this.m_flags & b2Body.e_awakeFlag) == b2Body.e_awakeFlag;
}
b2Body.prototype.SetFixedRotation = function (fixed) {
if (fixed) {
this.m_flags |= b2Body.e_fixedRotationFlag;
}
else {
this.m_flags &= ~b2Body.e_fixedRotationFlag;
}
this.ResetMassData();
}
b2Body.prototype.IsFixedRotation = function () {
return (this.m_flags & b2Body.e_fixedRotationFlag) == b2Body.e_fixedRotationFlag;
}
b2Body.prototype.SetActive = function (flag) {
if (flag == this.IsActive()) {
return;
}
var broadPhase;
var f;
if (flag) {
this.m_flags |= b2Body.e_activeFlag;
broadPhase = this.m_world.m_contactManager.m_broadPhase;
for (f = this.m_fixtureList;
f; f = f.m_next) {
f.CreateProxy(broadPhase, this.m_xf);
}
}
else {
this.m_flags &= ~b2Body.e_activeFlag;
broadPhase = this.m_world.m_contactManager.m_broadPhase;
for (f = this.m_fixtureList;
f; f = f.m_next) {
f.DestroyProxy(broadPhase);
}
var ce = this.m_contactList;
while (ce) {
var ce0 = ce;
ce = ce.next;
this.m_world.m_contactManager.Destroy(ce0.contact);
}
this.m_contactList = null;
}
}
b2Body.prototype.IsActive = function () {
return (this.m_flags & b2Body.e_activeFlag) == b2Body.e_activeFlag;
}
b2Body.prototype.IsSleepingAllowed = function () {
return (this.m_flags & b2Body.e_allowSleepFlag) == b2Body.e_allowSleepFlag;
}
b2Body.prototype.GetFixtureList = function () {
return this.m_fixtureList;
}
b2Body.prototype.GetJointList = function () {
return this.m_jointList;
}
b2Body.prototype.GetControllerList = function () {
return this.m_controllerList;
}
b2Body.prototype.GetContactList = function () {
return this.m_contactList;
}
b2Body.prototype.GetNext = function () {
return this.m_next;
}
b2Body.prototype.GetUserData = function () {
return this.m_userData;
}
b2Body.prototype.SetUserData = function (data) {
this.m_userData = data;
}
b2Body.prototype.GetWorld = function () {
return this.m_world;
}
b2Body.prototype.b2Body = function (bd, world) {
this.m_flags = 0;
if (bd.bullet) {
this.m_flags |= b2Body.e_bulletFlag;
}
if (bd.fixedRotation) {
this.m_flags |= b2Body.e_fixedRotationFlag;
}
if (bd.allowSleep) {
this.m_flags |= b2Body.e_allowSleepFlag;
}
if (bd.awake) {
this.m_flags |= b2Body.e_awakeFlag;
}
if (bd.active) {
this.m_flags |= b2Body.e_activeFlag;
}
this.m_world = world;
this.m_xf.position.SetV(bd.position);
this.m_xf.R.Set(bd.angle);
this.m_sweep.localCenter.SetZero();
this.m_sweep.t0 = 1.0;
this.m_sweep.a0 = this.m_sweep.a = bd.angle;
var tMat = this.m_xf.R;
var tVec = this.m_sweep.localCenter;
this.m_sweep.c.x = (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
this.m_sweep.c.y = (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
this.m_sweep.c.x += this.m_xf.position.x;
this.m_sweep.c.y += this.m_xf.position.y;
this.m_sweep.c0.SetV(this.m_sweep.c);
this.m_jointList = null;
this.m_controllerList = null;
this.m_contactList = null;
this.m_controllerCount = 0;
this.m_prev = null;
this.m_next = null;
this.m_linearVelocity.SetV(bd.linearVelocity);
this.m_angularVelocity = bd.angularVelocity;
this.m_linearDamping = bd.linearDamping;
this.m_angularDamping = bd.angularDamping;
this.m_force.Set(0.0, 0.0);
this.m_torque = 0.0;
this.m_sleepTime = 0.0;
this.m_type = bd.type;
if (this.m_type == b2Body.b2_dynamicBody) {
this.m_mass = 1.0;
this.m_invMass = 1.0;
}
else {
this.m_mass = 0.0;
this.m_invMass = 0.0;
}
this.m_I = 0.0;
this.m_invI = 0.0;
this.m_inertiaScale = bd.inertiaScale;
this.m_userData = bd.userData;
this.m_fixtureList = null;
this.m_fixtureCount = 0;
}
b2Body.prototype.SynchronizeFixtures = function () {
var xf1 = b2Body.s_xf1;
xf1.R.Set(this.m_sweep.a0);
var tMat = xf1.R;
var tVec = this.m_sweep.localCenter;
xf1.position.x = this.m_sweep.c0.x - (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
xf1.position.y = this.m_sweep.c0.y - (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
var f;
var broadPhase = this.m_world.m_contactManager.m_broadPhase;
for (f = this.m_fixtureList;
f; f = f.m_next) {
f.Synchronize(broadPhase, xf1, this.m_xf);
}
}
b2Body.prototype.SynchronizeTransform = function () {
this.m_xf.R.Set(this.m_sweep.a);
var tMat = this.m_xf.R;
var tVec = this.m_sweep.localCenter;
this.m_xf.position.x = this.m_sweep.c.x - (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
this.m_xf.position.y = this.m_sweep.c.y - (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
}
b2Body.prototype.ShouldCollide = function (other) {
if (this.m_type != b2Body.b2_dynamicBody && other.m_type != b2Body.b2_dynamicBody) {
return false;
}
for (var jn = this.m_jointList; jn; jn = jn.next) {
if (jn.other == other) if (jn.joint.m_collideConnected == false) {
return false;
}
}
return true;
}
b2Body.prototype.Advance = function (t) {
if (t === undefined) t = 0;
this.m_sweep.Advance(t);
this.m_sweep.c.SetV(this.m_sweep.c0);
this.m_sweep.a = this.m_sweep.a0;
this.SynchronizeTransform();
}
_A2J_postDefs.push(function () {
Box2D.Dynamics.b2Body.s_xf1 = new b2Transform();
Box2D.Dynamics.b2Body.prototype.s_xf1 = Box2D.Dynamics.b2Body.s_xf1;
Box2D.Dynamics.b2Body.e_islandFlag = 0x0001;
Box2D.Dynamics.b2Body.prototype.e_islandFlag = Box2D.Dynamics.b2Body.e_islandFlag;
Box2D.Dynamics.b2Body.e_awakeFlag = 0x0002;
Box2D.Dynamics.b2Body.prototype.e_awakeFlag = Box2D.Dynamics.b2Body.e_awakeFlag;
Box2D.Dynamics.b2Body.e_allowSleepFlag = 0x0004;
Box2D.Dynamics.b2Body.prototype.e_allowSleepFlag = Box2D.Dynamics.b2Body.e_allowSleepFlag;
Box2D.Dynamics.b2Body.e_bulletFlag = 0x0008;
Box2D.Dynamics.b2Body.prototype.e_bulletFlag = Box2D.Dynamics.b2Body.e_bulletFlag;
Box2D.Dynamics.b2Body.e_fixedRotationFlag = 0x0010;
Box2D.Dynamics.b2Body.prototype.e_fixedRotationFlag = Box2D.Dynamics.b2Body.e_fixedRotationFlag;
Box2D.Dynamics.b2Body.e_activeFlag = 0x0020;
Box2D.Dynamics.b2Body.prototype.e_activeFlag = Box2D.Dynamics.b2Body.e_activeFlag;
Box2D.Dynamics.b2Body.b2_staticBody = 0;
Box2D.Dynamics.b2Body.prototype.b2_staticBody = Box2D.Dynamics.b2Body.b2_staticBody;
Box2D.Dynamics.b2Body.b2_kinematicBody = 1;
Box2D.Dynamics.b2Body.prototype.b2_kinematicBody = Box2D.Dynamics.b2Body.b2_kinematicBody;
Box2D.Dynamics.b2Body.b2_dynamicBody = 2;
Box2D.Dynamics.b2Body.prototype.b2_dynamicBody = Box2D.Dynamics.b2Body.b2_dynamicBody;
});
b2BodyDef.b2BodyDef = function () {
this.position = new b2Vec2();
this.linearVelocity = new b2Vec2();
};
b2BodyDef.prototype.b2BodyDef = function () {
this.userData = null;
this.position.Set(0.0, 0.0);
this.angle = 0.0;
this.linearVelocity.Set(0, 0);
this.angularVelocity = 0.0;
this.linearDamping = 0.0;
this.angularDamping = 0.0;
this.allowSleep = true;
this.awake = true;
this.fixedRotation = false;
this.bullet = false;
this.type = b2Body.b2_staticBody;
this.active = true;
this.inertiaScale = 1.0;
}
b2ContactFilter.b2ContactFilter = function () {};
b2ContactFilter.prototype.ShouldCollide = function (fixtureA, fixtureB) {
var filter1 = fixtureA.GetFilterData();
var filter2 = fixtureB.GetFilterData();
if (filter1.groupIndex == filter2.groupIndex && filter1.groupIndex != 0) {
return filter1.groupIndex > 0;
}
var collide = (filter1.maskBits & filter2.categoryBits) != 0 && (filter1.categoryBits & filter2.maskBits) != 0;
return collide;
}
b2ContactFilter.prototype.RayCollide = function (userData, fixture) {
if (!userData) return true;
return this.ShouldCollide((userData instanceof b2Fixture ? userData : null), fixture);
}
_A2J_postDefs.push(function () {
Box2D.Dynamics.b2ContactFilter.b2_defaultFilter = new b2ContactFilter();
Box2D.Dynamics.b2ContactFilter.prototype.b2_defaultFilter = Box2D.Dynamics.b2ContactFilter.b2_defaultFilter;
});
b2ContactImpulse.b2ContactImpulse = function () {
this.normalImpulses = new Vector_a2j_Number(b2Settings.b2_maxManifoldPoints);
this.tangentImpulses = new Vector_a2j_Number(b2Settings.b2_maxManifoldPoints);
};
b2ContactListener.b2ContactListener = function () {};
b2ContactListener.prototype.BeginContact = function (contact) {}
b2ContactListener.prototype.EndContact = function (contact) {}
b2ContactListener.prototype.PreSolve = function (contact, oldManifold) {}
b2ContactListener.prototype.PostSolve = function (contact, impulse) {}
_A2J_postDefs.push(function () {
Box2D.Dynamics.b2ContactListener.b2_defaultListener = new b2ContactListener();
Box2D.Dynamics.b2ContactListener.prototype.b2_defaultListener = Box2D.Dynamics.b2ContactListener.b2_defaultListener;
});
b2ContactManager.b2ContactManager = function () {};
b2ContactManager.prototype.b2ContactManager = function () {
this.m_world = null;
this.m_contactCount = 0;
this.m_contactFilter = b2ContactFilter.b2_defaultFilter;
this.m_contactListener = b2ContactListener.b2_defaultListener;
this.m_contactFactory = new b2ContactFactory(this.m_allocator);
this.m_broadPhase = new b2DynamicTreeBroadPhase();
}
b2ContactManager.prototype.AddPair = function (proxyUserDataA, proxyUserDataB) {
var fixtureA = (proxyUserDataA instanceof b2Fixture ? proxyUserDataA : null);
var fixtureB = (proxyUserDataB instanceof b2Fixture ? proxyUserDataB : null);
var bodyA = fixtureA.GetBody();
var bodyB = fixtureB.GetBody();
if (bodyA == bodyB) return;
var edge = bodyB.GetContactList();
while (edge) {
if (edge.other == bodyA) {
var fA = edge.contact.GetFixtureA();
var fB = edge.contact.GetFixtureB();
if (fA == fixtureA && fB == fixtureB) return;
if (fA == fixtureB && fB == fixtureA) return;
}
edge = edge.next;
}
if (bodyB.ShouldCollide(bodyA) == false) {
return;
}
if (this.m_contactFilter.ShouldCollide(fixtureA, fixtureB) == false) {
return;
}
var c = this.m_contactFactory.Create(fixtureA, fixtureB);
fixtureA = c.GetFixtureA();
fixtureB = c.GetFixtureB();
bodyA = fixtureA.m_body;
bodyB = fixtureB.m_body;
c.m_prev = null;
c.m_next = this.m_world.m_contactList;
if (this.m_world.m_contactList != null) {
this.m_world.m_contactList.m_prev = c;
}
this.m_world.m_contactList = c;
c.m_nodeA.contact = c;
c.m_nodeA.other = bodyB;
c.m_nodeA.prev = null;
c.m_nodeA.next = bodyA.m_contactList;
if (bodyA.m_contactList != null) {
bodyA.m_contactList.prev = c.m_nodeA;
}
bodyA.m_contactList = c.m_nodeA;
c.m_nodeB.contact = c;
c.m_nodeB.other = bodyA;
c.m_nodeB.prev = null;
c.m_nodeB.next = bodyB.m_contactList;
if (bodyB.m_contactList != null) {
bodyB.m_contactList.prev = c.m_nodeB;
}
bodyB.m_contactList = c.m_nodeB;
++this.m_world.m_contactCount;
return;
}
b2ContactManager.prototype.FindNewContacts = function () {
this.m_broadPhase.UpdatePairs(a2j.generateCallback(this, this.AddPair));
}
b2ContactManager.prototype.Destroy = function (c) {
var fixtureA = c.GetFixtureA();
var fixtureB = c.GetFixtureB();
var bodyA = fixtureA.GetBody();
var bodyB = fixtureB.GetBody();
if (c.IsTouching()) {
this.m_contactListener.EndContact(c);
}
if (c.m_prev) {
c.m_prev.m_next = c.m_next;
}
if (c.m_next) {
c.m_next.m_prev = c.m_prev;
}
if (c == this.m_world.m_contactList) {
this.m_world.m_contactList = c.m_next;
}
if (c.m_nodeA.prev) {
c.m_nodeA.prev.next = c.m_nodeA.next;
}
if (c.m_nodeA.next) {
c.m_nodeA.next.prev = c.m_nodeA.prev;
}
if (c.m_nodeA == bodyA.m_contactList) {
bodyA.m_contactList = c.m_nodeA.next;
}
if (c.m_nodeB.prev) {
c.m_nodeB.prev.next = c.m_nodeB.next;
}
if (c.m_nodeB.next) {
c.m_nodeB.next.prev = c.m_nodeB.prev;
}
if (c.m_nodeB == bodyB.m_contactList) {
bodyB.m_contactList = c.m_nodeB.next;
}
this.m_contactFactory.Destroy(c);
--this.m_contactCount;
}
b2ContactManager.prototype.Collide = function () {
var c = this.m_world.m_contactList;
while (c) {
var fixtureA = c.GetFixtureA();
var fixtureB = c.GetFixtureB();
var bodyA = fixtureA.GetBody();
var bodyB = fixtureB.GetBody();
if (bodyA.IsAwake() == false && bodyB.IsAwake() == false) {
c = c.GetNext();
continue;
}
if (c.m_flags & b2Contact.e_filterFlag) {
if (bodyB.ShouldCollide(bodyA) == false) {
var cNuke = c;
c = cNuke.GetNext();
this.Destroy(cNuke);
continue;
}
if (this.m_contactFilter.ShouldCollide(fixtureA, fixtureB) == false) {
cNuke = c;
c = cNuke.GetNext();
this.Destroy(cNuke);
continue;
}
c.m_flags &= ~b2Contact.e_filterFlag;
}
var proxyA = fixtureA.m_proxy;
var proxyB = fixtureB.m_proxy;
var overlap = this.m_broadPhase.TestOverlap(proxyA, proxyB);
if (overlap == false) {
cNuke = c;
c = cNuke.GetNext();
this.Destroy(cNuke);
continue;
}
c.Update(this.m_contactListener);
c = c.GetNext();
}
}
_A2J_postDefs.push(function () {
Box2D.Dynamics.b2ContactManager.s_evalCP = new b2ContactPoint();
Box2D.Dynamics.b2ContactManager.prototype.s_evalCP = Box2D.Dynamics.b2ContactManager.s_evalCP;
});
b2DebugDraw.b2DebugDraw = function () {};
b2DebugDraw.prototype.b2DebugDraw = function () {
m_drawFlags = 0;
}
b2DebugDraw.prototype.SetFlags = function (flags) {
if (flags === undefined) flags = 0;
}
b2DebugDraw.prototype.GetFlags = function () {}
b2DebugDraw.prototype.AppendFlags = function (flags) {
if (flags === undefined) flags = 0;
}
b2DebugDraw.prototype.ClearFlags = function (flags) {
if (flags === undefined) flags = 0;
}
b2DebugDraw.prototype.SetSprite = function (sprite) {}
b2DebugDraw.prototype.GetSprite = function () {}
b2DebugDraw.prototype.SetDrawScale = function (drawScale) {
if (drawScale === undefined) drawScale = 0;
}
b2DebugDraw.prototype.GetDrawScale = function () {}
b2DebugDraw.prototype.SetLineThickness = function (lineThickness) {
if (lineThickness === undefined) lineThickness = 0;
}
b2DebugDraw.prototype.GetLineThickness = function () {}
b2DebugDraw.prototype.SetAlpha = function (alpha) {
if (alpha === undefined) alpha = 0;
}
b2DebugDraw.prototype.GetAlpha = function () {}
b2DebugDraw.prototype.SetFillAlpha = function (alpha) {
if (alpha === undefined) alpha = 0;
}
b2DebugDraw.prototype.GetFillAlpha = function () {}
b2DebugDraw.prototype.SetXFormScale = function (xformScale) {
if (xformScale === undefined) xformScale = 0;
}
b2DebugDraw.prototype.GetXFormScale = function () {}
b2DebugDraw.prototype.DrawPolygon = function (vertices, vertexCount, color) {
if (vertexCount === undefined) vertexCount = 0;
}
b2DebugDraw.prototype.DrawSolidPolygon = function (vertices, vertexCount, color) {
if (vertexCount === undefined) vertexCount = 0;
}
b2DebugDraw.prototype.DrawCircle = function (center, radius, color) {
if (radius === undefined) radius = 0;
}
b2DebugDraw.prototype.DrawSolidCircle = function (center, radius, axis, color) {
if (radius === undefined) radius = 0;
}
b2DebugDraw.prototype.DrawSegment = function (p1, p2, color) {}
b2DebugDraw.prototype.DrawTransform = function (xf) {}
_A2J_postDefs.push(function () {
Box2D.Dynamics.b2DebugDraw.e_shapeBit = 0x0001;
Box2D.Dynamics.b2DebugDraw.prototype.e_shapeBit = Box2D.Dynamics.b2DebugDraw.e_shapeBit;
Box2D.Dynamics.b2DebugDraw.e_jointBit = 0x0002;
Box2D.Dynamics.b2DebugDraw.prototype.e_jointBit = Box2D.Dynamics.b2DebugDraw.e_jointBit;
Box2D.Dynamics.b2DebugDraw.e_aabbBit = 0x0004;
Box2D.Dynamics.b2DebugDraw.prototype.e_aabbBit = Box2D.Dynamics.b2DebugDraw.e_aabbBit;
Box2D.Dynamics.b2DebugDraw.e_pairBit = 0x0008;
Box2D.Dynamics.b2DebugDraw.prototype.e_pairBit = Box2D.Dynamics.b2DebugDraw.e_pairBit;
Box2D.Dynamics.b2DebugDraw.e_centerOfMassBit = 0x0010;
Box2D.Dynamics.b2DebugDraw.prototype.e_centerOfMassBit = Box2D.Dynamics.b2DebugDraw.e_centerOfMassBit;
Box2D.Dynamics.b2DebugDraw.e_controllerBit = 0x0020;
Box2D.Dynamics.b2DebugDraw.prototype.e_controllerBit = Box2D.Dynamics.b2DebugDraw.e_controllerBit;
});
b2DestructionListener.b2DestructionListener = function () {};
b2DestructionListener.prototype.SayGoodbyeJoint = function (joint) {}
b2DestructionListener.prototype.SayGoodbyeFixture = function (fixture) {}
b2FilterData.b2FilterData = function () {
this.categoryBits = 0x0001;
this.maskBits = 0xFFFF;
this.groupIndex = 0;
};
b2FilterData.prototype.Copy = function () {
var copy = new b2FilterData();
copy.categoryBits = this.categoryBits;
copy.maskBits = this.maskBits;
copy.groupIndex = this.groupIndex;
return copy;
}
b2Fixture.b2Fixture = function () {
this.m_filter = new b2FilterData();
};
b2Fixture.prototype.GetType = function () {
return this.m_shape.GetType();
}
b2Fixture.prototype.GetShape = function () {
return this.m_shape;
}
b2Fixture.prototype.SetSensor = function (sensor) {
if (this.m_isSensor == sensor) return;
this.m_isSensor = sensor;
if (this.m_body == null) return;
var edge = this.m_body.GetContactList();
while (edge) {
var contact = edge.contact;
var fixtureA = contact.GetFixtureA();
var fixtureB = contact.GetFixtureB();
if (fixtureA == this || fixtureB == this) contact.SetSensor(fixtureA.IsSensor() || fixtureB.IsSensor());
edge = edge.next;
}
}
b2Fixture.prototype.IsSensor = function () {
return this.m_isSensor;
}
b2Fixture.prototype.SetFilterData = function (filter) {
this.m_filter = filter.Copy();
if (this.m_body) return;
var edge = this.m_body.GetContactList();
while (edge) {
var contact = edge.contact;
var fixtureA = contact.GetFixtureA();
var fixtureB = contact.GetFixtureB();
if (fixtureA == this || fixtureB == this) contact.FlagForFiltering();
edge = edge.next;
}
}
b2Fixture.prototype.GetFilterData = function () {
return this.m_filter.Copy();
}
b2Fixture.prototype.GetBody = function () {
return this.m_body;
}
b2Fixture.prototype.GetNext = function () {
return this.m_next;
}
b2Fixture.prototype.GetUserData = function () {
return this.m_userData;
}
b2Fixture.prototype.SetUserData = function (data) {
this.m_userData = data;
}
b2Fixture.prototype.TestPoint = function (p) {
return this.m_shape.TestPoint(this.m_body.GetTransform(), p);
}
b2Fixture.prototype.RayCast = function (output, input) {
return this.m_shape.RayCast(output, input, this.m_body.GetTransform());
}
b2Fixture.prototype.GetMassData = function (massData) {
if (massData === undefined) massData = null;
if (massData == null) {
massData = new b2MassData();
}
this.m_shape.ComputeMass(massData, this.m_density);
return massData;
}
b2Fixture.prototype.SetDensity = function (density) {
if (density === undefined) density = 0;
this.m_density = density;
}
b2Fixture.prototype.GetDensity = function () {
return this.m_density;
}
b2Fixture.prototype.GetFriction = function () {
return this.m_friction;
}
b2Fixture.prototype.SetFriction = function (friction) {
if (friction === undefined) friction = 0;
this.m_friction = friction;
}
b2Fixture.prototype.GetRestitution = function () {
return this.m_restitution;
}
b2Fixture.prototype.SetRestitution = function (restitution) {
if (restitution === undefined) restitution = 0;
this.m_restitution = restitution;
}
b2Fixture.prototype.GetAABB = function () {
return this.m_aabb;
}
b2Fixture.prototype.b2Fixture = function () {
this.m_aabb = new b2AABB();
this.m_userData = null;
this.m_body = null;
this.m_next = null;
this.m_shape = null;
this.m_density = 0.0;
this.m_friction = 0.0;
this.m_restitution = 0.0;
}
b2Fixture.prototype.Create = function (body, xf, def) {
this.m_userData = def.userData;
this.m_friction = def.friction;
this.m_restitution = def.restitution;
this.m_body = body;
this.m_next = null;
this.m_filter = def.filter.Copy();
this.m_isSensor = def.isSensor;
this.m_shape = def.shape.Copy();
this.m_density = def.density;
}
b2Fixture.prototype.Destroy = function () {
this.m_shape = null;
}
b2Fixture.prototype.CreateProxy = function (broadPhase, xf) {
this.m_shape.ComputeAABB(this.m_aabb, xf);
this.m_proxy = broadPhase.CreateProxy(this.m_aabb, this);
}
b2Fixture.prototype.DestroyProxy = function (broadPhase) {
if (this.m_proxy == null) {
return;
}
broadPhase.DestroyProxy(this.m_proxy);
this.m_proxy = null;
}
b2Fixture.prototype.Synchronize = function (broadPhase, transform1, transform2) {
if (!this.m_proxy) return;
var aabb1 = new b2AABB();
var aabb2 = new b2AABB();
this.m_shape.ComputeAABB(aabb1, transform1);
this.m_shape.ComputeAABB(aabb2, transform2);
this.m_aabb.Combine(aabb1, aabb2);
var displacement = b2Math.SubtractVV(transform2.position, transform1.position);
broadPhase.MoveProxy(this.m_proxy, this.m_aabb, displacement);
}
b2FixtureDef.b2FixtureDef = function () {
this.filter = new b2FilterData();
};
b2FixtureDef.prototype.b2FixtureDef = function () {
this.shape = null;
this.userData = null;
this.friction = 0.2;
this.restitution = 0.0;
this.density = 0.0;
this.filter.categoryBits = 0x0001;
this.filter.maskBits = 0xFFFF;
this.filter.groupIndex = 0;
this.isSensor = false;
}
b2Island.b2Island = function () {};
b2Island.prototype.b2Island = function () {
this.m_bodies = new Vector();
this.m_contacts = new Vector();
this.m_joints = new Vector();
}
b2Island.prototype.Initialize = function (bodyCapacity, contactCapacity, jointCapacity, allocator, listener, contactSolver) {
if (bodyCapacity === undefined) bodyCapacity = 0;
if (contactCapacity === undefined) contactCapacity = 0;
if (jointCapacity === undefined) jointCapacity = 0;
var i = 0;
this.m_bodyCapacity = bodyCapacity;
this.m_contactCapacity = contactCapacity;
this.m_jointCapacity = jointCapacity;
this.m_bodyCount = 0;
this.m_contactCount = 0;
this.m_jointCount = 0;
this.m_allocator = allocator;
this.m_listener = listener;
this.m_contactSolver = contactSolver;
for (i = this.m_bodies.length;
i < bodyCapacity; i++)
this.m_bodies[i] = null;
for (i = this.m_contacts.length;
i < contactCapacity; i++)
this.m_contacts[i] = null;
for (i = this.m_joints.length;
i < jointCapacity; i++)
this.m_joints[i] = null;
}
b2Island.prototype.Clear = function () {
this.m_bodyCount = 0;
this.m_contactCount = 0;
this.m_jointCount = 0;
}
b2Island.prototype.Solve = function (step, gravity, allowSleep) {
var i = 0;
var j = 0;
var b;
var joint;
for (i = 0;
i < this.m_bodyCount; ++i) {
b = this.m_bodies[i];
if (b.GetType() != b2Body.b2_dynamicBody) continue;
b.m_linearVelocity.x += step.dt * (gravity.x + b.m_invMass * b.m_force.x);
b.m_linearVelocity.y += step.dt * (gravity.y + b.m_invMass * b.m_force.y);
b.m_angularVelocity += step.dt * b.m_invI * b.m_torque;
b.m_linearVelocity.Multiply(b2Math.Clamp(1.0 - step.dt * b.m_linearDamping, 0.0, 1.0));
b.m_angularVelocity *= b2Math.Clamp(1.0 - step.dt * b.m_angularDamping, 0.0, 1.0);
}
this.m_contactSolver.Initialize(step, this.m_contacts, this.m_contactCount, this.m_allocator);
var contactSolver = this.m_contactSolver;
contactSolver.InitVelocityConstraints(step);
for (i = 0;
i < this.m_jointCount; ++i) {
joint = this.m_joints[i];
joint.InitVelocityConstraints(step);
}
for (i = 0;
i < step.velocityIterations; ++i) {
for (j = 0;
j < this.m_jointCount; ++j) {
joint = this.m_joints[j];
joint.SolveVelocityConstraints(step);
}
contactSolver.SolveVelocityConstraints();
}
for (i = 0;
i < this.m_jointCount; ++i) {
joint = this.m_joints[i];
joint.FinalizeVelocityConstraints();
}
contactSolver.FinalizeVelocityConstraints();
for (i = 0;
i < this.m_bodyCount; ++i) {
b = this.m_bodies[i];
if (b.GetType() == b2Body.b2_staticBody) continue;
var translationX = step.dt * b.m_linearVelocity.x;
var translationY = step.dt * b.m_linearVelocity.y;
if ((translationX * translationX + translationY * translationY) > b2Settings.b2_maxTranslationSquared) {
b.m_linearVelocity.Normalize();
b.m_linearVelocity.x *= b2Settings.b2_maxTranslation * step.inv_dt;
b.m_linearVelocity.y *= b2Settings.b2_maxTranslation * step.inv_dt;
}
var rotation = step.dt * b.m_angularVelocity;
if (rotation * rotation > b2Settings.b2_maxRotationSquared) {
if (b.m_angularVelocity < 0.0) {
b.m_angularVelocity = (-b2Settings.b2_maxRotation * step.inv_dt);
}
else {
b.m_angularVelocity = b2Settings.b2_maxRotation * step.inv_dt;
}
}
b.m_sweep.c0.SetV(b.m_sweep.c);
b.m_sweep.a0 = b.m_sweep.a;
b.m_sweep.c.x += step.dt * b.m_linearVelocity.x;
b.m_sweep.c.y += step.dt * b.m_linearVelocity.y;
b.m_sweep.a += step.dt * b.m_angularVelocity;
b.SynchronizeTransform();
}
for (i = 0;
i < step.positionIterations; ++i) {
var contactsOkay = contactSolver.SolvePositionConstraints(b2Settings.b2_contactBaumgarte);
var jointsOkay = true;
for (j = 0;
j < this.m_jointCount; ++j) {
joint = this.m_joints[j];
var jointOkay = joint.SolvePositionConstraints(b2Settings.b2_contactBaumgarte);
jointsOkay = jointsOkay && jointOkay;
}
if (contactsOkay && jointsOkay) {
break;
}
}
this.Report(contactSolver.m_constraints);
if (allowSleep) {
var minSleepTime = Number.MAX_VALUE;
var linTolSqr = b2Settings.b2_linearSleepTolerance * b2Settings.b2_linearSleepTolerance;
var angTolSqr = b2Settings.b2_angularSleepTolerance * b2Settings.b2_angularSleepTolerance;
for (i = 0;
i < this.m_bodyCount; ++i) {
b = this.m_bodies[i];
if (b.GetType() == b2Body.b2_staticBody) {
continue;
}
if ((b.m_flags & b2Body.e_allowSleepFlag) == 0) {
b.m_sleepTime = 0.0;
minSleepTime = 0.0;
}
if ((b.m_flags & b2Body.e_allowSleepFlag) == 0 || b.m_angularVelocity * b.m_angularVelocity > angTolSqr || b2Math.Dot(b.m_linearVelocity, b.m_linearVelocity) > linTolSqr) {
b.m_sleepTime = 0.0;
minSleepTime = 0.0;
}
else {
b.m_sleepTime += step.dt;
minSleepTime = b2Math.Min(minSleepTime, b.m_sleepTime);
}
}
if (minSleepTime >= b2Settings.b2_timeToSleep) {
for (i = 0;
i < this.m_bodyCount; ++i) {
b = this.m_bodies[i];
b.SetAwake(false);
}
}
}
}
b2Island.prototype.SolveTOI = function (subStep) {
var i = 0;
var j = 0;
this.m_contactSolver.Initialize(subStep, this.m_contacts, this.m_contactCount, this.m_allocator);
var contactSolver = this.m_contactSolver;
for (i = 0;
i < this.m_jointCount; ++i) {
this.m_joints[i].InitVelocityConstraints(subStep);
}
for (i = 0;
i < subStep.velocityIterations; ++i) {
contactSolver.SolveVelocityConstraints();
for (j = 0;
j < this.m_jointCount; ++j) {
this.m_joints[j].SolveVelocityConstraints(subStep);
}
}
for (i = 0;
i < this.m_bodyCount; ++i) {
var b = this.m_bodies[i];
if (b.GetType() == b2Body.b2_staticBody) continue;
var translationX = subStep.dt * b.m_linearVelocity.x;
var translationY = subStep.dt * b.m_linearVelocity.y;
if ((translationX * translationX + translationY * translationY) > b2Settings.b2_maxTranslationSquared) {
b.m_linearVelocity.Normalize();
b.m_linearVelocity.x *= b2Settings.b2_maxTranslation * subStep.inv_dt;
b.m_linearVelocity.y *= b2Settings.b2_maxTranslation * subStep.inv_dt;
}
var rotation = subStep.dt * b.m_angularVelocity;
if (rotation * rotation > b2Settings.b2_maxRotationSquared) {
if (b.m_angularVelocity < 0.0) {
b.m_angularVelocity = (-b2Settings.b2_maxRotation * subStep.inv_dt);
}
else {
b.m_angularVelocity = b2Settings.b2_maxRotation * subStep.inv_dt;
}
}
b.m_sweep.c0.SetV(b.m_sweep.c);
b.m_sweep.a0 = b.m_sweep.a;
b.m_sweep.c.x += subStep.dt * b.m_linearVelocity.x;
b.m_sweep.c.y += subStep.dt * b.m_linearVelocity.y;
b.m_sweep.a += subStep.dt * b.m_angularVelocity;
b.SynchronizeTransform();
}
var k_toiBaumgarte = 0.75;
for (i = 0;
i < subStep.positionIterations; ++i) {
var contactsOkay = contactSolver.SolvePositionConstraints(k_toiBaumgarte);
var jointsOkay = true;
for (j = 0;
j < this.m_jointCount; ++j) {
var jointOkay = this.m_joints[j].SolvePositionConstraints(b2Settings.b2_contactBaumgarte);
jointsOkay = jointsOkay && jointOkay;
}
if (contactsOkay && jointsOkay) {
break;
}
}
this.Report(contactSolver.m_constraints);
}
b2Island.prototype.Report = function (constraints) {
if (this.m_listener == null) {
return;
}
for (var i = 0; i < this.m_contactCount; ++i) {
var c = this.m_contacts[i];
var cc = constraints[i];
for (var j = 0; j < cc.pointCount; ++j) {
b2Island.s_impulse.normalImpulses[j] = cc.points[j].normalImpulse;
b2Island.s_impulse.tangentImpulses[j] = cc.points[j].tangentImpulse;
}
this.m_listener.PostSolve(c, b2Island.s_impulse);
}
}
b2Island.prototype.AddBody = function (body) {
body.m_islandIndex = this.m_bodyCount;
this.m_bodies[this.m_bodyCount++] = body;
}
b2Island.prototype.AddContact = function (contact) {
this.m_contacts[this.m_contactCount++] = contact;
}
b2Island.prototype.AddJoint = function (joint) {
this.m_joints[this.m_jointCount++] = joint;
}
_A2J_postDefs.push(function () {
Box2D.Dynamics.b2Island.s_impulse = new b2ContactImpulse();
Box2D.Dynamics.b2Island.prototype.s_impulse = Box2D.Dynamics.b2Island.s_impulse;
});
b2TimeStep.b2TimeStep = function () {};
b2TimeStep.prototype.Set = function (step) {
this.dt = step.dt;
this.inv_dt = step.inv_dt;
this.positionIterations = step.positionIterations;
this.velocityIterations = step.velocityIterations;
this.warmStarting = step.warmStarting;
}
b2World.b2World = function () {
this.s_stack = new Vector();
this.m_contactManager = new b2ContactManager();
this.m_contactSolver = new b2ContactSolver();
this.m_island = new b2Island();
};
b2World.prototype.b2World = function (gravity, doSleep) {
this.m_destructionListener = null;
this.m_debugDraw = null;
this.m_bodyList = null;
this.m_contactList = null;
this.m_jointList = null;
this.m_controllerList = null;
this.m_bodyCount = 0;
this.m_contactCount = 0;
this.m_jointCount = 0;
this.m_controllerCount = 0;
b2World.m_warmStarting = true;
b2World.m_continuousPhysics = true;
this.m_allowSleep = doSleep;
this.m_gravity = gravity;
this.m_inv_dt0 = 0.0;
this.m_contactManager.m_world = this;
var bd = new b2BodyDef();
this.m_groundBody = this.CreateBody(bd);
}
b2World.prototype.SetDestructionListener = function (listener) {
this.m_destructionListener = listener;
}
b2World.prototype.SetContactFilter = function (filter) {
this.m_contactManager.m_contactFilter = filter;
}
b2World.prototype.SetContactListener = function (listener) {
this.m_contactManager.m_contactListener = listener;
}
b2World.prototype.SetDebugDraw = function (debugDraw) {
this.m_debugDraw = debugDraw;
}
b2World.prototype.SetBroadPhase = function (broadPhase) {
var oldBroadPhase = this.m_contactManager.m_broadPhase;
this.m_contactManager.m_broadPhase = broadPhase;
for (var b = this.m_bodyList; b; b = b.m_next) {
for (var f = b.m_fixtureList; f; f = f.m_next) {
f.m_proxy = broadPhase.CreateProxy(oldBroadPhase.GetFatAABB(f.m_proxy), f);
}
}
}
b2World.prototype.Validate = function () {
this.m_contactManager.m_broadPhase.Validate();
}
b2World.prototype.GetProxyCount = function () {
return this.m_contactManager.m_broadPhase.GetProxyCount();
}
b2World.prototype.CreateBody = function (def) {
if (this.IsLocked() == true) {
return null;
}
var b = new b2Body(def, this);
b.m_prev = null;
b.m_next = this.m_bodyList;
if (this.m_bodyList) {
this.m_bodyList.m_prev = b;
}
this.m_bodyList = b;
++this.m_bodyCount;
return b;
}
b2World.prototype.DestroyBody = function (b) {
if (this.IsLocked() == true) {
return;
}
var jn = b.m_jointList;
while (jn) {
var jn0 = jn;
jn = jn.next;
if (this.m_destructionListener) {
this.m_destructionListener.SayGoodbyeJoint(jn0.joint);
}
this.DestroyJoint(jn0.joint);
}
var coe = b.m_controllerList;
while (coe) {
var coe0 = coe;
coe = coe.nextController;
coe0.controller.RemoveBody(b);
}
var ce = b.m_contactList;
while (ce) {
var ce0 = ce;
ce = ce.next;
this.m_contactManager.Destroy(ce0.contact);
}
b.m_contactList = null;
var f = b.m_fixtureList;
while (f) {
var f0 = f;
f = f.m_next;
if (this.m_destructionListener) {
this.m_destructionListener.SayGoodbyeFixture(f0);
}
f0.DestroyProxy(this.m_contactManager.m_broadPhase);
f0.Destroy();
}
b.m_fixtureList = null;
b.m_fixtureCount = 0;
if (b.m_prev) {
b.m_prev.m_next = b.m_next;
}
if (b.m_next) {
b.m_next.m_prev = b.m_prev;
}
if (b == this.m_bodyList) {
this.m_bodyList = b.m_next;
}--this.m_bodyCount;
}
b2World.prototype.CreateJoint = function (def) {
var j = b2Joint.Create(def, null);
j.m_prev = null;
j.m_next = this.m_jointList;
if (this.m_jointList) {
this.m_jointList.m_prev = j;
}
this.m_jointList = j;
++this.m_jointCount;
j.m_edgeA.joint = j;
j.m_edgeA.other = j.m_bodyB;
j.m_edgeA.prev = null;
j.m_edgeA.next = j.m_bodyA.m_jointList;
if (j.m_bodyA.m_jointList) j.m_bodyA.m_jointList.prev = j.m_edgeA;
j.m_bodyA.m_jointList = j.m_edgeA;
j.m_edgeB.joint = j;
j.m_edgeB.other = j.m_bodyA;
j.m_edgeB.prev = null;
j.m_edgeB.next = j.m_bodyB.m_jointList;
if (j.m_bodyB.m_jointList) j.m_bodyB.m_jointList.prev = j.m_edgeB;
j.m_bodyB.m_jointList = j.m_edgeB;
var bodyA = def.bodyA;
var bodyB = def.bodyB;
if (def.collideConnected == false) {
var edge = bodyB.GetContactList();
while (edge) {
if (edge.other == bodyA) {
edge.contact.FlagForFiltering();
}
edge = edge.next;
}
}
return j;
}
b2World.prototype.DestroyJoint = function (j) {
var collideConnected = j.m_collideConnected;
if (j.m_prev) {
j.m_prev.m_next = j.m_next;
}
if (j.m_next) {
j.m_next.m_prev = j.m_prev;
}
if (j == this.m_jointList) {
this.m_jointList = j.m_next;
}
var bodyA = j.m_bodyA;
var bodyB = j.m_bodyB;
bodyA.SetAwake(true);
bodyB.SetAwake(true);
if (j.m_edgeA.prev) {
j.m_edgeA.prev.next = j.m_edgeA.next;
}
if (j.m_edgeA.next) {
j.m_edgeA.next.prev = j.m_edgeA.prev;
}
if (j.m_edgeA == bodyA.m_jointList) {
bodyA.m_jointList = j.m_edgeA.next;
}
j.m_edgeA.prev = null;
j.m_edgeA.next = null;
if (j.m_edgeB.prev) {
j.m_edgeB.prev.next = j.m_edgeB.next;
}
if (j.m_edgeB.next) {
j.m_edgeB.next.prev = j.m_edgeB.prev;
}
if (j.m_edgeB == bodyB.m_jointList) {
bodyB.m_jointList = j.m_edgeB.next;
}
j.m_edgeB.prev = null;
j.m_edgeB.next = null;
b2Joint.Destroy(j, null);
--this.m_jointCount;
if (collideConnected == false) {
var edge = bodyB.GetContactList();
while (edge) {
if (edge.other == bodyA) {
edge.contact.FlagForFiltering();
}
edge = edge.next;
}
}
}
b2World.prototype.AddController = function (c) {
c.m_next = this.m_controllerList;
c.m_prev = null;
this.m_controllerList = c;
c.m_world = this;
this.m_controllerCount++;
return c;
}
b2World.prototype.RemoveController = function (c) {
if (c.m_prev) c.m_prev.m_next = c.m_next;
if (c.m_next) c.m_next.m_prev = c.m_prev;
if (this.m_controllerList == c) this.m_controllerList = c.m_next;
this.m_controllerCount--;
}
b2World.prototype.CreateController = function (controller) {
if (controller.m_world != this) throw new Error("Controller can only be a member of one world");
controller.m_next = this.m_controllerList;
controller.m_prev = null;
if (this.m_controllerList) this.m_controllerList.m_prev = controller;
this.m_controllerList = controller;
++this.m_controllerCount;
controller.m_world = this;
return controller;
}
b2World.prototype.DestroyController = function (controller) {
controller.Clear();
if (controller.m_next) controller.m_next.m_prev = controller.m_prev;
if (controller.m_prev) controller.m_prev.m_next = controller.m_next;
if (controller == this.m_controllerList) this.m_controllerList = controller.m_next;
--this.m_controllerCount;
}
b2World.prototype.SetWarmStarting = function (flag) {
b2World.m_warmStarting = flag;
}
b2World.prototype.SetContinuousPhysics = function (flag) {
b2World.m_continuousPhysics = flag;
}
b2World.prototype.GetBodyCount = function () {
return this.m_bodyCount;
}
b2World.prototype.GetJointCount = function () {
return this.m_jointCount;
}
b2World.prototype.GetContactCount = function () {
return this.m_contactCount;
}
b2World.prototype.SetGravity = function (gravity) {
this.m_gravity = gravity;
}
b2World.prototype.GetGravity = function () {
return this.m_gravity;
}
b2World.prototype.GetGroundBody = function () {
return this.m_groundBody;
}
b2World.prototype.Step = function (dt, velocityIterations, positionIterations) {
if (dt === undefined) dt = 0;
if (velocityIterations === undefined) velocityIterations = 0;
if (positionIterations === undefined) positionIterations = 0;
if (this.m_flags & b2World.e_newFixture) {
this.m_contactManager.FindNewContacts();
this.m_flags &= ~b2World.e_newFixture;
}
this.m_flags |= b2World.e_locked;
var step = b2World.s_timestep2;
step.dt = dt;
step.velocityIterations = velocityIterations;
step.positionIterations = positionIterations;
if (dt > 0.0) {
step.inv_dt = 1.0 / dt;
}
else {
step.inv_dt = 0.0;
}
step.dtRatio = this.m_inv_dt0 * dt;
step.warmStarting = b2World.m_warmStarting;
this.m_contactManager.Collide();
if (step.dt > 0.0) {
this.Solve(step);
}
if (b2World.m_continuousPhysics && step.dt > 0.0) {
this.SolveTOI(step);
}
if (step.dt > 0.0) {
this.m_inv_dt0 = step.inv_dt;
}
this.m_flags &= ~b2World.e_locked;
}
b2World.prototype.ClearForces = function () {
for (var body = this.m_bodyList; body; body = body.m_next) {
body.m_force.SetZero();
body.m_torque = 0.0;
}
}
b2World.prototype.DrawDebugData = function () {
if (this.m_debugDraw == null) {
return;
}
this.m_debugDraw.m_sprite.graphics.clear();
var flags = this.m_debugDraw.GetFlags();
var i = 0;
var b;
var f;
var s;
var j;
var bp;
var invQ = new b2Vec2;
var x1 = new b2Vec2;
var x2 = new b2Vec2;
var xf;
var b1 = new b2AABB();
var b2 = new b2AABB();
var vs = [new b2Vec2(), new b2Vec2(), new b2Vec2(), new b2Vec2()];
var color = new b2Color(0, 0, 0);
if (flags & b2DebugDraw.e_shapeBit) {
for (b = this.m_bodyList;
b; b = b.m_next) {
xf = b.m_xf;
for (f = b.GetFixtureList();
f; f = f.m_next) {
s = f.GetShape();
if (b.IsActive() == false) {
color.Set(0.5, 0.5, 0.3);
this.DrawShape(s, xf, color);
}
else if (b.GetType() == b2Body.b2_staticBody) {
color.Set(0.5, 0.9, 0.5);
this.DrawShape(s, xf, color);
}
else if (b.GetType() == b2Body.b2_kinematicBody) {
color.Set(0.5, 0.5, 0.9);
this.DrawShape(s, xf, color);
}
else if (b.IsAwake() == false) {
color.Set(0.6, 0.6, 0.6);
this.DrawShape(s, xf, color);
}
else {
color.Set(0.9, 0.7, 0.7);
this.DrawShape(s, xf, color);
}
}
}
}
if (flags & b2DebugDraw.e_jointBit) {
for (j = this.m_jointList;
j; j = j.m_next) {
this.DrawJoint(j);
}
}
if (flags & b2DebugDraw.e_controllerBit) {
for (var c = this.m_controllerList; c; c = c.m_next) {
c.Draw(this.m_debugDraw);
}
}
if (flags & b2DebugDraw.e_pairBit) {
color.Set(0.3, 0.9, 0.9);
for (var contact = this.m_contactManager.m_contactList; contact; contact = contact.GetNext()) {
var fixtureA = contact.GetFixtureA();
var fixtureB = contact.GetFixtureB();
var cA = fixtureA.GetAABB().GetCenter();
var cB = fixtureB.GetAABB().GetCenter();
this.m_debugDraw.DrawSegment(cA, cB, color);
}
}
if (flags & b2DebugDraw.e_aabbBit) {
bp = this.m_contactManager.m_broadPhase;
vs = [new b2Vec2(), new b2Vec2(), new b2Vec2(), new b2Vec2()];
for (b = this.m_bodyList;
b; b = b.GetNext()) {
if (b.IsActive() == false) {
continue;
}
for (f = b.GetFixtureList();
f; f = f.GetNext()) {
var aabb = bp.GetFatAABB(f.m_proxy);
vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y);
vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y);
vs[2].Set(aabb.upperBound.x, aabb.upperBound.y);
vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y);
this.m_debugDraw.DrawPolygon(vs, 4, color);
}
}
}
if (flags & b2DebugDraw.e_centerOfMassBit) {
for (b = this.m_bodyList;
b; b = b.m_next) {
xf = b2World.s_xf;
xf.R = b.m_xf.R;
xf.position = b.GetWorldCenter();
this.m_debugDraw.DrawTransform(xf);
}
}
}
b2World.prototype.QueryAABB = function (callback, aabb) {
var __this = this;
var broadPhase = __this.m_contactManager.m_broadPhase;
function WorldQueryWrapper(proxy) {
return callback(broadPhase.GetUserData(proxy));
};
broadPhase.Query(WorldQueryWrapper, aabb);
}
b2World.prototype.QueryShape = function (callback, shape, transform) {
var __this = this;
if (transform === undefined) transform = null;
if (transform == null) {
transform = new b2Transform();
transform.SetIdentity();
}
var broadPhase = __this.m_contactManager.m_broadPhase;
function WorldQueryWrapper(proxy) {
var fixture = (broadPhase.GetUserData(proxy) instanceof b2Fixture ? broadPhase.GetUserData(proxy) : null);
if (b2Shape.TestOverlap(shape, transform, fixture.GetShape(), fixture.GetBody().GetTransform())) return callback(fixture);
return true;
};
var aabb = new b2AABB();
shape.ComputeAABB(aabb, transform);
broadPhase.Query(WorldQueryWrapper, aabb);
}
b2World.prototype.QueryPoint = function (callback, p) {
var __this = this;
var broadPhase = __this.m_contactManager.m_broadPhase;
function WorldQueryWrapper(proxy) {
var fixture = (broadPhase.GetUserData(proxy) instanceof b2Fixture ? broadPhase.GetUserData(proxy) : null);
if (fixture.TestPoint(p)) return callback(fixture);
return true;
};
var aabb = new b2AABB();
aabb.lowerBound.Set(p.x - b2Settings.b2_linearSlop, p.y - b2Settings.b2_linearSlop);
aabb.upperBound.Set(p.x + b2Settings.b2_linearSlop, p.y + b2Settings.b2_linearSlop);
broadPhase.Query(WorldQueryWrapper, aabb);
}
b2World.prototype.RayCast = function (callback, point1, point2) {
var __this = this;
var broadPhase = __this.m_contactManager.m_broadPhase;
var output = new b2RayCastOutput;
function RayCastWrapper(input, proxy) {
var userData = broadPhase.GetUserData(proxy);
var fixture = (userData instanceof b2Fixture ? userData : null);
var hit = fixture.RayCast(output, input);
if (hit) {
var fraction = output.fraction;
var point = new b2Vec2((1.0 - fraction) * point1.x + fraction * point2.x, (1.0 - fraction) * point1.y + fraction * point2.y);
return callback(fixture, point, output.normal, fraction);
}
return input.maxFraction;
};
var input = new b2RayCastInput(point1, point2);
broadPhase.RayCast(RayCastWrapper, input);
}
b2World.prototype.RayCastOne = function (point1, point2) {
var __this = this;
var result;
function RayCastOneWrapper(fixture, point, normal, fraction) {
if (fraction === undefined) fraction = 0;
result = fixture;
return fraction;
};
__this.RayCast(RayCastOneWrapper, point1, point2);
return result;
}
b2World.prototype.RayCastAll = function (point1, point2) {
var __this = this;
var result = new Vector();
function RayCastAllWrapper(fixture, point, normal, fraction) {
if (fraction === undefined) fraction = 0;
result[result.length] = fixture;
return 1;
};
__this.RayCast(RayCastAllWrapper, point1, point2);
return result;
}
b2World.prototype.GetBodyList = function () {
return this.m_bodyList;
}
b2World.prototype.GetJointList = function () {
return this.m_jointList;
}
b2World.prototype.GetContactList = function () {
return this.m_contactList;
}
b2World.prototype.IsLocked = function () {
return (this.m_flags & b2World.e_locked) > 0;
}
b2World.prototype.Solve = function (step) {
var b;
for (var controller = this.m_controllerList; controller; controller = controller.m_next) {
controller.Step(step);
}
var island = this.m_island;
island.Initialize(this.m_bodyCount, this.m_contactCount, this.m_jointCount, null, this.m_contactManager.m_contactListener, this.m_contactSolver);
for (b = this.m_bodyList;
b; b = b.m_next) {
b.m_flags &= ~b2Body.e_islandFlag;
}
for (var c = this.m_contactList; c; c = c.m_next) {
c.m_flags &= ~b2Contact.e_islandFlag;
}
for (var j = this.m_jointList; j; j = j.m_next) {
j.m_islandFlag = false;
}
var stackSize = parseInt(this.m_bodyCount);
var stack = this.s_stack;
for (var seed = this.m_bodyList; seed; seed = seed.m_next) {
if (seed.m_flags & b2Body.e_islandFlag) {
continue;
}
if (seed.IsAwake() == false || seed.IsActive() == false) {
continue;
}
if (seed.GetType() == b2Body.b2_staticBody) {
continue;
}
island.Clear();
var stackCount = 0;
stack[stackCount++] = seed;
seed.m_flags |= b2Body.e_islandFlag;
while (stackCount > 0) {
b = stack[--stackCount];
island.AddBody(b);
if (b.IsAwake() == false) {
b.SetAwake(true);
}
if (b.GetType() == b2Body.b2_staticBody) {
continue;
}
var other;
for (var ce = b.m_contactList; ce; ce = ce.next) {
if (ce.contact.m_flags & b2Contact.e_islandFlag) {
continue;
}
if (ce.contact.IsSensor() == true || ce.contact.IsEnabled() == false || ce.contact.IsTouching() == false) {
continue;
}
island.AddContact(ce.contact);
ce.contact.m_flags |= b2Contact.e_islandFlag;
other = ce.other;
if (other.m_flags & b2Body.e_islandFlag) {
continue;
}
stack[stackCount++] = other;
other.m_flags |= b2Body.e_islandFlag;
}
for (var jn = b.m_jointList; jn; jn = jn.next) {
if (jn.joint.m_islandFlag == true) {
continue;
}
other = jn.other;
if (other.IsActive() == false) {
continue;
}
island.AddJoint(jn.joint);
jn.joint.m_islandFlag = true;
if (other.m_flags & b2Body.e_islandFlag) {
continue;
}
stack[stackCount++] = other;
other.m_flags |= b2Body.e_islandFlag;
}
}
island.Solve(step, this.m_gravity, this.m_allowSleep);
for (var i = 0; i < island.m_bodyCount; ++i) {
b = island.m_bodies[i];
if (b.GetType() == b2Body.b2_staticBody) {
b.m_flags &= ~b2Body.e_islandFlag;
}
}
}
for (i = 0;
i < stack.length; ++i) {
if (!stack[i]) break;
stack[i] = null;
}
for (b = this.m_bodyList;
b; b = b.m_next) {
if (b.IsAwake() == false || b.IsActive() == false) {
continue;
}
if (b.GetType() == b2Body.b2_staticBody) {
continue;
}
b.SynchronizeFixtures();
}
this.m_contactManager.FindNewContacts();
}
b2World.prototype.SolveTOI = function (step) {
var b;
var fA;
var fB;
var bA;
var bB;
var cEdge;
var j;
var island = this.m_island;
island.Initialize(this.m_bodyCount, b2Settings.b2_maxTOIContactsPerIsland, b2Settings.b2_maxTOIJointsPerIsland, null, this.m_contactManager.m_contactListener, this.m_contactSolver);
var queue = b2World.s_queue;
for (b = this.m_bodyList;
b; b = b.m_next) {
b.m_flags &= ~b2Body.e_islandFlag;
b.m_sweep.t0 = 0.0;
}
var c;
for (c = this.m_contactList;
c; c = c.m_next) {
c.m_flags &= ~ (b2Contact.e_toiFlag | b2Contact.e_islandFlag);
}
for (j = this.m_jointList;
j; j = j.m_next) {
j.m_islandFlag = false;
}
for (;;) {
var minContact = null;
var minTOI = 1.0;
for (c = this.m_contactList;
c; c = c.m_next) {
if (c.IsSensor() == true || c.IsEnabled() == false || c.IsContinuous() == false) {
continue;
}
var toi = 1.0;
if (c.m_flags & b2Contact.e_toiFlag) {
toi = c.m_toi;
}
else {
fA = c.m_fixtureA;
fB = c.m_fixtureB;
bA = fA.m_body;
bB = fB.m_body;
if ((bA.GetType() != b2Body.b2_dynamicBody || bA.IsAwake() == false) && (bB.GetType() != b2Body.b2_dynamicBody || bB.IsAwake() == false)) {
continue;
}
var t0 = bA.m_sweep.t0;
if (bA.m_sweep.t0 < bB.m_sweep.t0) {
t0 = bB.m_sweep.t0;
bA.m_sweep.Advance(t0);
}
else if (bB.m_sweep.t0 < bA.m_sweep.t0) {
t0 = bA.m_sweep.t0;
bB.m_sweep.Advance(t0);
}
toi = c.ComputeTOI(bA.m_sweep, bB.m_sweep);
b2Settings.b2Assert(0.0 <= toi && toi <= 1.0);
if (toi > 0.0 && toi < 1.0) {
toi = (1.0 - toi) * t0 + toi;
if (toi > 1) toi = 1;
}
c.m_toi = toi;
c.m_flags |= b2Contact.e_toiFlag;
}
if (Number.MIN_VALUE < toi && toi < minTOI) {
minContact = c;
minTOI = toi;
}
}
if (minContact == null || 1.0 - 100.0 * Number.MIN_VALUE < minTOI) {
break;
}
fA = minContact.m_fixtureA;
fB = minContact.m_fixtureB;
bA = fA.m_body;
bB = fB.m_body;
b2World.s_backupA.Set(bA.m_sweep);
b2World.s_backupB.Set(bB.m_sweep);
bA.Advance(minTOI);
bB.Advance(minTOI);
minContact.Update(this.m_contactManager.m_contactListener);
minContact.m_flags &= ~b2Contact.e_toiFlag;
if (minContact.IsSensor() == true || minContact.IsEnabled() == false) {
bA.m_sweep.Set(b2World.s_backupA);
bB.m_sweep.Set(b2World.s_backupB);
bA.SynchronizeTransform();
bB.SynchronizeTransform();
continue;
}
if (minContact.IsTouching() == false) {
continue;
}
var seed = bA;
if (seed.GetType() != b2Body.b2_dynamicBody) {
seed = bB;
}
island.Clear();
var queueStart = 0;
var queueSize = 0;
queue[queueStart + queueSize++] = seed;
seed.m_flags |= b2Body.e_islandFlag;
while (queueSize > 0) {
b = queue[queueStart++];
--queueSize;
island.AddBody(b);
if (b.IsAwake() == false) {
b.SetAwake(true);
}
if (b.GetType() != b2Body.b2_dynamicBody) {
continue;
}
for (cEdge = b.m_contactList;
cEdge; cEdge = cEdge.next) {
if (island.m_contactCount == island.m_contactCapacity) {
break;
}
if (cEdge.contact.m_flags & b2Contact.e_islandFlag) {
continue;
}
if (cEdge.contact.IsSensor() == true || cEdge.contact.IsEnabled() == false || cEdge.contact.IsTouching() == false) {
continue;
}
island.AddContact(cEdge.contact);
cEdge.contact.m_flags |= b2Contact.e_islandFlag;
var other = cEdge.other;
if (other.m_flags & b2Body.e_islandFlag) {
continue;
}
if (other.GetType() != b2Body.b2_staticBody) {
other.Advance(minTOI);
other.SetAwake(true);
}
queue[queueStart + queueSize] = other;
++queueSize;
other.m_flags |= b2Body.e_islandFlag;
}
for (var jEdge = b.m_jointList; jEdge; jEdge = jEdge.next) {
if (island.m_jointCount == island.m_jointCapacity) continue;
if (jEdge.joint.m_islandFlag == true) continue;
other = jEdge.other;
if (other.IsActive() == false) {
continue;
}
island.AddJoint(jEdge.joint);
jEdge.joint.m_islandFlag = true;
if (other.m_flags & b2Body.e_islandFlag) continue;
if (other.GetType() != b2Body.b2_staticBody) {
other.Advance(minTOI);
other.SetAwake(true);
}
queue[queueStart + queueSize] = other;
++queueSize;
other.m_flags |= b2Body.e_islandFlag;
}
}
var subStep = b2World.s_timestep;
subStep.warmStarting = false;
subStep.dt = (1.0 - minTOI) * step.dt;
subStep.inv_dt = 1.0 / subStep.dt;
subStep.dtRatio = 0.0;
subStep.velocityIterations = step.velocityIterations;
subStep.positionIterations = step.positionIterations;
island.SolveTOI(subStep);
var i = 0;
for (i = 0;
i < island.m_bodyCount; ++i) {
b = island.m_bodies[i];
b.m_flags &= ~b2Body.e_islandFlag;
if (b.IsAwake() == false) {
continue;
}
if (b.GetType() != b2Body.b2_dynamicBody) {
continue;
}
b.SynchronizeFixtures();
for (cEdge = b.m_contactList;
cEdge; cEdge = cEdge.next) {
cEdge.contact.m_flags &= ~b2Contact.e_toiFlag;
}
}
for (i = 0;
i < island.m_contactCount; ++i) {
c = island.m_contacts[i];
c.m_flags &= ~ (b2Contact.e_toiFlag | b2Contact.e_islandFlag);
}
for (i = 0;
i < island.m_jointCount; ++i) {
j = island.m_joints[i];
j.m_islandFlag = false;
}
this.m_contactManager.FindNewContacts();
}
}
b2World.prototype.DrawJoint = function (joint) {
var b1 = joint.GetBodyA();
var b2 = joint.GetBodyB();
var xf1 = b1.m_xf;
var xf2 = b2.m_xf;
var x1 = xf1.position;
var x2 = xf2.position;
var p1 = joint.GetAnchorA();
var p2 = joint.GetAnchorB();
var color = b2World.s_jointColor;
switch (joint.m_type) {
case b2Joint.e_distanceJoint:
this.m_debugDraw.DrawSegment(p1, p2, color);
break;
case b2Joint.e_pulleyJoint:
{
var pulley = ((joint instanceof b2PulleyJoint ? joint : null));
var s1 = pulley.GetGroundAnchorA();
var s2 = pulley.GetGroundAnchorB();
this.m_debugDraw.DrawSegment(s1, p1, color);
this.m_debugDraw.DrawSegment(s2, p2, color);
this.m_debugDraw.DrawSegment(s1, s2, color);
}
break;
case b2Joint.e_mouseJoint:
this.m_debugDraw.DrawSegment(p1, p2, color);
break;
default:
if (b1 != this.m_groundBody) this.m_debugDraw.DrawSegment(x1, p1, color);
this.m_debugDraw.DrawSegment(p1, p2, color);
if (b2 != this.m_groundBody) this.m_debugDraw.DrawSegment(x2, p2, color);
}
}
b2World.prototype.DrawShape = function (shape, xf, color) {
switch (shape.m_type) {
case b2Shape.e_circleShape:
{
var circle = ((shape instanceof b2CircleShape ? shape : null));
var center = b2Math.MulX(xf, circle.m_p);
var radius = circle.m_radius;
var axis = xf.R.col1;
this.m_debugDraw.DrawSolidCircle(center, radius, axis, color);
}
break;
case b2Shape.e_polygonShape:
{
var i = 0;
var poly = ((shape instanceof b2PolygonShape ? shape : null));
var vertexCount = parseInt(poly.GetVertexCount());
var localVertices = poly.GetVertices();
var vertices = new Vector(vertexCount);
for (i = 0;
i < vertexCount; ++i) {
vertices[i] = b2Math.MulX(xf, localVertices[i]);
}
this.m_debugDraw.DrawSolidPolygon(vertices, vertexCount, color);
}
break;
case b2Shape.e_edgeShape:
{
var edge = (shape instanceof b2EdgeShape ? shape : null);
this.m_debugDraw.DrawSegment(b2Math.MulX(xf, edge.GetVertex1()), b2Math.MulX(xf, edge.GetVertex2()), color);
}
break;
}
}
_A2J_postDefs.push(function () {
Box2D.Dynamics.b2World.s_timestep2 = new b2TimeStep();
Box2D.Dynamics.b2World.prototype.s_timestep2 = Box2D.Dynamics.b2World.s_timestep2;
Box2D.Dynamics.b2World.s_xf = new b2Transform();
Box2D.Dynamics.b2World.prototype.s_xf = Box2D.Dynamics.b2World.s_xf;
Box2D.Dynamics.b2World.s_backupA = new b2Sweep();
Box2D.Dynamics.b2World.prototype.s_backupA = Box2D.Dynamics.b2World.s_backupA;
Box2D.Dynamics.b2World.s_backupB = new b2Sweep();
Box2D.Dynamics.b2World.prototype.s_backupB = Box2D.Dynamics.b2World.s_backupB;
Box2D.Dynamics.b2World.s_timestep = new b2TimeStep();
Box2D.Dynamics.b2World.prototype.s_timestep = Box2D.Dynamics.b2World.s_timestep;
Box2D.Dynamics.b2World.s_queue = new Vector();
Box2D.Dynamics.b2World.prototype.s_queue = Box2D.Dynamics.b2World.s_queue;
Box2D.Dynamics.b2World.s_jointColor = new b2Color(0.5, 0.8, 0.8);
Box2D.Dynamics.b2World.prototype.s_jointColor = Box2D.Dynamics.b2World.s_jointColor;
Box2D.Dynamics.b2World.e_newFixture = 0x0001;
Box2D.Dynamics.b2World.prototype.e_newFixture = Box2D.Dynamics.b2World.e_newFixture;
Box2D.Dynamics.b2World.e_locked = 0x0002;
Box2D.Dynamics.b2World.prototype.e_locked = Box2D.Dynamics.b2World.e_locked;
});
})(); /* source: disabled*/
(function () {
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2EdgeChainDef = Box2D.Collision.Shapes.b2EdgeChainDef;
var b2EdgeShape = Box2D.Collision.Shapes.b2EdgeShape;
var b2MassData = Box2D.Collision.Shapes.b2MassData;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2Shape = Box2D.Collision.Shapes.b2Shape;
var b2CircleContact = Box2D.Dynamics.Contacts.b2CircleContact;
var b2Contact = Box2D.Dynamics.Contacts.b2Contact;
var b2ContactConstraint = Box2D.Dynamics.Contacts.b2ContactConstraint;
var b2ContactConstraintPoint = Box2D.Dynamics.Contacts.b2ContactConstraintPoint;
var b2ContactEdge = Box2D.Dynamics.Contacts.b2ContactEdge;
var b2ContactFactory = Box2D.Dynamics.Contacts.b2ContactFactory;
var b2ContactRegister = Box2D.Dynamics.Contacts.b2ContactRegister;
var b2ContactResult = Box2D.Dynamics.Contacts.b2ContactResult;
var b2ContactSolver = Box2D.Dynamics.Contacts.b2ContactSolver;
var b2EdgeAndCircleContact = Box2D.Dynamics.Contacts.b2EdgeAndCircleContact;
var b2NullContact = Box2D.Dynamics.Contacts.b2NullContact;
var b2PolyAndCircleContact = Box2D.Dynamics.Contacts.b2PolyAndCircleContact;
var b2PolyAndEdgeContact = Box2D.Dynamics.Contacts.b2PolyAndEdgeContact;
var b2PolygonContact = Box2D.Dynamics.Contacts.b2PolygonContact;
var b2PositionSolverManifold = Box2D.Dynamics.Contacts.b2PositionSolverManifold;
var b2Body = Box2D.Dynamics.b2Body;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2ContactFilter = Box2D.Dynamics.b2ContactFilter;
var b2ContactImpulse = Box2D.Dynamics.b2ContactImpulse;
var b2ContactListener = Box2D.Dynamics.b2ContactListener;
var b2ContactManager = Box2D.Dynamics.b2ContactManager;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var b2DestructionListener = Box2D.Dynamics.b2DestructionListener;
var b2FilterData = Box2D.Dynamics.b2FilterData;
var b2Fixture = Box2D.Dynamics.b2Fixture;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2Island = Box2D.Dynamics.b2Island;
var b2TimeStep = Box2D.Dynamics.b2TimeStep;
var b2World = Box2D.Dynamics.b2World;
var b2Color = Box2D.Common.b2Color;
var b2internal = Box2D.Common.b2internal;
var b2Settings = Box2D.Common.b2Settings;
var b2Mat22 = Box2D.Common.Math.b2Mat22;
var b2Mat33 = Box2D.Common.Math.b2Mat33;
var b2Math = Box2D.Common.Math.b2Math;
var b2Sweep = Box2D.Common.Math.b2Sweep;
var b2Transform = Box2D.Common.Math.b2Transform;
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2Vec3 = Box2D.Common.Math.b2Vec3;
var b2AABB = Box2D.Collision.b2AABB;
var b2Bound = Box2D.Collision.b2Bound;
var b2BoundValues = Box2D.Collision.b2BoundValues;
var b2BroadPhase = Box2D.Collision.b2BroadPhase;
var b2Collision = Box2D.Collision.b2Collision;
var b2ContactID = Box2D.Collision.b2ContactID;
var b2ContactPoint = Box2D.Collision.b2ContactPoint;
var b2Distance = Box2D.Collision.b2Distance;
var b2DistanceInput = Box2D.Collision.b2DistanceInput;
var b2DistanceOutput = Box2D.Collision.b2DistanceOutput;
var b2DistanceProxy = Box2D.Collision.b2DistanceProxy;
var b2DynamicTree = Box2D.Collision.b2DynamicTree;
var b2DynamicTreeBroadPhase = Box2D.Collision.b2DynamicTreeBroadPhase;
var b2DynamicTreeNode = Box2D.Collision.b2DynamicTreeNode;
var b2DynamicTreePair = Box2D.Collision.b2DynamicTreePair;
var b2Manifold = Box2D.Collision.b2Manifold;
var b2ManifoldPoint = Box2D.Collision.b2ManifoldPoint;
var b2OBB = Box2D.Collision.b2OBB;
var b2Pair = Box2D.Collision.b2Pair;
var b2PairManager = Box2D.Collision.b2PairManager;
var b2Point = Box2D.Collision.b2Point;
var b2Proxy = Box2D.Collision.b2Proxy;
var b2RayCastInput = Box2D.Collision.b2RayCastInput;
var b2RayCastOutput = Box2D.Collision.b2RayCastOutput;
var b2Segment = Box2D.Collision.b2Segment;
var b2SeparationFunction = Box2D.Collision.b2SeparationFunction;
var b2Simplex = Box2D.Collision.b2Simplex;
var b2SimplexCache = Box2D.Collision.b2SimplexCache;
var b2SimplexVertex = Box2D.Collision.b2SimplexVertex;
var b2TimeOfImpact = Box2D.Collision.b2TimeOfImpact;
var b2TOIInput = Box2D.Collision.b2TOIInput;
var b2WorldManifold = Box2D.Collision.b2WorldManifold;
var ClipVertex = Box2D.Collision.ClipVertex;
var Features = Box2D.Collision.Features;
var IBroadPhase = Box2D.Collision.IBroadPhase;
var b2internal = Box2D.Common.b2internal;
var b2CircleContact = Box2D.Dynamics.Contacts.b2CircleContact;
var b2Contact = Box2D.Dynamics.Contacts.b2Contact;
var b2ContactConstraint = Box2D.Dynamics.Contacts.b2ContactConstraint;
var b2ContactConstraintPoint = Box2D.Dynamics.Contacts.b2ContactConstraintPoint;
var b2ContactEdge = Box2D.Dynamics.Contacts.b2ContactEdge;
var b2ContactFactory = Box2D.Dynamics.Contacts.b2ContactFactory;
var b2ContactRegister = Box2D.Dynamics.Contacts.b2ContactRegister;
var b2ContactResult = Box2D.Dynamics.Contacts.b2ContactResult;
var b2ContactSolver = Box2D.Dynamics.Contacts.b2ContactSolver;
var b2EdgeAndCircleContact = Box2D.Dynamics.Contacts.b2EdgeAndCircleContact;
var b2NullContact = Box2D.Dynamics.Contacts.b2NullContact;
var b2PolyAndCircleContact = Box2D.Dynamics.Contacts.b2PolyAndCircleContact;
var b2PolyAndEdgeContact = Box2D.Dynamics.Contacts.b2PolyAndEdgeContact;
var b2PolygonContact = Box2D.Dynamics.Contacts.b2PolygonContact;
var b2PositionSolverManifold = Box2D.Dynamics.Contacts.b2PositionSolverManifold;
b2CircleContact.inherit(Box2D.Dynamics.Contacts.b2Contact);
b2CircleContact.prototype.__super = Box2D.Dynamics.Contacts.b2Contact.prototype;
b2CircleContact.b2CircleContact = function () {
Box2D.Dynamics.Contacts.b2Contact.b2Contact.apply(this, arguments);
};
b2CircleContact.prototype.Create = function (allocator) {
return new b2CircleContact();
}
b2CircleContact.Create = b2CircleContact.prototype.Create;
b2CircleContact.prototype.Destroy = function (contact, allocator) {}
b2CircleContact.Destroy = b2CircleContact.prototype.Destroy;
b2CircleContact.prototype.Reset = function (fixtureA, fixtureB) {
this.__super.Reset.call(this, fixtureA, fixtureB);
}
b2CircleContact.prototype.Evaluate = function () {
var bA = this.m_fixtureA.GetBody();
var bB = this.m_fixtureB.GetBody();
b2Collision.CollideCircles(this.m_manifold, (this.m_fixtureA.GetShape() instanceof b2CircleShape ? this.m_fixtureA.GetShape() : null), bA.m_xf, (this.m_fixtureB.GetShape() instanceof b2CircleShape ? this.m_fixtureB.GetShape() : null), bB.m_xf);
}
b2Contact.b2Contact = function () {
this.m_nodeA = new b2ContactEdge();
this.m_nodeB = new b2ContactEdge();
this.m_manifold = new b2Manifold();
this.m_oldManifold = new b2Manifold();
};
b2Contact.prototype.GetManifold = function () {
return this.m_manifold;
}
b2Contact.prototype.GetWorldManifold = function (worldManifold) {
var bodyA = this.m_fixtureA.GetBody();
var bodyB = this.m_fixtureB.GetBody();
var shapeA = this.m_fixtureA.GetShape();
var shapeB = this.m_fixtureB.GetShape();
worldManifold.Initialize(this.m_manifold, bodyA.GetTransform(), shapeA.m_radius, bodyB.GetTransform(), shapeB.m_radius);
}
b2Contact.prototype.IsTouching = function () {
return (this.m_flags & b2Contact.e_touchingFlag) == b2Contact.e_touchingFlag;
}
b2Contact.prototype.IsContinuous = function () {
return (this.m_flags & b2Contact.e_continuousFlag) == b2Contact.e_continuousFlag;
}
b2Contact.prototype.SetSensor = function (sensor) {
if (sensor) {
this.m_flags |= b2Contact.e_sensorFlag;
}
else {
this.m_flags &= ~b2Contact.e_sensorFlag;
}
}
b2Contact.prototype.IsSensor = function () {
return (this.m_flags & b2Contact.e_sensorFlag) == b2Contact.e_sensorFlag;
}
b2Contact.prototype.SetEnabled = function (flag) {
if (flag) {
this.m_flags |= b2Contact.e_enabledFlag;
}
else {
this.m_flags &= ~b2Contact.e_enabledFlag;
}
}
b2Contact.prototype.IsEnabled = function () {
return (this.m_flags & b2Contact.e_enabledFlag) == b2Contact.e_enabledFlag;
}
b2Contact.prototype.GetNext = function () {
return this.m_next;
}
b2Contact.prototype.GetFixtureA = function () {
return this.m_fixtureA;
}
b2Contact.prototype.GetFixtureB = function () {
return this.m_fixtureB;
}
b2Contact.prototype.FlagForFiltering = function () {
this.m_flags |= b2Contact.e_filterFlag;
}
b2Contact.prototype.b2Contact = function () {}
b2Contact.prototype.Reset = function (fixtureA, fixtureB) {
if (fixtureA === undefined) fixtureA = null;
if (fixtureB === undefined) fixtureB = null;
this.m_flags = b2Contact.e_enabledFlag;
if (!fixtureA || !fixtureB) {
this.m_fixtureA = null;
this.m_fixtureB = null;
return;
}
if (fixtureA.IsSensor() || fixtureB.IsSensor()) {
this.m_flags |= b2Contact.e_sensorFlag;
}
var bodyA = fixtureA.GetBody();
var bodyB = fixtureB.GetBody();
if (bodyA.GetType() != b2Body.b2_dynamicBody || bodyA.IsBullet() || bodyB.GetType() != b2Body.b2_dynamicBody || bodyB.IsBullet()) {
this.m_flags |= b2Contact.e_continuousFlag;
}
this.m_fixtureA = fixtureA;
this.m_fixtureB = fixtureB;
this.m_manifold.m_pointCount = 0;
this.m_prev = null;
this.m_next = null;
this.m_nodeA.contact = null;
this.m_nodeA.prev = null;
this.m_nodeA.next = null;
this.m_nodeA.other = null;
this.m_nodeB.contact = null;
this.m_nodeB.prev = null;
this.m_nodeB.next = null;
this.m_nodeB.other = null;
}
b2Contact.prototype.Update = function (listener) {
var tManifold = this.m_oldManifold;
this.m_oldManifold = this.m_manifold;
this.m_manifold = tManifold;
this.m_flags |= b2Contact.e_enabledFlag;
var touching = false;
var wasTouching = (this.m_flags & b2Contact.e_touchingFlag) == b2Contact.e_touchingFlag;
var bodyA = this.m_fixtureA.m_body;
var bodyB = this.m_fixtureB.m_body;
var aabbOverlap = this.m_fixtureA.m_aabb.TestOverlap(this.m_fixtureB.m_aabb);
if (this.m_flags & b2Contact.e_sensorFlag) {
if (aabbOverlap) {
var shapeA = this.m_fixtureA.GetShape();
var shapeB = this.m_fixtureB.GetShape();
var xfA = bodyA.GetTransform();
var xfB = bodyB.GetTransform();
touching = b2Shape.TestOverlap(shapeA, xfA, shapeB, xfB);
}
this.m_manifold.m_pointCount = 0;
}
else {
if (bodyA.GetType() != b2Body.b2_dynamicBody || bodyA.IsBullet() || bodyB.GetType() != b2Body.b2_dynamicBody || bodyB.IsBullet()) {
this.m_flags |= b2Contact.e_continuousFlag;
}
else {
this.m_flags &= ~b2Contact.e_continuousFlag;
}
if (aabbOverlap) {
this.Evaluate();
touching = this.m_manifold.m_pointCount > 0;
for (var i = 0; i < this.m_manifold.m_pointCount; ++i) {
var mp2 = this.m_manifold.m_points[i];
mp2.m_normalImpulse = 0.0;
mp2.m_tangentImpulse = 0.0;
var id2 = mp2.m_id;
for (var j = 0; j < this.m_oldManifold.m_pointCount; ++j) {
var mp1 = this.m_oldManifold.m_points[j];
if (mp1.m_id.key == id2.key) {
mp2.m_normalImpulse = mp1.m_normalImpulse;
mp2.m_tangentImpulse = mp1.m_tangentImpulse;
break;
}
}
}
}
else {
this.m_manifold.m_pointCount = 0;
}
if (touching != wasTouching) {
bodyA.SetAwake(true);
bodyB.SetAwake(true);
}
}
if (touching) {
this.m_flags |= b2Contact.e_touchingFlag;
}
else {
this.m_flags &= ~b2Contact.e_touchingFlag;
}
if (wasTouching == false && touching == true) {
listener.BeginContact(this);
}
if (wasTouching == true && touching == false) {
listener.EndContact(this);
}
if ((this.m_flags & b2Contact.e_sensorFlag) == 0) {
listener.PreSolve(this, this.m_oldManifold);
}
}
b2Contact.prototype.Evaluate = function () {}
b2Contact.prototype.ComputeTOI = function (sweepA, sweepB) {
b2Contact.s_input.proxyA.Set(this.m_fixtureA.GetShape());
b2Contact.s_input.proxyB.Set(this.m_fixtureB.GetShape());
b2Contact.s_input.sweepA = sweepA;
b2Contact.s_input.sweepB = sweepB;
b2Contact.s_input.tolerance = b2Settings.b2_linearSlop;
return b2TimeOfImpact.TimeOfImpact(b2Contact.s_input);
}
_A2J_postDefs.push(function () {
Box2D.Dynamics.Contacts.b2Contact.e_sensorFlag = 0x0001;
Box2D.Dynamics.Contacts.b2Contact.prototype.e_sensorFlag = Box2D.Dynamics.Contacts.b2Contact.e_sensorFlag;
Box2D.Dynamics.Contacts.b2Contact.e_continuousFlag = 0x0002;
Box2D.Dynamics.Contacts.b2Contact.prototype.e_continuousFlag = Box2D.Dynamics.Contacts.b2Contact.e_continuousFlag;
Box2D.Dynamics.Contacts.b2Contact.e_islandFlag = 0x0004;
Box2D.Dynamics.Contacts.b2Contact.prototype.e_islandFlag = Box2D.Dynamics.Contacts.b2Contact.e_islandFlag;
Box2D.Dynamics.Contacts.b2Contact.e_toiFlag = 0x0008;
Box2D.Dynamics.Contacts.b2Contact.prototype.e_toiFlag = Box2D.Dynamics.Contacts.b2Contact.e_toiFlag;
Box2D.Dynamics.Contacts.b2Contact.e_touchingFlag = 0x0010;
Box2D.Dynamics.Contacts.b2Contact.prototype.e_touchingFlag = Box2D.Dynamics.Contacts.b2Contact.e_touchingFlag;
Box2D.Dynamics.Contacts.b2Contact.e_enabledFlag = 0x0020;
Box2D.Dynamics.Contacts.b2Contact.prototype.e_enabledFlag = Box2D.Dynamics.Contacts.b2Contact.e_enabledFlag;
Box2D.Dynamics.Contacts.b2Contact.e_filterFlag = 0x0040;
Box2D.Dynamics.Contacts.b2Contact.prototype.e_filterFlag = Box2D.Dynamics.Contacts.b2Contact.e_filterFlag;
Box2D.Dynamics.Contacts.b2Contact.s_input = new b2TOIInput();
Box2D.Dynamics.Contacts.b2Contact.prototype.s_input = Box2D.Dynamics.Contacts.b2Contact.s_input;
});
b2ContactConstraint.b2ContactConstraint = function () {
this.localPlaneNormal = new b2Vec2();
this.localPoint = new b2Vec2();
this.normal = new b2Vec2();
this.normalMass = new b2Mat22();
this.K = new b2Mat22();
};
b2ContactConstraint.prototype.b2ContactConstraint = function () {
this.points = new Vector(b2Settings.b2_maxManifoldPoints);
for (var i = 0; i < b2Settings.b2_maxManifoldPoints; i++) {
this.points[i] = new b2ContactConstraintPoint();
}
}
b2ContactConstraintPoint.b2ContactConstraintPoint = function () {
this.localPoint = new b2Vec2();
this.rA = new b2Vec2();
this.rB = new b2Vec2();
};
b2ContactEdge.b2ContactEdge = function () {};
b2ContactFactory.b2ContactFactory = function () {};
b2ContactFactory.prototype.b2ContactFactory = function (allocator) {
this.m_allocator = allocator;
this.InitializeRegisters();
}
b2ContactFactory.prototype.AddType = function (createFcn, destroyFcn, type1, type2) {
if (type1 === undefined) type1 = 0;
if (type2 === undefined) type2 = 0;
this.m_registers[type1][type2].createFcn = createFcn;
this.m_registers[type1][type2].destroyFcn = destroyFcn;
this.m_registers[type1][type2].primary = true;
if (type1 != type2) {
this.m_registers[type2][type1].createFcn = createFcn;
this.m_registers[type2][type1].destroyFcn = destroyFcn;
this.m_registers[type2][type1].primary = false;
}
}
b2ContactFactory.prototype.InitializeRegisters = function () {
this.m_registers = new Vector(b2Shape.e_shapeTypeCount);
for (var i = 0; i < b2Shape.e_shapeTypeCount; i++) {
this.m_registers[i] = new Vector(b2Shape.e_shapeTypeCount);
for (var j = 0; j < b2Shape.e_shapeTypeCount; j++) {
this.m_registers[i][j] = new b2ContactRegister();
}
}
this.AddType(b2CircleContact.Create, b2CircleContact.Destroy, b2Shape.e_circleShape, b2Shape.e_circleShape);
this.AddType(b2PolyAndCircleContact.Create, b2PolyAndCircleContact.Destroy, b2Shape.e_polygonShape, b2Shape.e_circleShape);
this.AddType(b2PolygonContact.Create, b2PolygonContact.Destroy, b2Shape.e_polygonShape, b2Shape.e_polygonShape);
this.AddType(b2EdgeAndCircleContact.Create, b2EdgeAndCircleContact.Destroy, b2Shape.e_edgeShape, b2Shape.e_circleShape);
this.AddType(b2PolyAndEdgeContact.Create, b2PolyAndEdgeContact.Destroy, b2Shape.e_polygonShape, b2Shape.e_edgeShape);
}
b2ContactFactory.prototype.Create = function (fixtureA, fixtureB) {
var type1 = parseInt(fixtureA.GetType());
var type2 = parseInt(fixtureB.GetType());
var reg = this.m_registers[type1][type2];
var c;
if (reg.pool) {
c = reg.pool;
reg.pool = c.m_next;
reg.poolCount--;
c.Reset(fixtureA, fixtureB);
return c;
}
var createFcn = reg.createFcn;
if (createFcn != null) {
if (reg.primary) {
c = createFcn(this.m_allocator);
c.Reset(fixtureA, fixtureB);
return c;
}
else {
c = createFcn(this.m_allocator);
c.Reset(fixtureB, fixtureA);
return c;
}
}
else {
return null;
}
}
b2ContactFactory.prototype.Destroy = function (contact) {
if (contact.m_manifold.m_pointCount > 0) {
contact.m_fixtureA.m_body.SetAwake(true);
contact.m_fixtureB.m_body.SetAwake(true);
}
var type1 = parseInt(contact.m_fixtureA.GetType());
var type2 = parseInt(contact.m_fixtureB.GetType());
var reg = this.m_registers[type1][type2];
if (true) {
reg.poolCount++;
contact.m_next = reg.pool;
reg.pool = contact;
}
var destroyFcn = reg.destroyFcn;
destroyFcn(contact, this.m_allocator);
}
b2ContactRegister.b2ContactRegister = function () {};
b2ContactResult.b2ContactResult = function () {
this.position = new b2Vec2();
this.normal = new b2Vec2();
this.id = new b2ContactID();
};
b2ContactSolver.b2ContactSolver = function () {
this.m_step = new b2TimeStep();
this.m_constraints = new Vector();
};
b2ContactSolver.prototype.b2ContactSolver = function () {}
b2ContactSolver.prototype.Initialize = function (step, contacts, contactCount, allocator) {
if (contactCount === undefined) contactCount = 0;
var contact;
this.m_step.Set(step);
this.m_allocator = allocator;
var i = 0;
var tVec;
var tMat;
this.m_constraintCount = contactCount;
while (this.m_constraints.length < this.m_constraintCount) {
this.m_constraints[this.m_constraints.length] = new b2ContactConstraint();
}
for (i = 0;
i < contactCount; ++i) {
contact = contacts[i];
var fixtureA = contact.m_fixtureA;
var fixtureB = contact.m_fixtureB;
var shapeA = fixtureA.m_shape;
var shapeB = fixtureB.m_shape;
var radiusA = shapeA.m_radius;
var radiusB = shapeB.m_radius;
var bodyA = fixtureA.m_body;
var bodyB = fixtureB.m_body;
var manifold = contact.GetManifold();
var friction = b2Settings.b2MixFriction(fixtureA.GetFriction(), fixtureB.GetFriction());
var restitution = b2Settings.b2MixRestitution(fixtureA.GetRestitution(), fixtureB.GetRestitution());
var vAX = bodyA.m_linearVelocity.x;
var vAY = bodyA.m_linearVelocity.y;
var vBX = bodyB.m_linearVelocity.x;
var vBY = bodyB.m_linearVelocity.y;
var wA = bodyA.m_angularVelocity;
var wB = bodyB.m_angularVelocity;
b2Settings.b2Assert(manifold.m_pointCount > 0);
b2ContactSolver.s_worldManifold.Initialize(manifold, bodyA.m_xf, radiusA, bodyB.m_xf, radiusB);
var normalX = b2ContactSolver.s_worldManifold.m_normal.x;
var normalY = b2ContactSolver.s_worldManifold.m_normal.y;
var cc = this.m_constraints[i];
cc.bodyA = bodyA;
cc.bodyB = bodyB;
cc.manifold = manifold;
cc.normal.x = normalX;
cc.normal.y = normalY;
cc.pointCount = manifold.m_pointCount;
cc.friction = friction;
cc.restitution = restitution;
cc.localPlaneNormal.x = manifold.m_localPlaneNormal.x;
cc.localPlaneNormal.y = manifold.m_localPlaneNormal.y;
cc.localPoint.x = manifold.m_localPoint.x;
cc.localPoint.y = manifold.m_localPoint.y;
cc.radius = radiusA + radiusB;
cc.type = manifold.m_type;
for (var k = 0; k < cc.pointCount; ++k) {
var cp = manifold.m_points[k];
var ccp = cc.points[k];
ccp.normalImpulse = cp.m_normalImpulse;
ccp.tangentImpulse = cp.m_tangentImpulse;
ccp.localPoint.SetV(cp.m_localPoint);
var rAX = ccp.rA.x = b2ContactSolver.s_worldManifold.m_points[k].x - bodyA.m_sweep.c.x;
var rAY = ccp.rA.y = b2ContactSolver.s_worldManifold.m_points[k].y - bodyA.m_sweep.c.y;
var rBX = ccp.rB.x = b2ContactSolver.s_worldManifold.m_points[k].x - bodyB.m_sweep.c.x;
var rBY = ccp.rB.y = b2ContactSolver.s_worldManifold.m_points[k].y - bodyB.m_sweep.c.y;
var rnA = rAX * normalY - rAY * normalX;
var rnB = rBX * normalY - rBY * normalX;
rnA *= rnA;
rnB *= rnB;
var kNormal = bodyA.m_invMass + bodyB.m_invMass + bodyA.m_invI * rnA + bodyB.m_invI * rnB;
ccp.normalMass = 1.0 / kNormal;
var kEqualized = bodyA.m_mass * bodyA.m_invMass + bodyB.m_mass * bodyB.m_invMass;
kEqualized += bodyA.m_mass * bodyA.m_invI * rnA + bodyB.m_mass * bodyB.m_invI * rnB;
ccp.equalizedMass = 1.0 / kEqualized;
var tangentX = normalY;
var tangentY = (-normalX);
var rtA = rAX * tangentY - rAY * tangentX;
var rtB = rBX * tangentY - rBY * tangentX;
rtA *= rtA;
rtB *= rtB;
var kTangent = bodyA.m_invMass + bodyB.m_invMass + bodyA.m_invI * rtA + bodyB.m_invI * rtB;
ccp.tangentMass = 1.0 / kTangent;
ccp.velocityBias = 0.0;
var tX = vBX + ((-wB * rBY)) - vAX - ((-wA * rAY));
var tY = vBY + (wB * rBX) - vAY - (wA * rAX);
var vRel = cc.normal.x * tX + cc.normal.y * tY;
if (vRel < (-b2Settings.b2_velocityThreshold)) {
ccp.velocityBias += (-cc.restitution * vRel);
}
}
if (cc.pointCount == 2) {
var ccp1 = cc.points[0];
var ccp2 = cc.points[1];
var invMassA = bodyA.m_invMass;
var invIA = bodyA.m_invI;
var invMassB = bodyB.m_invMass;
var invIB = bodyB.m_invI;
var rn1A = ccp1.rA.x * normalY - ccp1.rA.y * normalX;
var rn1B = ccp1.rB.x * normalY - ccp1.rB.y * normalX;
var rn2A = ccp2.rA.x * normalY - ccp2.rA.y * normalX;
var rn2B = ccp2.rB.x * normalY - ccp2.rB.y * normalX;
var k11 = invMassA + invMassB + invIA * rn1A * rn1A + invIB * rn1B * rn1B;
var k22 = invMassA + invMassB + invIA * rn2A * rn2A + invIB * rn2B * rn2B;
var k12 = invMassA + invMassB + invIA * rn1A * rn2A + invIB * rn1B * rn2B;
var k_maxConditionNumber = 100.0;
if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) {
cc.K.col1.Set(k11, k12);
cc.K.col2.Set(k12, k22);
cc.K.GetInverse(cc.normalMass);
}
else {
cc.pointCount = 1;
}
}
}
}
b2ContactSolver.prototype.InitVelocityConstraints = function (step) {
var tVec;
var tVec2;
var tMat;
for (var i = 0; i < this.m_constraintCount; ++i) {
var c = this.m_constraints[i];
var bodyA = c.bodyA;
var bodyB = c.bodyB;
var invMassA = bodyA.m_invMass;
var invIA = bodyA.m_invI;
var invMassB = bodyB.m_invMass;
var invIB = bodyB.m_invI;
var normalX = c.normal.x;
var normalY = c.normal.y;
var tangentX = normalY;
var tangentY = (-normalX);
var tX = 0;
var j = 0;
var tCount = 0;
if (step.warmStarting) {
tCount = c.pointCount;
for (j = 0;
j < tCount; ++j) {
var ccp = c.points[j];
ccp.normalImpulse *= step.dtRatio;
ccp.tangentImpulse *= step.dtRatio;
var PX = ccp.normalImpulse * normalX + ccp.tangentImpulse * tangentX;
var PY = ccp.normalImpulse * normalY + ccp.tangentImpulse * tangentY;
bodyA.m_angularVelocity -= invIA * (ccp.rA.x * PY - ccp.rA.y * PX);
bodyA.m_linearVelocity.x -= invMassA * PX;
bodyA.m_linearVelocity.y -= invMassA * PY;
bodyB.m_angularVelocity += invIB * (ccp.rB.x * PY - ccp.rB.y * PX);
bodyB.m_linearVelocity.x += invMassB * PX;
bodyB.m_linearVelocity.y += invMassB * PY;
}
}
else {
tCount = c.pointCount;
for (j = 0;
j < tCount; ++j) {
var ccp2 = c.points[j];
ccp2.normalImpulse = 0.0;
ccp2.tangentImpulse = 0.0;
}
}
}
}
b2ContactSolver.prototype.SolveVelocityConstraints = function () {
var j = 0;
var ccp;
var rAX = 0;
var rAY = 0;
var rBX = 0;
var rBY = 0;
var dvX = 0;
var dvY = 0;
var vn = 0;
var vt = 0;
var lambda = 0;
var maxFriction = 0;
var newImpulse = 0;
var PX = 0;
var PY = 0;
var dX = 0;
var dY = 0;
var P1X = 0;
var P1Y = 0;
var P2X = 0;
var P2Y = 0;
var tMat;
var tVec;
for (var i = 0; i < this.m_constraintCount; ++i) {
var c = this.m_constraints[i];
var bodyA = c.bodyA;
var bodyB = c.bodyB;
var wA = bodyA.m_angularVelocity;
var wB = bodyB.m_angularVelocity;
var vA = bodyA.m_linearVelocity;
var vB = bodyB.m_linearVelocity;
var invMassA = bodyA.m_invMass;
var invIA = bodyA.m_invI;
var invMassB = bodyB.m_invMass;
var invIB = bodyB.m_invI;
var normalX = c.normal.x;
var normalY = c.normal.y;
var tangentX = normalY;
var tangentY = (-normalX);
var friction = c.friction;
var tX = 0;
for (j = 0;
j < c.pointCount; j++) {
ccp = c.points[j];
dvX = vB.x - wB * ccp.rB.y - vA.x + wA * ccp.rA.y;
dvY = vB.y + wB * ccp.rB.x - vA.y - wA * ccp.rA.x;
vt = dvX * tangentX + dvY * tangentY;
lambda = ccp.tangentMass * (-vt);
maxFriction = friction * ccp.normalImpulse;
newImpulse = b2Math.Clamp(ccp.tangentImpulse + lambda, (-maxFriction), maxFriction);
lambda = newImpulse - ccp.tangentImpulse;
PX = lambda * tangentX;
PY = lambda * tangentY;
vA.x -= invMassA * PX;
vA.y -= invMassA * PY;
wA -= invIA * (ccp.rA.x * PY - ccp.rA.y * PX);
vB.x += invMassB * PX;
vB.y += invMassB * PY;
wB += invIB * (ccp.rB.x * PY - ccp.rB.y * PX);
ccp.tangentImpulse = newImpulse;
}
var tCount = parseInt(c.pointCount);
if (c.pointCount == 1) {
ccp = c.points[0];
dvX = vB.x + ((-wB * ccp.rB.y)) - vA.x - ((-wA * ccp.rA.y));
dvY = vB.y + (wB * ccp.rB.x) - vA.y - (wA * ccp.rA.x);
vn = dvX * normalX + dvY * normalY;
lambda = (-ccp.normalMass * (vn - ccp.velocityBias));
newImpulse = ccp.normalImpulse + lambda;
newImpulse = newImpulse > 0 ? newImpulse : 0.0;
lambda = newImpulse - ccp.normalImpulse;
PX = lambda * normalX;
PY = lambda * normalY;
vA.x -= invMassA * PX;
vA.y -= invMassA * PY;
wA -= invIA * (ccp.rA.x * PY - ccp.rA.y * PX);
vB.x += invMassB * PX;
vB.y += invMassB * PY;
wB += invIB * (ccp.rB.x * PY - ccp.rB.y * PX);
ccp.normalImpulse = newImpulse;
}
else {
var cp1 = c.points[0];
var cp2 = c.points[1];
var aX = cp1.normalImpulse;
var aY = cp2.normalImpulse;
var dv1X = vB.x - wB * cp1.rB.y - vA.x + wA * cp1.rA.y;
var dv1Y = vB.y + wB * cp1.rB.x - vA.y - wA * cp1.rA.x;
var dv2X = vB.x - wB * cp2.rB.y - vA.x + wA * cp2.rA.y;
var dv2Y = vB.y + wB * cp2.rB.x - vA.y - wA * cp2.rA.x;
var vn1 = dv1X * normalX + dv1Y * normalY;
var vn2 = dv2X * normalX + dv2Y * normalY;
var bX = vn1 - cp1.velocityBias;
var bY = vn2 - cp2.velocityBias;
tMat = c.K;
bX -= tMat.col1.x * aX + tMat.col2.x * aY;
bY -= tMat.col1.y * aX + tMat.col2.y * aY;
var k_errorTol = 0.001;
for (;;) {
tMat = c.normalMass;
var xX = (-(tMat.col1.x * bX + tMat.col2.x * bY));
var xY = (-(tMat.col1.y * bX + tMat.col2.y * bY));
if (xX >= 0.0 && xY >= 0.0) {
dX = xX - aX;
dY = xY - aY;
P1X = dX * normalX;
P1Y = dX * normalY;
P2X = dY * normalX;
P2Y = dY * normalY;
vA.x -= invMassA * (P1X + P2X);
vA.y -= invMassA * (P1Y + P2Y);
wA -= invIA * (cp1.rA.x * P1Y - cp1.rA.y * P1X + cp2.rA.x * P2Y - cp2.rA.y * P2X);
vB.x += invMassB * (P1X + P2X);
vB.y += invMassB * (P1Y + P2Y);
wB += invIB * (cp1.rB.x * P1Y - cp1.rB.y * P1X + cp2.rB.x * P2Y - cp2.rB.y * P2X);
cp1.normalImpulse = xX;
cp2.normalImpulse = xY;
break;
}
xX = (-cp1.normalMass * bX);
xY = 0.0;
vn1 = 0.0;
vn2 = c.K.col1.y * xX + bY;
if (xX >= 0.0 && vn2 >= 0.0) {
dX = xX - aX;
dY = xY - aY;
P1X = dX * normalX;
P1Y = dX * normalY;
P2X = dY * normalX;
P2Y = dY * normalY;
vA.x -= invMassA * (P1X + P2X);
vA.y -= invMassA * (P1Y + P2Y);
wA -= invIA * (cp1.rA.x * P1Y - cp1.rA.y * P1X + cp2.rA.x * P2Y - cp2.rA.y * P2X);
vB.x += invMassB * (P1X + P2X);
vB.y += invMassB * (P1Y + P2Y);
wB += invIB * (cp1.rB.x * P1Y - cp1.rB.y * P1X + cp2.rB.x * P2Y - cp2.rB.y * P2X);
cp1.normalImpulse = xX;
cp2.normalImpulse = xY;
break;
}
xX = 0.0;
xY = (-cp2.normalMass * bY);
vn1 = c.K.col2.x * xY + bX;
vn2 = 0.0;
if (xY >= 0.0 && vn1 >= 0.0) {
dX = xX - aX;
dY = xY - aY;
P1X = dX * normalX;
P1Y = dX * normalY;
P2X = dY * normalX;
P2Y = dY * normalY;
vA.x -= invMassA * (P1X + P2X);
vA.y -= invMassA * (P1Y + P2Y);
wA -= invIA * (cp1.rA.x * P1Y - cp1.rA.y * P1X + cp2.rA.x * P2Y - cp2.rA.y * P2X);
vB.x += invMassB * (P1X + P2X);
vB.y += invMassB * (P1Y + P2Y);
wB += invIB * (cp1.rB.x * P1Y - cp1.rB.y * P1X + cp2.rB.x * P2Y - cp2.rB.y * P2X);
cp1.normalImpulse = xX;
cp2.normalImpulse = xY;
break;
}
xX = 0.0;
xY = 0.0;
vn1 = bX;
vn2 = bY;
if (vn1 >= 0.0 && vn2 >= 0.0) {
dX = xX - aX;
dY = xY - aY;
P1X = dX * normalX;
P1Y = dX * normalY;
P2X = dY * normalX;
P2Y = dY * normalY;
vA.x -= invMassA * (P1X + P2X);
vA.y -= invMassA * (P1Y + P2Y);
wA -= invIA * (cp1.rA.x * P1Y - cp1.rA.y * P1X + cp2.rA.x * P2Y - cp2.rA.y * P2X);
vB.x += invMassB * (P1X + P2X);
vB.y += invMassB * (P1Y + P2Y);
wB += invIB * (cp1.rB.x * P1Y - cp1.rB.y * P1X + cp2.rB.x * P2Y - cp2.rB.y * P2X);
cp1.normalImpulse = xX;
cp2.normalImpulse = xY;
break;
}
break;
}
}
bodyA.m_angularVelocity = wA;
bodyB.m_angularVelocity = wB;
}
}
b2ContactSolver.prototype.FinalizeVelocityConstraints = function () {
for (var i = 0; i < this.m_constraintCount; ++i) {
var c = this.m_constraints[i];
var m = c.manifold;
for (var j = 0; j < c.pointCount; ++j) {
var point1 = m.m_points[j];
var point2 = c.points[j];
point1.m_normalImpulse = point2.normalImpulse;
point1.m_tangentImpulse = point2.tangentImpulse;
}
}
}
b2ContactSolver.prototype.SolvePositionConstraints = function (baumgarte) {
if (baumgarte === undefined) baumgarte = 0;
var minSeparation = 0.0;
for (var i = 0; i < this.m_constraintCount; i++) {
var c = this.m_constraints[i];
var bodyA = c.bodyA;
var bodyB = c.bodyB;
var invMassA = bodyA.m_mass * bodyA.m_invMass;
var invIA = bodyA.m_mass * bodyA.m_invI;
var invMassB = bodyB.m_mass * bodyB.m_invMass;
var invIB = bodyB.m_mass * bodyB.m_invI;
b2ContactSolver.s_psm.Initialize(c);
var normal = b2ContactSolver.s_psm.m_normal;
for (var j = 0; j < c.pointCount; j++) {
var ccp = c.points[j];
var point = b2ContactSolver.s_psm.m_points[j];
var separation = b2ContactSolver.s_psm.m_separations[j];
var rAX = point.x - bodyA.m_sweep.c.x;
var rAY = point.y - bodyA.m_sweep.c.y;
var rBX = point.x - bodyB.m_sweep.c.x;
var rBY = point.y - bodyB.m_sweep.c.y;
minSeparation = minSeparation < separation ? minSeparation : separation;
var C = b2Math.Clamp(baumgarte * (separation + b2Settings.b2_linearSlop), (-b2Settings.b2_maxLinearCorrection), 0.0);
var impulse = (-ccp.equalizedMass * C);
var PX = impulse * normal.x;
var PY = impulse * normal.y;bodyA.m_sweep.c.x -= invMassA * PX;
bodyA.m_sweep.c.y -= invMassA * PY;
bodyA.m_sweep.a -= invIA * (rAX * PY - rAY * PX);
bodyA.SynchronizeTransform();
bodyB.m_sweep.c.x += invMassB * PX;
bodyB.m_sweep.c.y += invMassB * PY;
bodyB.m_sweep.a += invIB * (rBX * PY - rBY * PX);
bodyB.SynchronizeTransform();
}
}
return minSeparation > (-1.5 * b2Settings.b2_linearSlop);
}
_A2J_postDefs.push(function () {
Box2D.Dynamics.Contacts.b2ContactSolver.s_worldManifold = new b2WorldManifold();
Box2D.Dynamics.Contacts.b2ContactSolver.prototype.s_worldManifold = Box2D.Dynamics.Contacts.b2ContactSolver.s_worldManifold;
Box2D.Dynamics.Contacts.b2ContactSolver.s_psm = new b2PositionSolverManifold();
Box2D.Dynamics.Contacts.b2ContactSolver.prototype.s_psm = Box2D.Dynamics.Contacts.b2ContactSolver.s_psm;
});
b2EdgeAndCircleContact.inherit(Box2D.Dynamics.Contacts.b2Contact);
b2EdgeAndCircleContact.prototype.__super = Box2D.Dynamics.Contacts.b2Contact.prototype;
b2EdgeAndCircleContact.b2EdgeAndCircleContact = function () {
Box2D.Dynamics.Contacts.b2Contact.b2Contact.apply(this, arguments);
};
b2EdgeAndCircleContact.prototype.Create = function (allocator) {
return new b2EdgeAndCircleContact();
}
b2EdgeAndCircleContact.Create = b2EdgeAndCircleContact.prototype.Create;
b2EdgeAndCircleContact.prototype.Destroy = function (contact, allocator) {}
b2EdgeAndCircleContact.Destroy = b2EdgeAndCircleContact.prototype.Destroy;
b2EdgeAndCircleContact.prototype.Reset = function (fixtureA, fixtureB) {
this.__super.Reset.call(this, fixtureA, fixtureB);
}
b2EdgeAndCircleContact.prototype.Evaluate = function () {
var bA = this.m_fixtureA.GetBody();
var bB = this.m_fixtureB.GetBody();
this.b2CollideEdgeAndCircle(this.m_manifold, (this.m_fixtureA.GetShape() instanceof b2EdgeShape ? this.m_fixtureA.GetShape() : null), bA.m_xf, (this.m_fixtureB.GetShape() instanceof b2CircleShape ? this.m_fixtureB.GetShape() : null), bB.m_xf);
}
b2EdgeAndCircleContact.prototype.b2CollideEdgeAndCircle = function (manifold, edge, xf1, circle, xf2) {}
b2NullContact.inherit(Box2D.Dynamics.Contacts.b2Contact);
b2NullContact.prototype.__super = Box2D.Dynamics.Contacts.b2Contact.prototype;
b2NullContact.b2NullContact = function () {
Box2D.Dynamics.Contacts.b2Contact.b2Contact.apply(this, arguments);
};
b2NullContact.prototype.b2NullContact = function () {
this.__super.b2Contact.call(this);
}
b2NullContact.prototype.Evaluate = function () {}
b2PolyAndCircleContact.inherit(Box2D.Dynamics.Contacts.b2Contact);
b2PolyAndCircleContact.prototype.__super = Box2D.Dynamics.Contacts.b2Contact.prototype;
b2PolyAndCircleContact.b2PolyAndCircleContact = function () {
Box2D.Dynamics.Contacts.b2Contact.b2Contact.apply(this, arguments);
};
b2PolyAndCircleContact.prototype.Create = function (allocator) {
return new b2PolyAndCircleContact();
}
b2PolyAndCircleContact.Create = b2PolyAndCircleContact.prototype.Create;
b2PolyAndCircleContact.prototype.Destroy = function (contact, allocator) {}
b2PolyAndCircleContact.Destroy = b2PolyAndCircleContact.prototype.Destroy;
b2PolyAndCircleContact.prototype.Reset = function (fixtureA, fixtureB) {
this.__super.Reset.call(this, fixtureA, fixtureB);
b2Settings.b2Assert(fixtureA.GetType() == b2Shape.e_polygonShape);
b2Settings.b2Assert(fixtureB.GetType() == b2Shape.e_circleShape);
}
b2PolyAndCircleContact.prototype.Evaluate = function () {
var bA = this.m_fixtureA.m_body;
var bB = this.m_fixtureB.m_body;
b2Collision.CollidePolygonAndCircle(this.m_manifold, (this.m_fixtureA.GetShape() instanceof b2PolygonShape ? this.m_fixtureA.GetShape() : null), bA.m_xf, (this.m_fixtureB.GetShape() instanceof b2CircleShape ? this.m_fixtureB.GetShape() : null), bB.m_xf);
}
b2PolyAndEdgeContact.inherit(Box2D.Dynamics.Contacts.b2Contact);
b2PolyAndEdgeContact.prototype.__super = Box2D.Dynamics.Contacts.b2Contact.prototype;
b2PolyAndEdgeContact.b2PolyAndEdgeContact = function () {
Box2D.Dynamics.Contacts.b2Contact.b2Contact.apply(this, arguments);
};
b2PolyAndEdgeContact.prototype.Create = function (allocator) {
return new b2PolyAndEdgeContact();
}
b2PolyAndEdgeContact.Create = b2PolyAndEdgeContact.prototype.Create;
b2PolyAndEdgeContact.prototype.Destroy = function (contact, allocator) {}
b2PolyAndEdgeContact.Destroy = b2PolyAndEdgeContact.prototype.Destroy;
b2PolyAndEdgeContact.prototype.Reset = function (fixtureA, fixtureB) {
this.__super.Reset.call(this, fixtureA, fixtureB);
b2Settings.b2Assert(fixtureA.GetType() == b2Shape.e_polygonShape);
b2Settings.b2Assert(fixtureB.GetType() == b2Shape.e_edgeShape);
}
b2PolyAndEdgeContact.prototype.Evaluate = function () {
var bA = this.m_fixtureA.GetBody();
var bB = this.m_fixtureB.GetBody();
this.b2CollidePolyAndEdge(this.m_manifold, (this.m_fixtureA.GetShape() instanceof b2PolygonShape ? this.m_fixtureA.GetShape() : null), bA.m_xf, (this.m_fixtureB.GetShape() instanceof b2EdgeShape ? this.m_fixtureB.GetShape() : null), bB.m_xf);
}
b2PolyAndEdgeContact.prototype.b2CollidePolyAndEdge = function (manifold, polygon, xf1, edge, xf2) {}
b2PolygonContact.inherit(Box2D.Dynamics.Contacts.b2Contact);
b2PolygonContact.prototype.__super = Box2D.Dynamics.Contacts.b2Contact.prototype;
b2PolygonContact.b2PolygonContact = function () {
Box2D.Dynamics.Contacts.b2Contact.b2Contact.apply(this, arguments);
};
b2PolygonContact.prototype.Create = function (allocator) {
return new b2PolygonContact();
}
b2PolygonContact.Create = b2PolygonContact.prototype.Create;
b2PolygonContact.prototype.Destroy = function (contact, allocator) {}
b2PolygonContact.Destroy = b2PolygonContact.prototype.Destroy;
b2PolygonContact.prototype.Reset = function (fixtureA, fixtureB) {
this.__super.Reset.call(this, fixtureA, fixtureB);
}
b2PolygonContact.prototype.Evaluate = function () {
var bA = this.m_fixtureA.GetBody();
var bB = this.m_fixtureB.GetBody();
b2Collision.CollidePolygons(this.m_manifold, (this.m_fixtureA.GetShape() instanceof b2PolygonShape ? this.m_fixtureA.GetShape() : null), bA.m_xf, (this.m_fixtureB.GetShape() instanceof b2PolygonShape ? this.m_fixtureB.GetShape() : null), bB.m_xf);
}
b2PositionSolverManifold.b2PositionSolverManifold = function () {};
b2PositionSolverManifold.prototype.b2PositionSolverManifold = function () {
this.m_normal = new b2Vec2();
this.m_separations = new Vector_a2j_Number(b2Settings.b2_maxManifoldPoints);
this.m_points = new Vector(b2Settings.b2_maxManifoldPoints);
for (var i = 0; i < b2Settings.b2_maxManifoldPoints; i++) {
this.m_points[i] = new b2Vec2();
}
}
b2PositionSolverManifold.prototype.Initialize = function (cc) {
b2Settings.b2Assert(cc.pointCount > 0);
var i = 0;
var clipPointX = 0;
var clipPointY = 0;
var tMat;
var tVec;
var planePointX = 0;
var planePointY = 0;
switch (cc.type) {
case b2Manifold.e_circles:
{
tMat = cc.bodyA.m_xf.R;
tVec = cc.localPoint;
var pointAX = cc.bodyA.m_xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
var pointAY = cc.bodyA.m_xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
tMat = cc.bodyB.m_xf.R;
tVec = cc.points[0].localPoint;
var pointBX = cc.bodyB.m_xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
var pointBY = cc.bodyB.m_xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
var dX = pointBX - pointAX;
var dY = pointBY - pointAY;
var d2 = dX * dX + dY * dY;
if (d2 > Number.MIN_VALUE * Number.MIN_VALUE) {
var d = Math.sqrt(d2);
this.m_normal.x = dX / d;
this.m_normal.y = dY / d;
}
else {
this.m_normal.x = 1.0;
this.m_normal.y = 0.0;
}
this.m_points[0].x = 0.5 * (pointAX + pointBX);
this.m_points[0].y = 0.5 * (pointAY + pointBY);
this.m_separations[0] = dX * this.m_normal.x + dY * this.m_normal.y - cc.radius;
}
break;
case b2Manifold.e_faceA:
{
tMat = cc.bodyA.m_xf.R;
tVec = cc.localPlaneNormal;
this.m_normal.x = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
this.m_normal.y = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
tMat = cc.bodyA.m_xf.R;
tVec = cc.localPoint;
planePointX = cc.bodyA.m_xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
planePointY = cc.bodyA.m_xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
tMat = cc.bodyB.m_xf.R;
for (i = 0;
i < cc.pointCount; ++i) {
tVec = cc.points[i].localPoint;
clipPointX = cc.bodyB.m_xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
clipPointY = cc.bodyB.m_xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
this.m_separations[i] = (clipPointX - planePointX) * this.m_normal.x + (clipPointY - planePointY) * this.m_normal.y - cc.radius;
this.m_points[i].x = clipPointX;
this.m_points[i].y = clipPointY;
}
}
break;
case b2Manifold.e_faceB:
{
tMat = cc.bodyB.m_xf.R;
tVec = cc.localPlaneNormal;
this.m_normal.x = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
this.m_normal.y = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
tMat = cc.bodyB.m_xf.R;
tVec = cc.localPoint;
planePointX = cc.bodyB.m_xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
planePointY = cc.bodyB.m_xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
tMat = cc.bodyA.m_xf.R;
for (i = 0;
i < cc.pointCount; ++i) {
tVec = cc.points[i].localPoint;
clipPointX = cc.bodyA.m_xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
clipPointY = cc.bodyA.m_xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
this.m_separations[i] = (clipPointX - planePointX) * this.m_normal.x + (clipPointY - planePointY) * this.m_normal.y - cc.radius;
this.m_points[i].Set(clipPointX, clipPointY);
}
this.m_normal.x *= (-1);
this.m_normal.y *= (-1);
}
break;
}
}
_A2J_postDefs.push(function () {
Box2D.Dynamics.Contacts.b2PositionSolverManifold.circlePointA = new b2Vec2();
Box2D.Dynamics.Contacts.b2PositionSolverManifold.prototype.circlePointA = Box2D.Dynamics.Contacts.b2PositionSolverManifold.circlePointA;
Box2D.Dynamics.Contacts.b2PositionSolverManifold.circlePointB = new b2Vec2();
Box2D.Dynamics.Contacts.b2PositionSolverManifold.prototype.circlePointB = Box2D.Dynamics.Contacts.b2PositionSolverManifold.circlePointB;
});
})(); /* source: disabled*/
(function () {
var b2Body = Box2D.Dynamics.b2Body;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2ContactFilter = Box2D.Dynamics.b2ContactFilter;
var b2ContactImpulse = Box2D.Dynamics.b2ContactImpulse;
var b2ContactListener = Box2D.Dynamics.b2ContactListener;
var b2ContactManager = Box2D.Dynamics.b2ContactManager;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var b2DestructionListener = Box2D.Dynamics.b2DestructionListener;
var b2FilterData = Box2D.Dynamics.b2FilterData;
var b2Fixture = Box2D.Dynamics.b2Fixture;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2Island = Box2D.Dynamics.b2Island;
var b2TimeStep = Box2D.Dynamics.b2TimeStep;
var b2World = Box2D.Dynamics.b2World;
var b2Mat22 = Box2D.Common.Math.b2Mat22;
var b2Mat33 = Box2D.Common.Math.b2Mat33;
var b2Math = Box2D.Common.Math.b2Math;
var b2Sweep = Box2D.Common.Math.b2Sweep;
var b2Transform = Box2D.Common.Math.b2Transform;
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2Vec3 = Box2D.Common.Math.b2Vec3;
var b2Color = Box2D.Common.b2Color;
var b2internal = Box2D.Common.b2internal;
var b2Settings = Box2D.Common.b2Settings;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2EdgeChainDef = Box2D.Collision.Shapes.b2EdgeChainDef;
var b2EdgeShape = Box2D.Collision.Shapes.b2EdgeShape;
var b2MassData = Box2D.Collision.Shapes.b2MassData;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2Shape = Box2D.Collision.Shapes.b2Shape;
var b2Body = Box2D.Dynamics.b2Body;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2ContactFilter = Box2D.Dynamics.b2ContactFilter;
var b2ContactImpulse = Box2D.Dynamics.b2ContactImpulse;
var b2ContactListener = Box2D.Dynamics.b2ContactListener;
var b2ContactManager = Box2D.Dynamics.b2ContactManager;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var b2DestructionListener = Box2D.Dynamics.b2DestructionListener;
var b2FilterData = Box2D.Dynamics.b2FilterData;
var b2Fixture = Box2D.Dynamics.b2Fixture;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2Island = Box2D.Dynamics.b2Island;
var b2TimeStep = Box2D.Dynamics.b2TimeStep;
var b2World = Box2D.Dynamics.b2World;
var b2BuoyancyController = Box2D.Dynamics.Controllers.b2BuoyancyController;
var b2ConstantAccelController = Box2D.Dynamics.Controllers.b2ConstantAccelController;
var b2ConstantForceController = Box2D.Dynamics.Controllers.b2ConstantForceController;
var b2Controller = Box2D.Dynamics.Controllers.b2Controller;
var b2ControllerEdge = Box2D.Dynamics.Controllers.b2ControllerEdge;
var b2GravityController = Box2D.Dynamics.Controllers.b2GravityController;
var b2TensorDampingController = Box2D.Dynamics.Controllers.b2TensorDampingController;
b2BuoyancyController.inherit(Box2D.Dynamics.Controllers.b2Controller);
b2BuoyancyController.prototype.__super = Box2D.Dynamics.Controllers.b2Controller.prototype;
b2BuoyancyController.b2BuoyancyController = function () {
Box2D.Dynamics.Controllers.b2Controller.b2Controller.apply(this, arguments);
this.normal = new b2Vec2(0, (-1));
this.offset = 0;
this.density = 0;
this.velocity = new b2Vec2(0, 0);
this.linearDrag = 2;
this.angularDrag = 1;
this.useDensity = false;
this.useWorldGravity = true;
this.gravity = null;
};
b2BuoyancyController.prototype.Step = function (step) {
if (!this.m_bodyList) return;
if (this.useWorldGravity) {
this.gravity = this.GetWorld().GetGravity().Copy();
}
for (var i = this.m_bodyList; i; i = i.nextBody) {
var body = i.body;
if (body.IsAwake() == false) {
continue;
}
var areac = new b2Vec2();
var massc = new b2Vec2();
var area = 0.0;
var mass = 0.0;
for (var fixture = body.GetFixtureList(); fixture; fixture = fixture.GetNext()) {
var sc = new b2Vec2();
var sarea = fixture.GetShape().ComputeSubmergedArea(this.normal, this.offset, body.GetTransform(), sc);
area += sarea;
areac.x += sarea * sc.x;
areac.y += sarea * sc.y;
var shapeDensity = 0;
if (this.useDensity) {
shapeDensity = 1;
}
else {
shapeDensity = 1;
}
mass += sarea * shapeDensity;
massc.x += sarea * sc.x * shapeDensity;
massc.y += sarea * sc.y * shapeDensity;
}
areac.x /= area;
areac.y /= area;
massc.x /= mass;
massc.y /= mass;
if (area < Number.MIN_VALUE) continue;
var buoyancyForce = this.gravity.GetNegative();
buoyancyForce.Multiply(this.density * area);
body.ApplyForce(buoyancyForce, massc);
var dragForce = body.GetLinearVelocityFromWorldPoint(areac);
dragForce.Subtract(this.velocity);
dragForce.Multiply((-this.linearDrag * area));
body.ApplyForce(dragForce, areac);
body.ApplyTorque((-body.GetInertia() / body.GetMass() * area * body.GetAngularVelocity() * this.angularDrag));
}
}
b2BuoyancyController.prototype.Draw = function (debugDraw) {
var r = 1000;
var p1 = new b2Vec2();
var p2 = new b2Vec2();
p1.x = this.normal.x * this.offset + this.normal.y * r;
p1.y = this.normal.y * this.offset - this.normal.x * r;
p2.x = this.normal.x * this.offset - this.normal.y * r;
p2.y = this.normal.y * this.offset + this.normal.x * r;
var color = new b2Color(0, 0, 1);
debugDraw.DrawSegment(p1, p2, color);
}
b2ConstantAccelController.inherit(Box2D.Dynamics.Controllers.b2Controller);
b2ConstantAccelController.prototype.__super = Box2D.Dynamics.Controllers.b2Controller.prototype;
b2ConstantAccelController.b2ConstantAccelController = function () {
Box2D.Dynamics.Controllers.b2Controller.b2Controller.apply(this, arguments);
this.A = new b2Vec2(0, 0);
};
b2ConstantAccelController.prototype.Step = function (step) {
var smallA = new b2Vec2(this.A.x * step.dt, this.A.y * step.dt);
for (var i = this.m_bodyList; i; i = i.nextBody) {
var body = i.body;
if (!body.IsAwake()) continue;
body.SetLinearVelocity(new b2Vec2(body.GetLinearVelocity().x + smallA.x, body.GetLinearVelocity().y + smallA.y));
}
}
b2ConstantForceController.inherit(Box2D.Dynamics.Controllers.b2Controller);
b2ConstantForceController.prototype.__super = Box2D.Dynamics.Controllers.b2Controller.prototype;
b2ConstantForceController.b2ConstantForceController = function () {
Box2D.Dynamics.Controllers.b2Controller.b2Controller.apply(this, arguments);
this.F = new b2Vec2(0, 0);
};
b2ConstantForceController.prototype.Step = function (step) {
for (var i = this.m_bodyList; i; i = i.nextBody) {
var body = i.body;
if (!body.IsAwake()) continue;
body.ApplyForce(this.F, body.GetWorldCenter());
}
}
b2Controller.b2Controller = function () {};
b2Controller.prototype.Step = function (step) {}
b2Controller.prototype.Draw = function (debugDraw) {}
b2Controller.prototype.AddBody = function (body) {
var edge = new b2ControllerEdge();
edge.controller = this;
edge.body = body;
edge.nextBody = this.m_bodyList;
edge.prevBody = null;
this.m_bodyList = edge;
if (edge.nextBody) edge.nextBody.prevBody = edge;
this.m_bodyCount++;
edge.nextController = body.m_controllerList;
edge.prevController = null;
body.m_controllerList = edge;
if (edge.nextController) edge.nextController.prevController = edge;
body.m_controllerCount++;
}
b2Controller.prototype.RemoveBody = function (body) {
var edge = body.m_controllerList;
while (edge && edge.controller != this)
edge = edge.nextController;
if (edge.prevBody) edge.prevBody.nextBody = edge.nextBody;
if (edge.nextBody) edge.nextBody.prevBody = edge.prevBody;
if (edge.nextController) edge.nextController.prevController = edge.prevController;
if (edge.prevController) edge.prevController.nextController = edge.nextController;
if (this.m_bodyList == edge) this.m_bodyList = edge.nextBody;
if (body.m_controllerList == edge) body.m_controllerList = edge.nextController;
body.m_controllerCount--;
this.m_bodyCount--;
}
b2Controller.prototype.Clear = function () {
while (this.m_bodyList)
this.RemoveBody(this.m_bodyList.body);
}
b2Controller.prototype.GetNext = function () {
return this.m_next;
}
b2Controller.prototype.GetWorld = function () {
return this.m_world;
}
b2Controller.prototype.GetBodyList = function () {
return this.m_bodyList;
}
b2ControllerEdge.b2ControllerEdge = function () {};
b2GravityController.inherit(Box2D.Dynamics.Controllers.b2Controller);
b2GravityController.prototype.__super = Box2D.Dynamics.Controllers.b2Controller.prototype;
b2GravityController.b2GravityController = function () {
Box2D.Dynamics.Controllers.b2Controller.b2Controller.apply(this, arguments);
this.G = 1;
this.invSqr = true;
};
b2GravityController.prototype.Step = function (step) {
var i = null;
var body1 = null;
var p1 = null;
var mass1 = 0;
var j = null;
var body2 = null;
var p2 = null;
var dx = 0;
var dy = 0;
var r2 = 0;
var f = null;
if (this.invSqr) {
for (i = this.m_bodyList;
i; i = i.nextBody) {
body1 = i.body;
p1 = body1.GetWorldCenter();
mass1 = body1.GetMass();
for (j = this.m_bodyList;
j != i; j = j.nextBody) {
body2 = j.body;
p2 = body2.GetWorldCenter();
dx = p2.x - p1.x;
dy = p2.y - p1.y;
r2 = dx * dx + dy * dy;
if (r2 < Number.MIN_VALUE) continue;
f = new b2Vec2(dx, dy);
f.Multiply(this.G / r2 / Math.sqrt(r2) * mass1 * body2.GetMass());
if (body1.IsAwake()) body1.ApplyForce(f, p1);
f.Multiply((-1));
if (body2.IsAwake()) body2.ApplyForce(f, p2);
}
}
}
else {
for (i = this.m_bodyList;
i; i = i.nextBody) {
body1 = i.body;
p1 = body1.GetWorldCenter();
mass1 = body1.GetMass();
for (j = this.m_bodyList;
j != i; j = j.nextBody) {
body2 = j.body;
p2 = body2.GetWorldCenter();
dx = p2.x - p1.x;
dy = p2.y - p1.y;
r2 = dx * dx + dy * dy;
if (r2 < Number.MIN_VALUE) continue;
f = new b2Vec2(dx, dy);
f.Multiply(this.G / r2 * mass1 * body2.GetMass());
if (body1.IsAwake()) body1.ApplyForce(f, p1);
f.Multiply((-1));
if (body2.IsAwake()) body2.ApplyForce(f, p2);
}
}
}
}
b2TensorDampingController.inherit(Box2D.Dynamics.Controllers.b2Controller);
b2TensorDampingController.prototype.__super = Box2D.Dynamics.Controllers.b2Controller.prototype;
b2TensorDampingController.b2TensorDampingController = function () {
Box2D.Dynamics.Controllers.b2Controller.b2Controller.apply(this, arguments);
this.T = new b2Mat22();
this.maxTimestep = 0;
};
b2TensorDampingController.prototype.SetAxisAligned = function (xDamping, yDamping) {
if (xDamping === undefined) xDamping = 0;
if (yDamping === undefined) yDamping = 0;
this.T.col1.x = (-xDamping);
this.T.col1.y = 0;
this.T.col2.x = 0;
this.T.col2.y = (-yDamping);
if (xDamping > 0 || yDamping > 0) {
this.maxTimestep = 1 / Math.max(xDamping, yDamping);
}
else {
this.maxTimestep = 0;
}
}
b2TensorDampingController.prototype.Step = function (step) {
var timestep = step.dt;
if (timestep <= Number.MIN_VALUE) return;
if (timestep > this.maxTimestep && this.maxTimestep > 0) timestep = this.maxTimestep;
for (var i = this.m_bodyList; i; i = i.nextBody) {
var body = i.body;
if (!body.IsAwake()) {
continue;
}
var damping = body.GetWorldVector(b2Math.MulMV(this.T, body.GetLocalVector(body.GetLinearVelocity())));
body.SetLinearVelocity(new b2Vec2(body.GetLinearVelocity().x + damping.x * timestep, body.GetLinearVelocity().y + damping.y * timestep));
}
}
})(); /* source: disabled*/
(function () {
var b2Color = Box2D.Common.b2Color;
var b2internal = Box2D.Common.b2internal;
var b2Settings = Box2D.Common.b2Settings;
var b2Color = Box2D.Common.b2Color;
var b2internal = Box2D.Common.b2internal;
var b2Settings = Box2D.Common.b2Settings;
var b2internal = Box2D.Common.b2internal;
var b2Mat22 = Box2D.Common.Math.b2Mat22;
var b2Mat33 = Box2D.Common.Math.b2Mat33;
var b2Math = Box2D.Common.Math.b2Math;
var b2Sweep = Box2D.Common.Math.b2Sweep;
var b2Transform = Box2D.Common.Math.b2Transform;
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2Vec3 = Box2D.Common.Math.b2Vec3;
var b2DistanceJoint = Box2D.Dynamics.Joints.b2DistanceJoint;
var b2DistanceJointDef = Box2D.Dynamics.Joints.b2DistanceJointDef;
var b2FrictionJoint = Box2D.Dynamics.Joints.b2FrictionJoint;
var b2FrictionJointDef = Box2D.Dynamics.Joints.b2FrictionJointDef;
var b2GearJoint = Box2D.Dynamics.Joints.b2GearJoint;
var b2GearJointDef = Box2D.Dynamics.Joints.b2GearJointDef;
var b2Jacobian = Box2D.Dynamics.Joints.b2Jacobian;
var b2Joint = Box2D.Dynamics.Joints.b2Joint;
var b2JointDef = Box2D.Dynamics.Joints.b2JointDef;
var b2JointEdge = Box2D.Dynamics.Joints.b2JointEdge;
var b2LineJoint = Box2D.Dynamics.Joints.b2LineJoint;
var b2LineJointDef = Box2D.Dynamics.Joints.b2LineJointDef;
var b2MouseJoint = Box2D.Dynamics.Joints.b2MouseJoint;
var b2MouseJointDef = Box2D.Dynamics.Joints.b2MouseJointDef;
var b2PrismaticJoint = Box2D.Dynamics.Joints.b2PrismaticJoint;
var b2PrismaticJointDef = Box2D.Dynamics.Joints.b2PrismaticJointDef;
var b2PulleyJoint = Box2D.Dynamics.Joints.b2PulleyJoint;
var b2PulleyJointDef = Box2D.Dynamics.Joints.b2PulleyJointDef;
var b2RevoluteJoint = Box2D.Dynamics.Joints.b2RevoluteJoint;
var b2RevoluteJointDef = Box2D.Dynamics.Joints.b2RevoluteJointDef;
var b2WeldJoint = Box2D.Dynamics.Joints.b2WeldJoint;
var b2WeldJointDef = Box2D.Dynamics.Joints.b2WeldJointDef;
var b2Body = Box2D.Dynamics.b2Body;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2ContactFilter = Box2D.Dynamics.b2ContactFilter;
var b2ContactImpulse = Box2D.Dynamics.b2ContactImpulse;
var b2ContactListener = Box2D.Dynamics.b2ContactListener;
var b2ContactManager = Box2D.Dynamics.b2ContactManager;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var b2DestructionListener = Box2D.Dynamics.b2DestructionListener;
var b2FilterData = Box2D.Dynamics.b2FilterData;
var b2Fixture = Box2D.Dynamics.b2Fixture;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2Island = Box2D.Dynamics.b2Island;
var b2TimeStep = Box2D.Dynamics.b2TimeStep;
var b2World = Box2D.Dynamics.b2World;
var b2internal = Box2D.Common.b2internal;
var b2DistanceJoint = Box2D.Dynamics.Joints.b2DistanceJoint;
var b2DistanceJointDef = Box2D.Dynamics.Joints.b2DistanceJointDef;
var b2FrictionJoint = Box2D.Dynamics.Joints.b2FrictionJoint;
var b2FrictionJointDef = Box2D.Dynamics.Joints.b2FrictionJointDef;
var b2GearJoint = Box2D.Dynamics.Joints.b2GearJoint;
var b2GearJointDef = Box2D.Dynamics.Joints.b2GearJointDef;
var b2Jacobian = Box2D.Dynamics.Joints.b2Jacobian;
var b2Joint = Box2D.Dynamics.Joints.b2Joint;
var b2JointDef = Box2D.Dynamics.Joints.b2JointDef;
var b2JointEdge = Box2D.Dynamics.Joints.b2JointEdge;
var b2LineJoint = Box2D.Dynamics.Joints.b2LineJoint;
var b2LineJointDef = Box2D.Dynamics.Joints.b2LineJointDef;
var b2MouseJoint = Box2D.Dynamics.Joints.b2MouseJoint;
var b2MouseJointDef = Box2D.Dynamics.Joints.b2MouseJointDef;
var b2PrismaticJoint = Box2D.Dynamics.Joints.b2PrismaticJoint;
var b2PrismaticJointDef = Box2D.Dynamics.Joints.b2PrismaticJointDef;
var b2PulleyJoint = Box2D.Dynamics.Joints.b2PulleyJoint;
var b2PulleyJointDef = Box2D.Dynamics.Joints.b2PulleyJointDef;
var b2RevoluteJoint = Box2D.Dynamics.Joints.b2RevoluteJoint;
var b2RevoluteJointDef = Box2D.Dynamics.Joints.b2RevoluteJointDef;
var b2WeldJoint = Box2D.Dynamics.Joints.b2WeldJoint;
var b2WeldJointDef = Box2D.Dynamics.Joints.b2WeldJointDef;
b2DistanceJoint.inherit(Box2D.Dynamics.Joints.b2Joint);
b2DistanceJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
b2DistanceJoint.b2DistanceJoint = function () {
Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
this.m_localAnchor1 = new b2Vec2();
this.m_localAnchor2 = new b2Vec2();
this.m_u = new b2Vec2();
};
b2DistanceJoint.prototype.GetAnchorA = function () {
return this.m_bodyA.GetWorldPoint(this.m_localAnchor1);
}
b2DistanceJoint.prototype.GetAnchorB = function () {
return this.m_bodyB.GetWorldPoint(this.m_localAnchor2);
}
b2DistanceJoint.prototype.GetReactionForce = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return new b2Vec2(inv_dt * this.m_impulse * this.m_u.x, inv_dt * this.m_impulse * this.m_u.y);
}
b2DistanceJoint.prototype.GetReactionTorque = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return 0.0;
}
b2DistanceJoint.prototype.GetLength = function () {
return this.m_length;
}
b2DistanceJoint.prototype.SetLength = function (length) {
if (length === undefined) length = 0;
this.m_length = length;
}
b2DistanceJoint.prototype.GetFrequency = function () {
return this.m_frequencyHz;
}
b2DistanceJoint.prototype.SetFrequency = function (hz) {
if (hz === undefined) hz = 0;
this.m_frequencyHz = hz;
}
b2DistanceJoint.prototype.GetDampingRatio = function () {
return this.m_dampingRatio;
}
b2DistanceJoint.prototype.SetDampingRatio = function (ratio) {
if (ratio === undefined) ratio = 0;
this.m_dampingRatio = ratio;
}
b2DistanceJoint.prototype.b2DistanceJoint = function (def) {
this.__super.b2Joint.call(this, def);
var tMat;
var tX = 0;
var tY = 0;
this.m_localAnchor1.SetV(def.localAnchorA);
this.m_localAnchor2.SetV(def.localAnchorB);
this.m_length = def.length;
this.m_frequencyHz = def.frequencyHz;
this.m_dampingRatio = def.dampingRatio;
this.m_impulse = 0.0;
this.m_gamma = 0.0;
this.m_bias = 0.0;
}
b2DistanceJoint.prototype.InitVelocityConstraints = function (step) {
var tMat;
var tX = 0;
var bA = this.m_bodyA;
var bB = this.m_bodyB;
tMat = bA.m_xf.R;
var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = bB.m_xf.R;
var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
this.m_u.x = bB.m_sweep.c.x + r2X - bA.m_sweep.c.x - r1X;
this.m_u.y = bB.m_sweep.c.y + r2Y - bA.m_sweep.c.y - r1Y;
var length = Math.sqrt(this.m_u.x * this.m_u.x + this.m_u.y * this.m_u.y);
if (length > b2Settings.b2_linearSlop) {
this.m_u.Multiply(1.0 / length);
}
else {
this.m_u.SetZero();
}
var cr1u = (r1X * this.m_u.y - r1Y * this.m_u.x);
var cr2u = (r2X * this.m_u.y - r2Y * this.m_u.x);
var invMass = bA.m_invMass + bA.m_invI * cr1u * cr1u + bB.m_invMass + bB.m_invI * cr2u * cr2u;
this.m_mass = invMass != 0.0 ? 1.0 / invMass : 0.0;
if (this.m_frequencyHz > 0.0) {
var C = length - this.m_length;
var omega = 2.0 * Math.PI * this.m_frequencyHz;
var d = 2.0 * this.m_mass * this.m_dampingRatio * omega;
var k = this.m_mass * omega * omega;
this.m_gamma = step.dt * (d + step.dt * k);
this.m_gamma = this.m_gamma != 0.0 ? 1 / this.m_gamma : 0.0;
this.m_bias = C * step.dt * k * this.m_gamma;
this.m_mass = invMass + this.m_gamma;
this.m_mass = this.m_mass != 0.0 ? 1.0 / this.m_mass : 0.0;
}
if (step.warmStarting) {
this.m_impulse *= step.dtRatio;
var PX = this.m_impulse * this.m_u.x;
var PY = this.m_impulse * this.m_u.y;
bA.m_linearVelocity.x -= bA.m_invMass * PX;
bA.m_linearVelocity.y -= bA.m_invMass * PY;
bA.m_angularVelocity -= bA.m_invI * (r1X * PY - r1Y * PX);
bB.m_linearVelocity.x += bB.m_invMass * PX;
bB.m_linearVelocity.y += bB.m_invMass * PY;
bB.m_angularVelocity += bB.m_invI * (r2X * PY - r2Y * PX);
}
else {
this.m_impulse = 0.0;
}
}
b2DistanceJoint.prototype.SolveVelocityConstraints = function (step) {
var tMat;
var bA = this.m_bodyA;
var bB = this.m_bodyB;
tMat = bA.m_xf.R;
var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
var tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = bB.m_xf.R;
var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
var v1X = bA.m_linearVelocity.x + ((-bA.m_angularVelocity * r1Y));
var v1Y = bA.m_linearVelocity.y + (bA.m_angularVelocity * r1X);
var v2X = bB.m_linearVelocity.x + ((-bB.m_angularVelocity * r2Y));
var v2Y = bB.m_linearVelocity.y + (bB.m_angularVelocity * r2X);
var Cdot = (this.m_u.x * (v2X - v1X) + this.m_u.y * (v2Y - v1Y));
var impulse = (-this.m_mass * (Cdot + this.m_bias + this.m_gamma * this.m_impulse));
this.m_impulse += impulse;
var PX = impulse * this.m_u.x;
var PY = impulse * this.m_u.y;
bA.m_linearVelocity.x -= bA.m_invMass * PX;
bA.m_linearVelocity.y -= bA.m_invMass * PY;
bA.m_angularVelocity -= bA.m_invI * (r1X * PY - r1Y * PX);
bB.m_linearVelocity.x += bB.m_invMass * PX;
bB.m_linearVelocity.y += bB.m_invMass * PY;
bB.m_angularVelocity += bB.m_invI * (r2X * PY - r2Y * PX);
}
b2DistanceJoint.prototype.SolvePositionConstraints = function (baumgarte) {
if (baumgarte === undefined) baumgarte = 0;
var tMat;
if (this.m_frequencyHz > 0.0) {
return true;
}
var bA = this.m_bodyA;
var bB = this.m_bodyB;
tMat = bA.m_xf.R;
var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
var tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = bB.m_xf.R;
var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
var dX = bB.m_sweep.c.x + r2X - bA.m_sweep.c.x - r1X;
var dY = bB.m_sweep.c.y + r2Y - bA.m_sweep.c.y - r1Y;
var length = Math.sqrt(dX * dX + dY * dY);
dX /= length;
dY /= length;
var C = length - this.m_length;
C = b2Math.Clamp(C, (-b2Settings.b2_maxLinearCorrection), b2Settings.b2_maxLinearCorrection);
var impulse = (-this.m_mass * C);
this.m_u.Set(dX, dY);
var PX = impulse * this.m_u.x;
var PY = impulse * this.m_u.y;
bA.m_sweep.c.x -= bA.m_invMass * PX;
bA.m_sweep.c.y -= bA.m_invMass * PY;
bA.m_sweep.a -= bA.m_invI * (r1X * PY - r1Y * PX);
bB.m_sweep.c.x += bB.m_invMass * PX;
bB.m_sweep.c.y += bB.m_invMass * PY;
bB.m_sweep.a += bB.m_invI * (r2X * PY - r2Y * PX);
bA.SynchronizeTransform();
bB.SynchronizeTransform();
return b2Math.Abs(C) < b2Settings.b2_linearSlop;
}
b2DistanceJointDef.inherit(Box2D.Dynamics.Joints.b2JointDef);
b2DistanceJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
b2DistanceJointDef.b2DistanceJointDef = function () {
Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
this.localAnchorA = new b2Vec2();
this.localAnchorB = new b2Vec2();
};
b2DistanceJointDef.prototype.b2DistanceJointDef = function () {
this.__super.b2JointDef.call(this);
this.type = b2Joint.e_distanceJoint;
this.length = 1.0;
this.frequencyHz = 0.0;
this.dampingRatio = 0.0;
}
b2DistanceJointDef.prototype.Initialize = function (bA, bB, anchorA, anchorB) {
this.bodyA = bA;
this.bodyB = bB;
this.localAnchorA.SetV(this.bodyA.GetLocalPoint(anchorA));
this.localAnchorB.SetV(this.bodyB.GetLocalPoint(anchorB));
var dX = anchorB.x - anchorA.x;
var dY = anchorB.y - anchorA.y;
this.length = Math.sqrt(dX * dX + dY * dY);
this.frequencyHz = 0.0;
this.dampingRatio = 0.0;
}
b2FrictionJoint.inherit(Box2D.Dynamics.Joints.b2Joint);
b2FrictionJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
b2FrictionJoint.b2FrictionJoint = function () {
Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
this.m_localAnchorA = new b2Vec2();
this.m_localAnchorB = new b2Vec2();
this.m_linearMass = new b2Mat22();
this.m_linearImpulse = new b2Vec2();
};
b2FrictionJoint.prototype.GetAnchorA = function () {
return this.m_bodyA.GetWorldPoint(this.m_localAnchorA);
}
b2FrictionJoint.prototype.GetAnchorB = function () {
return this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
}
b2FrictionJoint.prototype.GetReactionForce = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return new b2Vec2(inv_dt * this.m_linearImpulse.x, inv_dt * this.m_linearImpulse.y);
}
b2FrictionJoint.prototype.GetReactionTorque = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return inv_dt * this.m_angularImpulse;
}
b2FrictionJoint.prototype.SetMaxForce = function (force) {
if (force === undefined) force = 0;
this.m_maxForce = force;
}
b2FrictionJoint.prototype.GetMaxForce = function () {
return this.m_maxForce;
}
b2FrictionJoint.prototype.SetMaxTorque = function (torque) {
if (torque === undefined) torque = 0;
this.m_maxTorque = torque;
}
b2FrictionJoint.prototype.GetMaxTorque = function () {
return this.m_maxTorque;
}
b2FrictionJoint.prototype.b2FrictionJoint = function (def) {
this.__super.b2Joint.call(this, def);
this.m_localAnchorA.SetV(def.localAnchorA);
this.m_localAnchorB.SetV(def.localAnchorB);
this.m_linearMass.SetZero();
this.m_angularMass = 0.0;
this.m_linearImpulse.SetZero();
this.m_angularImpulse = 0.0;
this.m_maxForce = def.maxForce;
this.m_maxTorque = def.maxTorque;
}
b2FrictionJoint.prototype.InitVelocityConstraints = function (step) {
var tMat;
var tX = 0;
var bA = this.m_bodyA;
var bB = this.m_bodyB;
tMat = bA.m_xf.R;
var rAX = this.m_localAnchorA.x - bA.m_sweep.localCenter.x;
var rAY = this.m_localAnchorA.y - bA.m_sweep.localCenter.y;
tX = (tMat.col1.x * rAX + tMat.col2.x * rAY);
rAY = (tMat.col1.y * rAX + tMat.col2.y * rAY);
rAX = tX;
tMat = bB.m_xf.R;
var rBX = this.m_localAnchorB.x - bB.m_sweep.localCenter.x;
var rBY = this.m_localAnchorB.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * rBX + tMat.col2.x * rBY);
rBY = (tMat.col1.y * rBX + tMat.col2.y * rBY);
rBX = tX;
var mA = bA.m_invMass;
var mB = bB.m_invMass;
var iA = bA.m_invI;
var iB = bB.m_invI;
var K = new b2Mat22();
K.col1.x = mA + mB;
K.col2.x = 0.0;
K.col1.y = 0.0;
K.col2.y = mA + mB;
K.col1.x += iA * rAY * rAY;
K.col2.x += (-iA * rAX * rAY);
K.col1.y += (-iA * rAX * rAY);
K.col2.y += iA * rAX * rAX;
K.col1.x += iB * rBY * rBY;
K.col2.x += (-iB * rBX * rBY);
K.col1.y += (-iB * rBX * rBY);
K.col2.y += iB * rBX * rBX;
K.GetInverse(this.m_linearMass);
this.m_angularMass = iA + iB;
if (this.m_angularMass > 0.0) {
this.m_angularMass = 1.0 / this.m_angularMass;
}
if (step.warmStarting) {
this.m_linearImpulse.x *= step.dtRatio;
this.m_linearImpulse.y *= step.dtRatio;
this.m_angularImpulse *= step.dtRatio;
var P = this.m_linearImpulse;
bA.m_linearVelocity.x -= mA * P.x;
bA.m_linearVelocity.y -= mA * P.y;
bA.m_angularVelocity -= iA * (rAX * P.y - rAY * P.x + this.m_angularImpulse);
bB.m_linearVelocity.x += mB * P.x;
bB.m_linearVelocity.y += mB * P.y;
bB.m_angularVelocity += iB * (rBX * P.y - rBY * P.x + this.m_angularImpulse);
}
else {
this.m_linearImpulse.SetZero();
this.m_angularImpulse = 0.0;
}
}
b2FrictionJoint.prototype.SolveVelocityConstraints = function (step) {
var tMat;
var tX = 0;
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var vA = bA.m_linearVelocity;
var wA = bA.m_angularVelocity;
var vB = bB.m_linearVelocity;
var wB = bB.m_angularVelocity;
var mA = bA.m_invMass;
var mB = bB.m_invMass;
var iA = bA.m_invI;
var iB = bB.m_invI;
tMat = bA.m_xf.R;
var rAX = this.m_localAnchorA.x - bA.m_sweep.localCenter.x;
var rAY = this.m_localAnchorA.y - bA.m_sweep.localCenter.y;
tX = (tMat.col1.x * rAX + tMat.col2.x * rAY);
rAY = (tMat.col1.y * rAX + tMat.col2.y * rAY);
rAX = tX;
tMat = bB.m_xf.R;
var rBX = this.m_localAnchorB.x - bB.m_sweep.localCenter.x;
var rBY = this.m_localAnchorB.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * rBX + tMat.col2.x * rBY);
rBY = (tMat.col1.y * rBX + tMat.col2.y * rBY);
rBX = tX;
var maxImpulse = 0; {
var Cdot = wB - wA;
var impulse = (-this.m_angularMass * Cdot);
var oldImpulse = this.m_angularImpulse;
maxImpulse = step.dt * this.m_maxTorque;
this.m_angularImpulse = b2Math.Clamp(this.m_angularImpulse + impulse, (-maxImpulse), maxImpulse);
impulse = this.m_angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
} {
var CdotX = vB.x - wB * rBY - vA.x + wA * rAY;
var CdotY = vB.y + wB * rBX - vA.y - wA * rAX;
var impulseV = b2Math.MulMV(this.m_linearMass, new b2Vec2((-CdotX), (-CdotY)));
var oldImpulseV = this.m_linearImpulse.Copy();
this.m_linearImpulse.Add(impulseV);
maxImpulse = step.dt * this.m_maxForce;
if (this.m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) {
this.m_linearImpulse.Normalize();
this.m_linearImpulse.Multiply(maxImpulse);
}
impulseV = b2Math.SubtractVV(this.m_linearImpulse, oldImpulseV);
vA.x -= mA * impulseV.x;
vA.y -= mA * impulseV.y;
wA -= iA * (rAX * impulseV.y - rAY * impulseV.x);
vB.x += mB * impulseV.x;
vB.y += mB * impulseV.y;
wB += iB * (rBX * impulseV.y - rBY * impulseV.x);
}
bA.m_angularVelocity = wA;
bB.m_angularVelocity = wB;
}
b2FrictionJoint.prototype.SolvePositionConstraints = function (baumgarte) {
if (baumgarte === undefined) baumgarte = 0;
return true;
}
b2FrictionJointDef.inherit(Box2D.Dynamics.Joints.b2JointDef);
b2FrictionJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
b2FrictionJointDef.b2FrictionJointDef = function () {
Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
this.localAnchorA = new b2Vec2();
this.localAnchorB = new b2Vec2();
};
b2FrictionJointDef.prototype.b2FrictionJointDef = function () {
this.__super.b2JointDef.call(this);
this.type = b2Joint.e_frictionJoint;
this.maxForce = 0.0;
this.maxTorque = 0.0;
}
b2FrictionJointDef.prototype.Initialize = function (bA, bB, anchor) {
this.bodyA = bA;
this.bodyB = bB;
this.localAnchorA.SetV(this.bodyA.GetLocalPoint(anchor));
this.localAnchorB.SetV(this.bodyB.GetLocalPoint(anchor));
}
b2GearJoint.inherit(Box2D.Dynamics.Joints.b2Joint);
b2GearJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
b2GearJoint.b2GearJoint = function () {
Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
this.m_groundAnchor1 = new b2Vec2();
this.m_groundAnchor2 = new b2Vec2();
this.m_localAnchor1 = new b2Vec2();
this.m_localAnchor2 = new b2Vec2();
this.m_J = new b2Jacobian();
};
b2GearJoint.prototype.GetAnchorA = function () {
return this.m_bodyA.GetWorldPoint(this.m_localAnchor1);
}
b2GearJoint.prototype.GetAnchorB = function () {
return this.m_bodyB.GetWorldPoint(this.m_localAnchor2);
}
b2GearJoint.prototype.GetReactionForce = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return new b2Vec2(inv_dt * this.m_impulse * this.m_J.linearB.x, inv_dt * this.m_impulse * this.m_J.linearB.y);
}
b2GearJoint.prototype.GetReactionTorque = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
var tMat = this.m_bodyB.m_xf.R;
var rX = this.m_localAnchor1.x - this.m_bodyB.m_sweep.localCenter.x;
var rY = this.m_localAnchor1.y - this.m_bodyB.m_sweep.localCenter.y;
var tX = tMat.col1.x * rX + tMat.col2.x * rY;
rY = tMat.col1.y * rX + tMat.col2.y * rY;
rX = tX;
var PX = this.m_impulse * this.m_J.linearB.x;
var PY = this.m_impulse * this.m_J.linearB.y;
return inv_dt * (this.m_impulse * this.m_J.angularB - rX * PY + rY * PX);
}
b2GearJoint.prototype.GetRatio = function () {
return this.m_ratio;
}
b2GearJoint.prototype.SetRatio = function (ratio) {
if (ratio === undefined) ratio = 0;
this.m_ratio = ratio;
}
b2GearJoint.prototype.b2GearJoint = function (def) {
this.__super.b2Joint.call(this, def);
var type1 = parseInt(def.joint1.m_type);
var type2 = parseInt(def.joint2.m_type);
this.m_revolute1 = null;
this.m_prismatic1 = null;
this.m_revolute2 = null;
this.m_prismatic2 = null;
var coordinate1 = 0;
var coordinate2 = 0;
this.m_ground1 = def.joint1.GetBodyA();
this.m_bodyA = def.joint1.GetBodyB();
if (type1 == b2Joint.e_revoluteJoint) {
this.m_revolute1 = (def.joint1 instanceof b2RevoluteJoint ? def.joint1 : null);
this.m_groundAnchor1.SetV(this.m_revolute1.m_localAnchor1);
this.m_localAnchor1.SetV(this.m_revolute1.m_localAnchor2);
coordinate1 = this.m_revolute1.GetJointAngle();
}
else {
this.m_prismatic1 = (def.joint1 instanceof b2PrismaticJoint ? def.joint1 : null);
this.m_groundAnchor1.SetV(this.m_prismatic1.m_localAnchor1);
this.m_localAnchor1.SetV(this.m_prismatic1.m_localAnchor2);
coordinate1 = this.m_prismatic1.GetJointTranslation();
}
this.m_ground2 = def.joint2.GetBodyA();
this.m_bodyB = def.joint2.GetBodyB();
if (type2 == b2Joint.e_revoluteJoint) {
this.m_revolute2 = (def.joint2 instanceof b2RevoluteJoint ? def.joint2 : null);
this.m_groundAnchor2.SetV(this.m_revolute2.m_localAnchor1);
this.m_localAnchor2.SetV(this.m_revolute2.m_localAnchor2);
coordinate2 = this.m_revolute2.GetJointAngle();
}
else {
this.m_prismatic2 = (def.joint2 instanceof b2PrismaticJoint ? def.joint2 : null);
this.m_groundAnchor2.SetV(this.m_prismatic2.m_localAnchor1);
this.m_localAnchor2.SetV(this.m_prismatic2.m_localAnchor2);
coordinate2 = this.m_prismatic2.GetJointTranslation();
}
this.m_ratio = def.ratio;
this.m_constant = coordinate1 + this.m_ratio * coordinate2;
this.m_impulse = 0.0;
}
b2GearJoint.prototype.InitVelocityConstraints = function (step) {
var g1 = this.m_ground1;
var g2 = this.m_ground2;
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var ugX = 0;
var ugY = 0;
var rX = 0;
var rY = 0;
var tMat;
var tVec;
var crug = 0;
var tX = 0;
var K = 0.0;
this.m_J.SetZero();
if (this.m_revolute1) {
this.m_J.angularA = (-1.0);
K += bA.m_invI;
}
else {
tMat = g1.m_xf.R;
tVec = this.m_prismatic1.m_localXAxis1;
ugX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
ugY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
tMat = bA.m_xf.R;
rX = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
rY = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
tX = tMat.col1.x * rX + tMat.col2.x * rY;
rY = tMat.col1.y * rX + tMat.col2.y * rY;
rX = tX;
crug = rX * ugY - rY * ugX;
this.m_J.linearA.Set((-ugX), (-ugY));
this.m_J.angularA = (-crug);
K += bA.m_invMass + bA.m_invI * crug * crug;
}
if (this.m_revolute2) {
this.m_J.angularB = (-this.m_ratio);
K += this.m_ratio * this.m_ratio * bB.m_invI;
}
else {
tMat = g2.m_xf.R;
tVec = this.m_prismatic2.m_localXAxis1;
ugX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
ugY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
tMat = bB.m_xf.R;
rX = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
rY = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
tX = tMat.col1.x * rX + tMat.col2.x * rY;
rY = tMat.col1.y * rX + tMat.col2.y * rY;
rX = tX;
crug = rX * ugY - rY * ugX;
this.m_J.linearB.Set((-this.m_ratio * ugX), (-this.m_ratio * ugY));
this.m_J.angularB = (-this.m_ratio * crug);
K += this.m_ratio * this.m_ratio * (bB.m_invMass + bB.m_invI * crug * crug);
}
this.m_mass = K > 0.0 ? 1.0 / K : 0.0;
if (step.warmStarting) {
bA.m_linearVelocity.x += bA.m_invMass * this.m_impulse * this.m_J.linearA.x;
bA.m_linearVelocity.y += bA.m_invMass * this.m_impulse * this.m_J.linearA.y;
bA.m_angularVelocity += bA.m_invI * this.m_impulse * this.m_J.angularA;
bB.m_linearVelocity.x += bB.m_invMass * this.m_impulse * this.m_J.linearB.x;
bB.m_linearVelocity.y += bB.m_invMass * this.m_impulse * this.m_J.linearB.y;
bB.m_angularVelocity += bB.m_invI * this.m_impulse * this.m_J.angularB;
}
else {
this.m_impulse = 0.0;
}
}
b2GearJoint.prototype.SolveVelocityConstraints = function (step) {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var Cdot = this.m_J.Compute(bA.m_linearVelocity, bA.m_angularVelocity, bB.m_linearVelocity, bB.m_angularVelocity);
var impulse = (-this.m_mass * Cdot);
this.m_impulse += impulse;
bA.m_linearVelocity.x += bA.m_invMass * impulse * this.m_J.linearA.x;
bA.m_linearVelocity.y += bA.m_invMass * impulse * this.m_J.linearA.y;
bA.m_angularVelocity += bA.m_invI * impulse * this.m_J.angularA;
bB.m_linearVelocity.x += bB.m_invMass * impulse * this.m_J.linearB.x;
bB.m_linearVelocity.y += bB.m_invMass * impulse * this.m_J.linearB.y;
bB.m_angularVelocity += bB.m_invI * impulse * this.m_J.angularB;
}
b2GearJoint.prototype.SolvePositionConstraints = function (baumgarte) {
if (baumgarte === undefined) baumgarte = 0;
var linearError = 0.0;
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var coordinate1 = 0;
var coordinate2 = 0;
if (this.m_revolute1) {
coordinate1 = this.m_revolute1.GetJointAngle();
}
else {
coordinate1 = this.m_prismatic1.GetJointTranslation();
}
if (this.m_revolute2) {
coordinate2 = this.m_revolute2.GetJointAngle();
}
else {
coordinate2 = this.m_prismatic2.GetJointTranslation();
}
var C = this.m_constant - (coordinate1 + this.m_ratio * coordinate2);
var impulse = (-this.m_mass * C);
bA.m_sweep.c.x += bA.m_invMass * impulse * this.m_J.linearA.x;
bA.m_sweep.c.y += bA.m_invMass * impulse * this.m_J.linearA.y;
bA.m_sweep.a += bA.m_invI * impulse * this.m_J.angularA;
bB.m_sweep.c.x += bB.m_invMass * impulse * this.m_J.linearB.x;
bB.m_sweep.c.y += bB.m_invMass * impulse * this.m_J.linearB.y;
bB.m_sweep.a += bB.m_invI * impulse * this.m_J.angularB;
bA.SynchronizeTransform();
bB.SynchronizeTransform();
return linearError < b2Settings.b2_linearSlop;
}
b2GearJointDef.inherit(Box2D.Dynamics.Joints.b2JointDef);
b2GearJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
b2GearJointDef.b2GearJointDef = function () {
Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
};
b2GearJointDef.prototype.b2GearJointDef = function () {
this.__super.b2JointDef.call(this);
this.type = b2Joint.e_gearJoint;
this.joint1 = null;
this.joint2 = null;
this.ratio = 1.0;
}
b2Jacobian.b2Jacobian = function () {
this.linearA = new b2Vec2();
this.linearB = new b2Vec2();
};
b2Jacobian.prototype.SetZero = function () {
this.linearA.SetZero();
this.angularA = 0.0;
this.linearB.SetZero();
this.angularB = 0.0;
}
b2Jacobian.prototype.Set = function (x1, a1, x2, a2) {
if (a1 === undefined) a1 = 0;
if (a2 === undefined) a2 = 0;
this.linearA.SetV(x1);
this.angularA = a1;
this.linearB.SetV(x2);
this.angularB = a2;
}
b2Jacobian.prototype.Compute = function (x1, a1, x2, a2) {
if (a1 === undefined) a1 = 0;
if (a2 === undefined) a2 = 0;
return (this.linearA.x * x1.x + this.linearA.y * x1.y) + this.angularA * a1 + (this.linearB.x * x2.x + this.linearB.y * x2.y) + this.angularB * a2;
}
b2Joint.b2Joint = function () {
this.m_edgeA = new b2JointEdge();
this.m_edgeB = new b2JointEdge();
this.m_localCenterA = new b2Vec2();
this.m_localCenterB = new b2Vec2();
};
b2Joint.prototype.GetType = function () {
return this.m_type;
}
b2Joint.prototype.GetAnchorA = function () {
return null;
}
b2Joint.prototype.GetAnchorB = function () {
return null;
}
b2Joint.prototype.GetReactionForce = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return null;
}
b2Joint.prototype.GetReactionTorque = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return 0.0;
}
b2Joint.prototype.GetBodyA = function () {
return this.m_bodyA;
}
b2Joint.prototype.GetBodyB = function () {
return this.m_bodyB;
}
b2Joint.prototype.GetNext = function () {
return this.m_next;
}
b2Joint.prototype.GetUserData = function () {
return this.m_userData;
}
b2Joint.prototype.SetUserData = function (data) {
this.m_userData = data;
}
b2Joint.prototype.IsActive = function () {
return this.m_bodyA.IsActive() && this.m_bodyB.IsActive();
}
b2Joint.prototype.Create = function (def, allocator) {
var joint = null;
switch (def.type) {
case b2Joint.e_distanceJoint:
{
joint = new b2DistanceJoint((def instanceof b2DistanceJointDef ? def : null));
}
break;
case b2Joint.e_mouseJoint:
{
joint = new b2MouseJoint((def instanceof b2MouseJointDef ? def : null));
}
break;
case b2Joint.e_prismaticJoint:
{
joint = new b2PrismaticJoint((def instanceof b2PrismaticJointDef ? def : null));
}
break;
case b2Joint.e_revoluteJoint:
{
joint = new b2RevoluteJoint((def instanceof b2RevoluteJointDef ? def : null));
}
break;
case b2Joint.e_pulleyJoint:
{
joint = new b2PulleyJoint((def instanceof b2PulleyJointDef ? def : null));
}
break;
case b2Joint.e_gearJoint:
{
joint = new b2GearJoint((def instanceof b2GearJointDef ? def : null));
}
break;
case b2Joint.e_lineJoint:
{
joint = new b2LineJoint((def instanceof b2LineJointDef ? def : null));
}
break;
case b2Joint.e_weldJoint:
{
joint = new b2WeldJoint((def instanceof b2WeldJointDef ? def : null));
}
break;
case b2Joint.e_frictionJoint:
{
joint = new b2FrictionJoint((def instanceof b2FrictionJointDef ? def : null));
}
break;
default:
break;
}
return joint;
}
b2Joint.Create = b2Joint.prototype.Create;
b2Joint.prototype.Destroy = function (joint, allocator) {}
b2Joint.Destroy = b2Joint.prototype.Destroy;
b2Joint.prototype.b2Joint = function (def) {
b2Settings.b2Assert(def.bodyA != def.bodyB);
this.m_type = def.type;
this.m_prev = null;
this.m_next = null;
this.m_bodyA = def.bodyA;
this.m_bodyB = def.bodyB;
this.m_collideConnected = def.collideConnected;
this.m_islandFlag = false;
this.m_userData = def.userData;
}
b2Joint.prototype.InitVelocityConstraints = function (step) {}
b2Joint.prototype.SolveVelocityConstraints = function (step) {}
b2Joint.prototype.FinalizeVelocityConstraints = function () {}
b2Joint.prototype.SolvePositionConstraints = function (baumgarte) {
if (baumgarte === undefined) baumgarte = 0;
return false;
}
_A2J_postDefs.push(function () {
Box2D.Dynamics.Joints.b2Joint.e_unknownJoint = 0;
Box2D.Dynamics.Joints.b2Joint.prototype.e_unknownJoint = Box2D.Dynamics.Joints.b2Joint.e_unknownJoint;
Box2D.Dynamics.Joints.b2Joint.e_revoluteJoint = 1;
Box2D.Dynamics.Joints.b2Joint.prototype.e_revoluteJoint = Box2D.Dynamics.Joints.b2Joint.e_revoluteJoint;
Box2D.Dynamics.Joints.b2Joint.e_prismaticJoint = 2;
Box2D.Dynamics.Joints.b2Joint.prototype.e_prismaticJoint = Box2D.Dynamics.Joints.b2Joint.e_prismaticJoint;
Box2D.Dynamics.Joints.b2Joint.e_distanceJoint = 3;
Box2D.Dynamics.Joints.b2Joint.prototype.e_distanceJoint = Box2D.Dynamics.Joints.b2Joint.e_distanceJoint;
Box2D.Dynamics.Joints.b2Joint.e_pulleyJoint = 4;
Box2D.Dynamics.Joints.b2Joint.prototype.e_pulleyJoint = Box2D.Dynamics.Joints.b2Joint.e_pulleyJoint;
Box2D.Dynamics.Joints.b2Joint.e_mouseJoint = 5;
Box2D.Dynamics.Joints.b2Joint.prototype.e_mouseJoint = Box2D.Dynamics.Joints.b2Joint.e_mouseJoint;
Box2D.Dynamics.Joints.b2Joint.e_gearJoint = 6;
Box2D.Dynamics.Joints.b2Joint.prototype.e_gearJoint = Box2D.Dynamics.Joints.b2Joint.e_gearJoint;
Box2D.Dynamics.Joints.b2Joint.e_lineJoint = 7;
Box2D.Dynamics.Joints.b2Joint.prototype.e_lineJoint = Box2D.Dynamics.Joints.b2Joint.e_lineJoint;
Box2D.Dynamics.Joints.b2Joint.e_weldJoint = 8;
Box2D.Dynamics.Joints.b2Joint.prototype.e_weldJoint = Box2D.Dynamics.Joints.b2Joint.e_weldJoint;
Box2D.Dynamics.Joints.b2Joint.e_frictionJoint = 9;
Box2D.Dynamics.Joints.b2Joint.prototype.e_frictionJoint = Box2D.Dynamics.Joints.b2Joint.e_frictionJoint;
Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit = 0;
Box2D.Dynamics.Joints.b2Joint.prototype.e_inactiveLimit = Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit;
Box2D.Dynamics.Joints.b2Joint.e_atLowerLimit = 1;
Box2D.Dynamics.Joints.b2Joint.prototype.e_atLowerLimit = Box2D.Dynamics.Joints.b2Joint.e_atLowerLimit;
Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit = 2;
Box2D.Dynamics.Joints.b2Joint.prototype.e_atUpperLimit = Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit;
Box2D.Dynamics.Joints.b2Joint.e_equalLimits = 3;
Box2D.Dynamics.Joints.b2Joint.prototype.e_equalLimits = Box2D.Dynamics.Joints.b2Joint.e_equalLimits;
});
b2JointDef.b2JointDef = function () {};
b2JointDef.prototype.b2JointDef = function () {
this.type = b2Joint.e_unknownJoint;
this.userData = null;
this.bodyA = null;
this.bodyB = null;
this.collideConnected = false;
}
b2JointEdge.b2JointEdge = function () {};
b2LineJoint.inherit(Box2D.Dynamics.Joints.b2Joint);
b2LineJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
b2LineJoint.b2LineJoint = function () {
Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
this.m_localAnchor1 = new b2Vec2();
this.m_localAnchor2 = new b2Vec2();
this.m_localXAxis1 = new b2Vec2();
this.m_localYAxis1 = new b2Vec2();
this.m_axis = new b2Vec2();
this.m_perp = new b2Vec2();
this.m_K = new b2Mat22();
this.m_impulse = new b2Vec2();
};
b2LineJoint.prototype.GetAnchorA = function () {
return this.m_bodyA.GetWorldPoint(this.m_localAnchor1);
}
b2LineJoint.prototype.GetAnchorB = function () {
return this.m_bodyB.GetWorldPoint(this.m_localAnchor2);
}
b2LineJoint.prototype.GetReactionForce = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return new b2Vec2(inv_dt * (this.m_impulse.x * this.m_perp.x + (this.m_motorImpulse + this.m_impulse.y) * this.m_axis.x), inv_dt * (this.m_impulse.x * this.m_perp.y + (this.m_motorImpulse + this.m_impulse.y) * this.m_axis.y));
}
b2LineJoint.prototype.GetReactionTorque = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return inv_dt * this.m_impulse.y;
}
b2LineJoint.prototype.GetJointTranslation = function () {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var tMat;
var p1 = bA.GetWorldPoint(this.m_localAnchor1);
var p2 = bB.GetWorldPoint(this.m_localAnchor2);
var dX = p2.x - p1.x;
var dY = p2.y - p1.y;
var axis = bA.GetWorldVector(this.m_localXAxis1);
var translation = axis.x * dX + axis.y * dY;
return translation;
}
b2LineJoint.prototype.GetJointSpeed = function () {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var tMat;
tMat = bA.m_xf.R;
var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
var tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = bB.m_xf.R;
var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
var p1X = bA.m_sweep.c.x + r1X;
var p1Y = bA.m_sweep.c.y + r1Y;
var p2X = bB.m_sweep.c.x + r2X;
var p2Y = bB.m_sweep.c.y + r2Y;
var dX = p2X - p1X;
var dY = p2Y - p1Y;
var axis = bA.GetWorldVector(this.m_localXAxis1);
var v1 = bA.m_linearVelocity;
var v2 = bB.m_linearVelocity;
var w1 = bA.m_angularVelocity;
var w2 = bB.m_angularVelocity;
var speed = (dX * ((-w1 * axis.y)) + dY * (w1 * axis.x)) + (axis.x * (((v2.x + ((-w2 * r2Y))) - v1.x) - ((-w1 * r1Y))) + axis.y * (((v2.y + (w2 * r2X)) - v1.y) - (w1 * r1X)));
return speed;
}
b2LineJoint.prototype.IsLimitEnabled = function () {
return this.m_enableLimit;
}
b2LineJoint.prototype.EnableLimit = function (flag) {
this.m_bodyA.SetAwake(true);
this.m_bodyB.SetAwake(true);
this.m_enableLimit = flag;
}
b2LineJoint.prototype.GetLowerLimit = function () {
return this.m_lowerTranslation;
}
b2LineJoint.prototype.GetUpperLimit = function () {
return this.m_upperTranslation;
}
b2LineJoint.prototype.SetLimits = function (lower, upper) {
if (lower === undefined) lower = 0;
if (upper === undefined) upper = 0;
this.m_bodyA.SetAwake(true);
this.m_bodyB.SetAwake(true);
this.m_lowerTranslation = lower;
this.m_upperTranslation = upper;
}
b2LineJoint.prototype.IsMotorEnabled = function () {
return this.m_enableMotor;
}
b2LineJoint.prototype.EnableMotor = function (flag) {
this.m_bodyA.SetAwake(true);
this.m_bodyB.SetAwake(true);
this.m_enableMotor = flag;
}
b2LineJoint.prototype.SetMotorSpeed = function (speed) {
if (speed === undefined) speed = 0;
this.m_bodyA.SetAwake(true);
this.m_bodyB.SetAwake(true);
this.m_motorSpeed = speed;
}
b2LineJoint.prototype.GetMotorSpeed = function () {
return this.m_motorSpeed;
}
b2LineJoint.prototype.SetMaxMotorForce = function (force) {
if (force === undefined) force = 0;
this.m_bodyA.SetAwake(true);
this.m_bodyB.SetAwake(true);
this.m_maxMotorForce = force;
}
b2LineJoint.prototype.GetMaxMotorForce = function () {
return this.m_maxMotorForce;
}
b2LineJoint.prototype.GetMotorForce = function () {
return this.m_motorImpulse;
}
b2LineJoint.prototype.b2LineJoint = function (def) {
this.__super.b2Joint.call(this, def);
var tMat;
var tX = 0;
var tY = 0;
this.m_localAnchor1.SetV(def.localAnchorA);
this.m_localAnchor2.SetV(def.localAnchorB);
this.m_localXAxis1.SetV(def.localAxisA);
this.m_localYAxis1.x = (-this.m_localXAxis1.y);
this.m_localYAxis1.y = this.m_localXAxis1.x;
this.m_impulse.SetZero();
this.m_motorMass = 0.0;
this.m_motorImpulse = 0.0;
this.m_lowerTranslation = def.lowerTranslation;
this.m_upperTranslation = def.upperTranslation;
this.m_maxMotorForce = def.maxMotorForce;
this.m_motorSpeed = def.motorSpeed;
this.m_enableLimit = def.enableLimit;
this.m_enableMotor = def.enableMotor;
this.m_limitState = this.e_inactiveLimit;
this.m_axis.SetZero();
this.m_perp.SetZero();
}
b2LineJoint.prototype.InitVelocityConstraints = function (step) {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var tMat;
var tX = 0;
this.m_localCenterA.SetV(bA.GetLocalCenter());
this.m_localCenterB.SetV(bB.GetLocalCenter());
var xf1 = bA.GetTransform();
var xf2 = bB.GetTransform();
tMat = bA.m_xf.R;
var r1X = this.m_localAnchor1.x - this.m_localCenterA.x;
var r1Y = this.m_localAnchor1.y - this.m_localCenterA.y;
tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = bB.m_xf.R;
var r2X = this.m_localAnchor2.x - this.m_localCenterB.x;
var r2Y = this.m_localAnchor2.y - this.m_localCenterB.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
var dX = bB.m_sweep.c.x + r2X - bA.m_sweep.c.x - r1X;
var dY = bB.m_sweep.c.y + r2Y - bA.m_sweep.c.y - r1Y;
this.m_invMassA = bA.m_invMass;
this.m_invMassB = bB.m_invMass;
this.m_invIA = bA.m_invI;
this.m_invIB = bB.m_invI; {
this.m_axis.SetV(b2Math.MulMV(xf1.R, this.m_localXAxis1));
this.m_a1 = (dX + r1X) * this.m_axis.y - (dY + r1Y) * this.m_axis.x;
this.m_a2 = r2X * this.m_axis.y - r2Y * this.m_axis.x;
this.m_motorMass = this.m_invMassA + this.m_invMassB + this.m_invIA * this.m_a1 * this.m_a1 + this.m_invIB * this.m_a2 * this.m_a2;
this.m_motorMass = this.m_motorMass > Number.MIN_VALUE ? 1.0 / this.m_motorMass : 0.0;
} {
this.m_perp.SetV(b2Math.MulMV(xf1.R, this.m_localYAxis1));
this.m_s1 = (dX + r1X) * this.m_perp.y - (dY + r1Y) * this.m_perp.x;
this.m_s2 = r2X * this.m_perp.y - r2Y * this.m_perp.x;
var m1 = this.m_invMassA;
var m2 = this.m_invMassB;
var i1 = this.m_invIA;
var i2 = this.m_invIB;
this.m_K.col1.x = m1 + m2 + i1 * this.m_s1 * this.m_s1 + i2 * this.m_s2 * this.m_s2;
this.m_K.col1.y = i1 * this.m_s1 * this.m_a1 + i2 * this.m_s2 * this.m_a2;
this.m_K.col2.x = this.m_K.col1.y;
this.m_K.col2.y = m1 + m2 + i1 * this.m_a1 * this.m_a1 + i2 * this.m_a2 * this.m_a2;
}
if (this.m_enableLimit) {
var jointTransition = this.m_axis.x * dX + this.m_axis.y * dY;
if (b2Math.Abs(this.m_upperTranslation - this.m_lowerTranslation) < 2.0 * b2Settings.b2_linearSlop) {
this.m_limitState = this.e_equalLimits;
}
else if (jointTransition <= this.m_lowerTranslation) {
if (this.m_limitState != this.e_atLowerLimit) {
this.m_limitState = this.e_atLowerLimit;
this.m_impulse.y = 0.0;
}
}
else if (jointTransition >= this.m_upperTranslation) {
if (this.m_limitState != this.e_atUpperLimit) {
this.m_limitState = this.e_atUpperLimit;
this.m_impulse.y = 0.0;
}
}
else {
this.m_limitState = this.e_inactiveLimit;
this.m_impulse.y = 0.0;
}
}
else {
this.m_limitState = this.e_inactiveLimit;
}
if (this.m_enableMotor == false) {
this.m_motorImpulse = 0.0;
}
if (step.warmStarting) {
this.m_impulse.x *= step.dtRatio;
this.m_impulse.y *= step.dtRatio;
this.m_motorImpulse *= step.dtRatio;
var PX = this.m_impulse.x * this.m_perp.x + (this.m_motorImpulse + this.m_impulse.y) * this.m_axis.x;
var PY = this.m_impulse.x * this.m_perp.y + (this.m_motorImpulse + this.m_impulse.y) * this.m_axis.y;
var L1 = this.m_impulse.x * this.m_s1 + (this.m_motorImpulse + this.m_impulse.y) * this.m_a1;
var L2 = this.m_impulse.x * this.m_s2 + (this.m_motorImpulse + this.m_impulse.y) * this.m_a2;
bA.m_linearVelocity.x -= this.m_invMassA * PX;
bA.m_linearVelocity.y -= this.m_invMassA * PY;
bA.m_angularVelocity -= this.m_invIA * L1;
bB.m_linearVelocity.x += this.m_invMassB * PX;
bB.m_linearVelocity.y += this.m_invMassB * PY;
bB.m_angularVelocity += this.m_invIB * L2;
}
else {
this.m_impulse.SetZero();
this.m_motorImpulse = 0.0;
}
}
b2LineJoint.prototype.SolveVelocityConstraints = function (step) {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var v1 = bA.m_linearVelocity;
var w1 = bA.m_angularVelocity;
var v2 = bB.m_linearVelocity;
var w2 = bB.m_angularVelocity;
var PX = 0;
var PY = 0;
var L1 = 0;
var L2 = 0;
if (this.m_enableMotor && this.m_limitState != this.e_equalLimits) {
var Cdot = this.m_axis.x * (v2.x - v1.x) + this.m_axis.y * (v2.y - v1.y) + this.m_a2 * w2 - this.m_a1 * w1;
var impulse = this.m_motorMass * (this.m_motorSpeed - Cdot);
var oldImpulse = this.m_motorImpulse;
var maxImpulse = step.dt * this.m_maxMotorForce;
this.m_motorImpulse = b2Math.Clamp(this.m_motorImpulse + impulse, (-maxImpulse), maxImpulse);
impulse = this.m_motorImpulse - oldImpulse;
PX = impulse * this.m_axis.x;
PY = impulse * this.m_axis.y;
L1 = impulse * this.m_a1;
L2 = impulse * this.m_a2;
v1.x -= this.m_invMassA * PX;
v1.y -= this.m_invMassA * PY;
w1 -= this.m_invIA * L1;
v2.x += this.m_invMassB * PX;
v2.y += this.m_invMassB * PY;
w2 += this.m_invIB * L2;
}
var Cdot1 = this.m_perp.x * (v2.x - v1.x) + this.m_perp.y * (v2.y - v1.y) + this.m_s2 * w2 - this.m_s1 * w1;
if (this.m_enableLimit && this.m_limitState != this.e_inactiveLimit) {
var Cdot2 = this.m_axis.x * (v2.x - v1.x) + this.m_axis.y * (v2.y - v1.y) + this.m_a2 * w2 - this.m_a1 * w1;
var f1 = this.m_impulse.Copy();
var df = this.m_K.Solve(new b2Vec2(), (-Cdot1), (-Cdot2));
this.m_impulse.Add(df);
if (this.m_limitState == this.e_atLowerLimit) {
this.m_impulse.y = b2Math.Max(this.m_impulse.y, 0.0);
}
else if (this.m_limitState == this.e_atUpperLimit) {
this.m_impulse.y = b2Math.Min(this.m_impulse.y, 0.0);
}
var b = (-Cdot1) - (this.m_impulse.y - f1.y) * this.m_K.col2.x;
var f2r = 0;
if (this.m_K.col1.x != 0.0) {
f2r = b / this.m_K.col1.x + f1.x;
}
else {
f2r = f1.x;
}
this.m_impulse.x = f2r;
df.x = this.m_impulse.x - f1.x;
df.y = this.m_impulse.y - f1.y;
PX = df.x * this.m_perp.x + df.y * this.m_axis.x;
PY = df.x * this.m_perp.y + df.y * this.m_axis.y;
L1 = df.x * this.m_s1 + df.y * this.m_a1;
L2 = df.x * this.m_s2 + df.y * this.m_a2;
v1.x -= this.m_invMassA * PX;
v1.y -= this.m_invMassA * PY;
w1 -= this.m_invIA * L1;
v2.x += this.m_invMassB * PX;
v2.y += this.m_invMassB * PY;
w2 += this.m_invIB * L2;
}
else {
var df2 = 0;
if (this.m_K.col1.x != 0.0) {
df2 = ((-Cdot1)) / this.m_K.col1.x;
}
else {
df2 = 0.0;
}
this.m_impulse.x += df2;
PX = df2 * this.m_perp.x;
PY = df2 * this.m_perp.y;
L1 = df2 * this.m_s1;
L2 = df2 * this.m_s2;
v1.x -= this.m_invMassA * PX;
v1.y -= this.m_invMassA * PY;
w1 -= this.m_invIA * L1;
v2.x += this.m_invMassB * PX;
v2.y += this.m_invMassB * PY;
w2 += this.m_invIB * L2;
}
bA.m_linearVelocity.SetV(v1);
bA.m_angularVelocity = w1;
bB.m_linearVelocity.SetV(v2);
bB.m_angularVelocity = w2;
}
b2LineJoint.prototype.SolvePositionConstraints = function (baumgarte) {
if (baumgarte === undefined) baumgarte = 0;
var limitC = 0;
var oldLimitImpulse = 0;
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var c1 = bA.m_sweep.c;
var a1 = bA.m_sweep.a;
var c2 = bB.m_sweep.c;
var a2 = bB.m_sweep.a;
var tMat;
var tX = 0;
var m1 = 0;
var m2 = 0;
var i1 = 0;
var i2 = 0;
var linearError = 0.0;
var angularError = 0.0;
var active = false;
var C2 = 0.0;
var R1 = b2Mat22.FromAngle(a1);
var R2 = b2Mat22.FromAngle(a2);
tMat = R1;
var r1X = this.m_localAnchor1.x - this.m_localCenterA.x;
var r1Y = this.m_localAnchor1.y - this.m_localCenterA.y;
tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = R2;
var r2X = this.m_localAnchor2.x - this.m_localCenterB.x;
var r2Y = this.m_localAnchor2.y - this.m_localCenterB.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
var dX = c2.x + r2X - c1.x - r1X;
var dY = c2.y + r2Y - c1.y - r1Y;
if (this.m_enableLimit) {
this.m_axis = b2Math.MulMV(R1, this.m_localXAxis1);
this.m_a1 = (dX + r1X) * this.m_axis.y - (dY + r1Y) * this.m_axis.x;
this.m_a2 = r2X * this.m_axis.y - r2Y * this.m_axis.x;
var translation = this.m_axis.x * dX + this.m_axis.y * dY;
if (b2Math.Abs(this.m_upperTranslation - this.m_lowerTranslation) < 2.0 * b2Settings.b2_linearSlop) {
C2 = b2Math.Clamp(translation, (-b2Settings.b2_maxLinearCorrection), b2Settings.b2_maxLinearCorrection);
linearError = b2Math.Abs(translation);
active = true;
}
else if (translation <= this.m_lowerTranslation) {
C2 = b2Math.Clamp(translation - this.m_lowerTranslation + b2Settings.b2_linearSlop, (-b2Settings.b2_maxLinearCorrection), 0.0);
linearError = this.m_lowerTranslation - translation;
active = true;
}
else if (translation >= this.m_upperTranslation) {
C2 = b2Math.Clamp(translation - this.m_upperTranslation + b2Settings.b2_linearSlop, 0.0, b2Settings.b2_maxLinearCorrection);
linearError = translation - this.m_upperTranslation;
active = true;
}
}
this.m_perp = b2Math.MulMV(R1, this.m_localYAxis1);
this.m_s1 = (dX + r1X) * this.m_perp.y - (dY + r1Y) * this.m_perp.x;
this.m_s2 = r2X * this.m_perp.y - r2Y * this.m_perp.x;
var impulse = new b2Vec2();
var C1 = this.m_perp.x * dX + this.m_perp.y * dY;
linearError = b2Math.Max(linearError, b2Math.Abs(C1));
angularError = 0.0;
if (active) {
m1 = this.m_invMassA;
m2 = this.m_invMassB;
i1 = this.m_invIA;
i2 = this.m_invIB;
this.m_K.col1.x = m1 + m2 + i1 * this.m_s1 * this.m_s1 + i2 * this.m_s2 * this.m_s2;
this.m_K.col1.y = i1 * this.m_s1 * this.m_a1 + i2 * this.m_s2 * this.m_a2;
this.m_K.col2.x = this.m_K.col1.y;
this.m_K.col2.y = m1 + m2 + i1 * this.m_a1 * this.m_a1 + i2 * this.m_a2 * this.m_a2;
this.m_K.Solve(impulse, (-C1), (-C2));
}
else {
m1 = this.m_invMassA;
m2 = this.m_invMassB;
i1 = this.m_invIA;
i2 = this.m_invIB;
var k11 = m1 + m2 + i1 * this.m_s1 * this.m_s1 + i2 * this.m_s2 * this.m_s2;
var impulse1 = 0;
if (k11 != 0.0) {
impulse1 = ((-C1)) / k11;
}
else {
impulse1 = 0.0;
}
impulse.x = impulse1;
impulse.y = 0.0;
}
var PX = impulse.x * this.m_perp.x + impulse.y * this.m_axis.x;
var PY = impulse.x * this.m_perp.y + impulse.y * this.m_axis.y;
var L1 = impulse.x * this.m_s1 + impulse.y * this.m_a1;
var L2 = impulse.x * this.m_s2 + impulse.y * this.m_a2;
c1.x -= this.m_invMassA * PX;
c1.y -= this.m_invMassA * PY;
a1 -= this.m_invIA * L1;
c2.x += this.m_invMassB * PX;
c2.y += this.m_invMassB * PY;
a2 += this.m_invIB * L2;
bA.m_sweep.a = a1;
bB.m_sweep.a = a2;
bA.SynchronizeTransform();
bB.SynchronizeTransform();
return linearError <= b2Settings.b2_linearSlop && angularError <= b2Settings.b2_angularSlop;
}
b2LineJointDef.inherit(Box2D.Dynamics.Joints.b2JointDef);
b2LineJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
b2LineJointDef.b2LineJointDef = function () {
Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
this.localAnchorA = new b2Vec2();
this.localAnchorB = new b2Vec2();
this.localAxisA = new b2Vec2();
};
b2LineJointDef.prototype.b2LineJointDef = function () {
this.__super.b2JointDef.call(this);
this.type = b2Joint.e_lineJoint;
this.localAxisA.Set(1.0, 0.0);
this.enableLimit = false;
this.lowerTranslation = 0.0;
this.upperTranslation = 0.0;
this.enableMotor = false;
this.maxMotorForce = 0.0;
this.motorSpeed = 0.0;
}
b2LineJointDef.prototype.Initialize = function (bA, bB, anchor, axis) {
this.bodyA = bA;
this.bodyB = bB;
this.localAnchorA = this.bodyA.GetLocalPoint(anchor);
this.localAnchorB = this.bodyB.GetLocalPoint(anchor);
this.localAxisA = this.bodyA.GetLocalVector(axis);
}
b2MouseJoint.inherit(Box2D.Dynamics.Joints.b2Joint);
b2MouseJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
b2MouseJoint.b2MouseJoint = function () {
Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
this.K = new b2Mat22();
this.K1 = new b2Mat22();
this.K2 = new b2Mat22();
this.m_localAnchor = new b2Vec2();
this.m_target = new b2Vec2();
this.m_impulse = new b2Vec2();
this.m_mass = new b2Mat22();
this.m_C = new b2Vec2();
};
b2MouseJoint.prototype.GetAnchorA = function () {
return this.m_target;
}
b2MouseJoint.prototype.GetAnchorB = function () {
return this.m_bodyB.GetWorldPoint(this.m_localAnchor);
}
b2MouseJoint.prototype.GetReactionForce = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return new b2Vec2(inv_dt * this.m_impulse.x, inv_dt * this.m_impulse.y);
}
b2MouseJoint.prototype.GetReactionTorque = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return 0.0;
}
b2MouseJoint.prototype.GetTarget = function () {
return this.m_target;
}
b2MouseJoint.prototype.SetTarget = function (target) {
if (this.m_bodyB.IsAwake() == false) {
this.m_bodyB.SetAwake(true);
}
this.m_target = target;
}
b2MouseJoint.prototype.GetMaxForce = function () {
return this.m_maxForce;
}
b2MouseJoint.prototype.SetMaxForce = function (maxForce) {
if (maxForce === undefined) maxForce = 0;
this.m_maxForce = maxForce;
}
b2MouseJoint.prototype.GetFrequency = function () {
return this.m_frequencyHz;
}
b2MouseJoint.prototype.SetFrequency = function (hz) {
if (hz === undefined) hz = 0;
this.m_frequencyHz = hz;
}
b2MouseJoint.prototype.GetDampingRatio = function () {
return this.m_dampingRatio;
}
b2MouseJoint.prototype.SetDampingRatio = function (ratio) {
if (ratio === undefined) ratio = 0;
this.m_dampingRatio = ratio;
}
b2MouseJoint.prototype.b2MouseJoint = function (def) {
this.__super.b2Joint.call(this, def);
this.m_target.SetV(def.target);
var tX = this.m_target.x - this.m_bodyB.m_xf.position.x;
var tY = this.m_target.y - this.m_bodyB.m_xf.position.y;
var tMat = this.m_bodyB.m_xf.R;
this.m_localAnchor.x = (tX * tMat.col1.x + tY * tMat.col1.y);
this.m_localAnchor.y = (tX * tMat.col2.x + tY * tMat.col2.y);
this.m_maxForce = def.maxForce;
this.m_impulse.SetZero();
this.m_frequencyHz = def.frequencyHz;
this.m_dampingRatio = def.dampingRatio;
this.m_beta = 0.0;
this.m_gamma = 0.0;
}
b2MouseJoint.prototype.InitVelocityConstraints = function (step) {
var b = this.m_bodyB;
var mass = b.GetMass();
var omega = 2.0 * Math.PI * this.m_frequencyHz;
var d = 2.0 * mass * this.m_dampingRatio * omega;
var k = mass * omega * omega;
this.m_gamma = step.dt * (d + step.dt * k);
this.m_gamma = this.m_gamma != 0 ? 1 / this.m_gamma : 0.0;
this.m_beta = step.dt * k * this.m_gamma;
var tMat;tMat = b.m_xf.R;
var rX = this.m_localAnchor.x - b.m_sweep.localCenter.x;
var rY = this.m_localAnchor.y - b.m_sweep.localCenter.y;
var tX = (tMat.col1.x * rX + tMat.col2.x * rY);rY = (tMat.col1.y * rX + tMat.col2.y * rY);
rX = tX;
var invMass = b.m_invMass;
var invI = b.m_invI;this.K1.col1.x = invMass;
this.K1.col2.x = 0.0;
this.K1.col1.y = 0.0;
this.K1.col2.y = invMass;
this.K2.col1.x = invI * rY * rY;
this.K2.col2.x = (-invI * rX * rY);
this.K2.col1.y = (-invI * rX * rY);
this.K2.col2.y = invI * rX * rX;
this.K.SetM(this.K1);
this.K.AddM(this.K2);
this.K.col1.x += this.m_gamma;
this.K.col2.y += this.m_gamma;
this.K.GetInverse(this.m_mass);
this.m_C.x = b.m_sweep.c.x + rX - this.m_target.x;
this.m_C.y = b.m_sweep.c.y + rY - this.m_target.y;
b.m_angularVelocity *= 0.98;
this.m_impulse.x *= step.dtRatio;
this.m_impulse.y *= step.dtRatio;
b.m_linearVelocity.x += invMass * this.m_impulse.x;
b.m_linearVelocity.y += invMass * this.m_impulse.y;
b.m_angularVelocity += invI * (rX * this.m_impulse.y - rY * this.m_impulse.x);
}
b2MouseJoint.prototype.SolveVelocityConstraints = function (step) {
var b = this.m_bodyB;
var tMat;
var tX = 0;
var tY = 0;
tMat = b.m_xf.R;
var rX = this.m_localAnchor.x - b.m_sweep.localCenter.x;
var rY = this.m_localAnchor.y - b.m_sweep.localCenter.y;
tX = (tMat.col1.x * rX + tMat.col2.x * rY);
rY = (tMat.col1.y * rX + tMat.col2.y * rY);
rX = tX;
var CdotX = b.m_linearVelocity.x + ((-b.m_angularVelocity * rY));
var CdotY = b.m_linearVelocity.y + (b.m_angularVelocity * rX);
tMat = this.m_mass;
tX = CdotX + this.m_beta * this.m_C.x + this.m_gamma * this.m_impulse.x;
tY = CdotY + this.m_beta * this.m_C.y + this.m_gamma * this.m_impulse.y;
var impulseX = (-(tMat.col1.x * tX + tMat.col2.x * tY));
var impulseY = (-(tMat.col1.y * tX + tMat.col2.y * tY));
var oldImpulseX = this.m_impulse.x;
var oldImpulseY = this.m_impulse.y;
this.m_impulse.x += impulseX;
this.m_impulse.y += impulseY;
var maxImpulse = step.dt * this.m_maxForce;
if (this.m_impulse.LengthSquared() > maxImpulse * maxImpulse) {
this.m_impulse.Multiply(maxImpulse / this.m_impulse.Length());
}
impulseX = this.m_impulse.x - oldImpulseX;
impulseY = this.m_impulse.y - oldImpulseY;
b.m_linearVelocity.x += b.m_invMass * impulseX;
b.m_linearVelocity.y += b.m_invMass * impulseY;
b.m_angularVelocity += b.m_invI * (rX * impulseY - rY * impulseX);
}
b2MouseJoint.prototype.SolvePositionConstraints = function (baumgarte) {
if (baumgarte === undefined) baumgarte = 0;
return true;
}
b2MouseJointDef.inherit(Box2D.Dynamics.Joints.b2JointDef);
b2MouseJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
b2MouseJointDef.b2MouseJointDef = function () {
Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
this.target = new b2Vec2();
};
b2MouseJointDef.prototype.b2MouseJointDef = function () {
this.__super.b2JointDef.call(this);
this.type = b2Joint.e_mouseJoint;
this.maxForce = 0.0;
this.frequencyHz = 5.0;
this.dampingRatio = 0.7;
}
b2PrismaticJoint.inherit(Box2D.Dynamics.Joints.b2Joint);
b2PrismaticJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
b2PrismaticJoint.b2PrismaticJoint = function () {
Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
this.m_localAnchor1 = new b2Vec2();
this.m_localAnchor2 = new b2Vec2();
this.m_localXAxis1 = new b2Vec2();
this.m_localYAxis1 = new b2Vec2();
this.m_axis = new b2Vec2();
this.m_perp = new b2Vec2();
this.m_K = new b2Mat33();
this.m_impulse = new b2Vec3();
};
b2PrismaticJoint.prototype.GetAnchorA = function () {
return this.m_bodyA.GetWorldPoint(this.m_localAnchor1);
}
b2PrismaticJoint.prototype.GetAnchorB = function () {
return this.m_bodyB.GetWorldPoint(this.m_localAnchor2);
}
b2PrismaticJoint.prototype.GetReactionForce = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return new b2Vec2(inv_dt * (this.m_impulse.x * this.m_perp.x + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis.x), inv_dt * (this.m_impulse.x * this.m_perp.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis.y));
}
b2PrismaticJoint.prototype.GetReactionTorque = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return inv_dt * this.m_impulse.y;
}
b2PrismaticJoint.prototype.GetJointTranslation = function () {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var tMat;
var p1 = bA.GetWorldPoint(this.m_localAnchor1);
var p2 = bB.GetWorldPoint(this.m_localAnchor2);
var dX = p2.x - p1.x;
var dY = p2.y - p1.y;
var axis = bA.GetWorldVector(this.m_localXAxis1);
var translation = axis.x * dX + axis.y * dY;
return translation;
}
b2PrismaticJoint.prototype.GetJointSpeed = function () {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var tMat;
tMat = bA.m_xf.R;
var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
var tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = bB.m_xf.R;
var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
var p1X = bA.m_sweep.c.x + r1X;
var p1Y = bA.m_sweep.c.y + r1Y;
var p2X = bB.m_sweep.c.x + r2X;
var p2Y = bB.m_sweep.c.y + r2Y;
var dX = p2X - p1X;
var dY = p2Y - p1Y;
var axis = bA.GetWorldVector(this.m_localXAxis1);
var v1 = bA.m_linearVelocity;
var v2 = bB.m_linearVelocity;
var w1 = bA.m_angularVelocity;
var w2 = bB.m_angularVelocity;
var speed = (dX * ((-w1 * axis.y)) + dY * (w1 * axis.x)) + (axis.x * (((v2.x + ((-w2 * r2Y))) - v1.x) - ((-w1 * r1Y))) + axis.y * (((v2.y + (w2 * r2X)) - v1.y) - (w1 * r1X)));
return speed;
}
b2PrismaticJoint.prototype.IsLimitEnabled = function () {
return this.m_enableLimit;
}
b2PrismaticJoint.prototype.EnableLimit = function (flag) {
this.m_bodyA.SetAwake(true);
this.m_bodyB.SetAwake(true);
this.m_enableLimit = flag;
}
b2PrismaticJoint.prototype.GetLowerLimit = function () {
return this.m_lowerTranslation;
}
b2PrismaticJoint.prototype.GetUpperLimit = function () {
return this.m_upperTranslation;
}
b2PrismaticJoint.prototype.SetLimits = function (lower, upper) {
if (lower === undefined) lower = 0;
if (upper === undefined) upper = 0;
this.m_bodyA.SetAwake(true);
this.m_bodyB.SetAwake(true);
this.m_lowerTranslation = lower;
this.m_upperTranslation = upper;
}
b2PrismaticJoint.prototype.IsMotorEnabled = function () {
return this.m_enableMotor;
}
b2PrismaticJoint.prototype.EnableMotor = function (flag) {
this.m_bodyA.SetAwake(true);
this.m_bodyB.SetAwake(true);
this.m_enableMotor = flag;
}
b2PrismaticJoint.prototype.SetMotorSpeed = function (speed) {
if (speed === undefined) speed = 0;
this.m_bodyA.SetAwake(true);
this.m_bodyB.SetAwake(true);
this.m_motorSpeed = speed;
}
b2PrismaticJoint.prototype.GetMotorSpeed = function () {
return this.m_motorSpeed;
}
b2PrismaticJoint.prototype.SetMaxMotorForce = function (force) {
if (force === undefined) force = 0;
this.m_bodyA.SetAwake(true);
this.m_bodyB.SetAwake(true);
this.m_maxMotorForce = force;
}
b2PrismaticJoint.prototype.GetMotorForce = function () {
return this.m_motorImpulse;
}
b2PrismaticJoint.prototype.b2PrismaticJoint = function (def) {
this.__super.b2Joint.call(this, def);
var tMat;
var tX = 0;
var tY = 0;
this.m_localAnchor1.SetV(def.localAnchorA);
this.m_localAnchor2.SetV(def.localAnchorB);
this.m_localXAxis1.SetV(def.localAxisA);
this.m_localYAxis1.x = (-this.m_localXAxis1.y);
this.m_localYAxis1.y = this.m_localXAxis1.x;
this.m_refAngle = def.referenceAngle;
this.m_impulse.SetZero();
this.m_motorMass = 0.0;
this.m_motorImpulse = 0.0;
this.m_lowerTranslation = def.lowerTranslation;
this.m_upperTranslation = def.upperTranslation;
this.m_maxMotorForce = def.maxMotorForce;
this.m_motorSpeed = def.motorSpeed;
this.m_enableLimit = def.enableLimit;
this.m_enableMotor = def.enableMotor;
this.m_limitState = this.e_inactiveLimit;
this.m_axis.SetZero();
this.m_perp.SetZero();
}
b2PrismaticJoint.prototype.InitVelocityConstraints = function (step) {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var tMat;
var tX = 0;
this.m_localCenterA.SetV(bA.GetLocalCenter());
this.m_localCenterB.SetV(bB.GetLocalCenter());
var xf1 = bA.GetTransform();
var xf2 = bB.GetTransform();
tMat = bA.m_xf.R;
var r1X = this.m_localAnchor1.x - this.m_localCenterA.x;
var r1Y = this.m_localAnchor1.y - this.m_localCenterA.y;
tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = bB.m_xf.R;
var r2X = this.m_localAnchor2.x - this.m_localCenterB.x;
var r2Y = this.m_localAnchor2.y - this.m_localCenterB.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
var dX = bB.m_sweep.c.x + r2X - bA.m_sweep.c.x - r1X;
var dY = bB.m_sweep.c.y + r2Y - bA.m_sweep.c.y - r1Y;
this.m_invMassA = bA.m_invMass;
this.m_invMassB = bB.m_invMass;
this.m_invIA = bA.m_invI;
this.m_invIB = bB.m_invI; {
this.m_axis.SetV(b2Math.MulMV(xf1.R, this.m_localXAxis1));
this.m_a1 = (dX + r1X) * this.m_axis.y - (dY + r1Y) * this.m_axis.x;
this.m_a2 = r2X * this.m_axis.y - r2Y * this.m_axis.x;
this.m_motorMass = this.m_invMassA + this.m_invMassB + this.m_invIA * this.m_a1 * this.m_a1 + this.m_invIB * this.m_a2 * this.m_a2;
if (this.m_motorMass > Number.MIN_VALUE) this.m_motorMass = 1.0 / this.m_motorMass;
} {
this.m_perp.SetV(b2Math.MulMV(xf1.R, this.m_localYAxis1));
this.m_s1 = (dX + r1X) * this.m_perp.y - (dY + r1Y) * this.m_perp.x;
this.m_s2 = r2X * this.m_perp.y - r2Y * this.m_perp.x;
var m1 = this.m_invMassA;
var m2 = this.m_invMassB;
var i1 = this.m_invIA;
var i2 = this.m_invIB;
this.m_K.col1.x = m1 + m2 + i1 * this.m_s1 * this.m_s1 + i2 * this.m_s2 * this.m_s2;
this.m_K.col1.y = i1 * this.m_s1 + i2 * this.m_s2;
this.m_K.col1.z = i1 * this.m_s1 * this.m_a1 + i2 * this.m_s2 * this.m_a2;
this.m_K.col2.x = this.m_K.col1.y;
this.m_K.col2.y = i1 + i2;
this.m_K.col2.z = i1 * this.m_a1 + i2 * this.m_a2;
this.m_K.col3.x = this.m_K.col1.z;
this.m_K.col3.y = this.m_K.col2.z;
this.m_K.col3.z = m1 + m2 + i1 * this.m_a1 * this.m_a1 + i2 * this.m_a2 * this.m_a2;
}
if (this.m_enableLimit) {
var jointTransition = this.m_axis.x * dX + this.m_axis.y * dY;
if (b2Math.Abs(this.m_upperTranslation - this.m_lowerTranslation) < 2.0 * b2Settings.b2_linearSlop) {
this.m_limitState = this.e_equalLimits;
}
else if (jointTransition <= this.m_lowerTranslation) {
if (this.m_limitState != this.e_atLowerLimit) {
this.m_limitState = this.e_atLowerLimit;
this.m_impulse.z = 0.0;
}
}
else if (jointTransition >= this.m_upperTranslation) {
if (this.m_limitState != this.e_atUpperLimit) {
this.m_limitState = this.e_atUpperLimit;
this.m_impulse.z = 0.0;
}
}
else {
this.m_limitState = this.e_inactiveLimit;
this.m_impulse.z = 0.0;
}
}
else {
this.m_limitState = this.e_inactiveLimit;
}
if (this.m_enableMotor == false) {
this.m_motorImpulse = 0.0;
}
if (step.warmStarting) {
this.m_impulse.x *= step.dtRatio;
this.m_impulse.y *= step.dtRatio;
this.m_motorImpulse *= step.dtRatio;
var PX = this.m_impulse.x * this.m_perp.x + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis.x;
var PY = this.m_impulse.x * this.m_perp.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis.y;
var L1 = this.m_impulse.x * this.m_s1 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a1;
var L2 = this.m_impulse.x * this.m_s2 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a2;
bA.m_linearVelocity.x -= this.m_invMassA * PX;
bA.m_linearVelocity.y -= this.m_invMassA * PY;
bA.m_angularVelocity -= this.m_invIA * L1;
bB.m_linearVelocity.x += this.m_invMassB * PX;
bB.m_linearVelocity.y += this.m_invMassB * PY;
bB.m_angularVelocity += this.m_invIB * L2;
}
else {
this.m_impulse.SetZero();
this.m_motorImpulse = 0.0;
}
}
b2PrismaticJoint.prototype.SolveVelocityConstraints = function (step) {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var v1 = bA.m_linearVelocity;
var w1 = bA.m_angularVelocity;
var v2 = bB.m_linearVelocity;
var w2 = bB.m_angularVelocity;
var PX = 0;
var PY = 0;
var L1 = 0;
var L2 = 0;
if (this.m_enableMotor && this.m_limitState != this.e_equalLimits) {
var Cdot = this.m_axis.x * (v2.x - v1.x) + this.m_axis.y * (v2.y - v1.y) + this.m_a2 * w2 - this.m_a1 * w1;
var impulse = this.m_motorMass * (this.m_motorSpeed - Cdot);
var oldImpulse = this.m_motorImpulse;
var maxImpulse = step.dt * this.m_maxMotorForce;
this.m_motorImpulse = b2Math.Clamp(this.m_motorImpulse + impulse, (-maxImpulse), maxImpulse);
impulse = this.m_motorImpulse - oldImpulse;
PX = impulse * this.m_axis.x;
PY = impulse * this.m_axis.y;
L1 = impulse * this.m_a1;
L2 = impulse * this.m_a2;
v1.x -= this.m_invMassA * PX;
v1.y -= this.m_invMassA * PY;
w1 -= this.m_invIA * L1;
v2.x += this.m_invMassB * PX;
v2.y += this.m_invMassB * PY;
w2 += this.m_invIB * L2;
}
var Cdot1X = this.m_perp.x * (v2.x - v1.x) + this.m_perp.y * (v2.y - v1.y) + this.m_s2 * w2 - this.m_s1 * w1;
var Cdot1Y = w2 - w1;
if (this.m_enableLimit && this.m_limitState != this.e_inactiveLimit) {
var Cdot2 = this.m_axis.x * (v2.x - v1.x) + this.m_axis.y * (v2.y - v1.y) + this.m_a2 * w2 - this.m_a1 * w1;
var f1 = this.m_impulse.Copy();
var df = this.m_K.Solve33(new b2Vec3(), (-Cdot1X), (-Cdot1Y), (-Cdot2));
this.m_impulse.Add(df);
if (this.m_limitState == this.e_atLowerLimit) {
this.m_impulse.z = b2Math.Max(this.m_impulse.z, 0.0);
}
else if (this.m_limitState == this.e_atUpperLimit) {
this.m_impulse.z = b2Math.Min(this.m_impulse.z, 0.0);
}
var bX = (-Cdot1X) - (this.m_impulse.z - f1.z) * this.m_K.col3.x;
var bY = (-Cdot1Y) - (this.m_impulse.z - f1.z) * this.m_K.col3.y;
var f2r = this.m_K.Solve22(new b2Vec2(), bX, bY);
f2r.x += f1.x;
f2r.y += f1.y;
this.m_impulse.x = f2r.x;
this.m_impulse.y = f2r.y;
df.x = this.m_impulse.x - f1.x;
df.y = this.m_impulse.y - f1.y;
df.z = this.m_impulse.z - f1.z;
PX = df.x * this.m_perp.x + df.z * this.m_axis.x;
PY = df.x * this.m_perp.y + df.z * this.m_axis.y;
L1 = df.x * this.m_s1 + df.y + df.z * this.m_a1;
L2 = df.x * this.m_s2 + df.y + df.z * this.m_a2;
v1.x -= this.m_invMassA * PX;
v1.y -= this.m_invMassA * PY;
w1 -= this.m_invIA * L1;
v2.x += this.m_invMassB * PX;
v2.y += this.m_invMassB * PY;
w2 += this.m_invIB * L2;
}
else {
var df2 = this.m_K.Solve22(new b2Vec2(), (-Cdot1X), (-Cdot1Y));
this.m_impulse.x += df2.x;
this.m_impulse.y += df2.y;
PX = df2.x * this.m_perp.x;
PY = df2.x * this.m_perp.y;
L1 = df2.x * this.m_s1 + df2.y;
L2 = df2.x * this.m_s2 + df2.y;
v1.x -= this.m_invMassA * PX;
v1.y -= this.m_invMassA * PY;
w1 -= this.m_invIA * L1;
v2.x += this.m_invMassB * PX;
v2.y += this.m_invMassB * PY;
w2 += this.m_invIB * L2;
}
bA.m_linearVelocity.SetV(v1);
bA.m_angularVelocity = w1;
bB.m_linearVelocity.SetV(v2);
bB.m_angularVelocity = w2;
}
b2PrismaticJoint.prototype.SolvePositionConstraints = function (baumgarte) {
if (baumgarte === undefined) baumgarte = 0;
var limitC = 0;
var oldLimitImpulse = 0;
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var c1 = bA.m_sweep.c;
var a1 = bA.m_sweep.a;
var c2 = bB.m_sweep.c;
var a2 = bB.m_sweep.a;
var tMat;
var tX = 0;
var m1 = 0;
var m2 = 0;
var i1 = 0;
var i2 = 0;
var linearError = 0.0;
var angularError = 0.0;
var active = false;
var C2 = 0.0;
var R1 = b2Mat22.FromAngle(a1);
var R2 = b2Mat22.FromAngle(a2);
tMat = R1;
var r1X = this.m_localAnchor1.x - this.m_localCenterA.x;
var r1Y = this.m_localAnchor1.y - this.m_localCenterA.y;
tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = R2;
var r2X = this.m_localAnchor2.x - this.m_localCenterB.x;
var r2Y = this.m_localAnchor2.y - this.m_localCenterB.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
var dX = c2.x + r2X - c1.x - r1X;
var dY = c2.y + r2Y - c1.y - r1Y;
if (this.m_enableLimit) {
this.m_axis = b2Math.MulMV(R1, this.m_localXAxis1);
this.m_a1 = (dX + r1X) * this.m_axis.y - (dY + r1Y) * this.m_axis.x;
this.m_a2 = r2X * this.m_axis.y - r2Y * this.m_axis.x;
var translation = this.m_axis.x * dX + this.m_axis.y * dY;
if (b2Math.Abs(this.m_upperTranslation - this.m_lowerTranslation) < 2.0 * b2Settings.b2_linearSlop) {
C2 = b2Math.Clamp(translation, (-b2Settings.b2_maxLinearCorrection), b2Settings.b2_maxLinearCorrection);
linearError = b2Math.Abs(translation);
active = true;
}
else if (translation <= this.m_lowerTranslation) {
C2 = b2Math.Clamp(translation - this.m_lowerTranslation + b2Settings.b2_linearSlop, (-b2Settings.b2_maxLinearCorrection), 0.0);
linearError = this.m_lowerTranslation - translation;
active = true;
}
else if (translation >= this.m_upperTranslation) {
C2 = b2Math.Clamp(translation - this.m_upperTranslation + b2Settings.b2_linearSlop, 0.0, b2Settings.b2_maxLinearCorrection);
linearError = translation - this.m_upperTranslation;
active = true;
}
}
this.m_perp = b2Math.MulMV(R1, this.m_localYAxis1);
this.m_s1 = (dX + r1X) * this.m_perp.y - (dY + r1Y) * this.m_perp.x;
this.m_s2 = r2X * this.m_perp.y - r2Y * this.m_perp.x;
var impulse = new b2Vec3();
var C1X = this.m_perp.x * dX + this.m_perp.y * dY;
var C1Y = a2 - a1 - this.m_refAngle;
linearError = b2Math.Max(linearError, b2Math.Abs(C1X));
angularError = b2Math.Abs(C1Y);
if (active) {
m1 = this.m_invMassA;
m2 = this.m_invMassB;
i1 = this.m_invIA;
i2 = this.m_invIB;
this.m_K.col1.x = m1 + m2 + i1 * this.m_s1 * this.m_s1 + i2 * this.m_s2 * this.m_s2;
this.m_K.col1.y = i1 * this.m_s1 + i2 * this.m_s2;
this.m_K.col1.z = i1 * this.m_s1 * this.m_a1 + i2 * this.m_s2 * this.m_a2;
this.m_K.col2.x = this.m_K.col1.y;
this.m_K.col2.y = i1 + i2;
this.m_K.col2.z = i1 * this.m_a1 + i2 * this.m_a2;
this.m_K.col3.x = this.m_K.col1.z;
this.m_K.col3.y = this.m_K.col2.z;
this.m_K.col3.z = m1 + m2 + i1 * this.m_a1 * this.m_a1 + i2 * this.m_a2 * this.m_a2;
this.m_K.Solve33(impulse, (-C1X), (-C1Y), (-C2));
}
else {
m1 = this.m_invMassA;
m2 = this.m_invMassB;
i1 = this.m_invIA;
i2 = this.m_invIB;
var k11 = m1 + m2 + i1 * this.m_s1 * this.m_s1 + i2 * this.m_s2 * this.m_s2;
var k12 = i1 * this.m_s1 + i2 * this.m_s2;
var k22 = i1 + i2;
this.m_K.col1.Set(k11, k12, 0.0);
this.m_K.col2.Set(k12, k22, 0.0);
var impulse1 = this.m_K.Solve22(new b2Vec2(), (-C1X), (-C1Y));
impulse.x = impulse1.x;
impulse.y = impulse1.y;
impulse.z = 0.0;
}
var PX = impulse.x * this.m_perp.x + impulse.z * this.m_axis.x;
var PY = impulse.x * this.m_perp.y + impulse.z * this.m_axis.y;
var L1 = impulse.x * this.m_s1 + impulse.y + impulse.z * this.m_a1;
var L2 = impulse.x * this.m_s2 + impulse.y + impulse.z * this.m_a2;
c1.x -= this.m_invMassA * PX;
c1.y -= this.m_invMassA * PY;
a1 -= this.m_invIA * L1;
c2.x += this.m_invMassB * PX;
c2.y += this.m_invMassB * PY;
a2 += this.m_invIB * L2;
bA.m_sweep.a = a1;
bB.m_sweep.a = a2;
bA.SynchronizeTransform();
bB.SynchronizeTransform();
return linearError <= b2Settings.b2_linearSlop && angularError <= b2Settings.b2_angularSlop;
}
b2PrismaticJointDef.inherit(Box2D.Dynamics.Joints.b2JointDef);
b2PrismaticJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
b2PrismaticJointDef.b2PrismaticJointDef = function () {
Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
this.localAnchorA = new b2Vec2();
this.localAnchorB = new b2Vec2();
this.localAxisA = new b2Vec2();
};
b2PrismaticJointDef.prototype.b2PrismaticJointDef = function () {
this.__super.b2JointDef.call(this);
this.type = b2Joint.e_prismaticJoint;
this.localAxisA.Set(1.0, 0.0);
this.referenceAngle = 0.0;
this.enableLimit = false;
this.lowerTranslation = 0.0;
this.upperTranslation = 0.0;
this.enableMotor = false;
this.maxMotorForce = 0.0;
this.motorSpeed = 0.0;
}
b2PrismaticJointDef.prototype.Initialize = function (bA, bB, anchor, axis) {
this.bodyA = bA;
this.bodyB = bB;
this.localAnchorA = this.bodyA.GetLocalPoint(anchor);
this.localAnchorB = this.bodyB.GetLocalPoint(anchor);
this.localAxisA = this.bodyA.GetLocalVector(axis);
this.referenceAngle = this.bodyB.GetAngle() - this.bodyA.GetAngle();
}
b2PulleyJoint.inherit(Box2D.Dynamics.Joints.b2Joint);
b2PulleyJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
b2PulleyJoint.b2PulleyJoint = function () {
Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
this.m_groundAnchor1 = new b2Vec2();
this.m_groundAnchor2 = new b2Vec2();
this.m_localAnchor1 = new b2Vec2();
this.m_localAnchor2 = new b2Vec2();
this.m_u1 = new b2Vec2();
this.m_u2 = new b2Vec2();
};
b2PulleyJoint.prototype.GetAnchorA = function () {
return this.m_bodyA.GetWorldPoint(this.m_localAnchor1);
}
b2PulleyJoint.prototype.GetAnchorB = function () {
return this.m_bodyB.GetWorldPoint(this.m_localAnchor2);
}
b2PulleyJoint.prototype.GetReactionForce = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return new b2Vec2(inv_dt * this.m_impulse * this.m_u2.x, inv_dt * this.m_impulse * this.m_u2.y);
}
b2PulleyJoint.prototype.GetReactionTorque = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return 0.0;
}
b2PulleyJoint.prototype.GetGroundAnchorA = function () {
var a = this.m_ground.m_xf.position.Copy();
a.Add(this.m_groundAnchor1);
return a;
}
b2PulleyJoint.prototype.GetGroundAnchorB = function () {
var a = this.m_ground.m_xf.position.Copy();
a.Add(this.m_groundAnchor2);
return a;
}
b2PulleyJoint.prototype.GetLength1 = function () {
var p = this.m_bodyA.GetWorldPoint(this.m_localAnchor1);
var sX = this.m_ground.m_xf.position.x + this.m_groundAnchor1.x;
var sY = this.m_ground.m_xf.position.y + this.m_groundAnchor1.y;
var dX = p.x - sX;
var dY = p.y - sY;
return Math.sqrt(dX * dX + dY * dY);
}
b2PulleyJoint.prototype.GetLength2 = function () {
var p = this.m_bodyB.GetWorldPoint(this.m_localAnchor2);
var sX = this.m_ground.m_xf.position.x + this.m_groundAnchor2.x;
var sY = this.m_ground.m_xf.position.y + this.m_groundAnchor2.y;
var dX = p.x - sX;
var dY = p.y - sY;
return Math.sqrt(dX * dX + dY * dY);
}
b2PulleyJoint.prototype.GetRatio = function () {
return this.m_ratio;
}
b2PulleyJoint.prototype.b2PulleyJoint = function (def) {
this.__super.b2Joint.call(this, def);
var tMat;
var tX = 0;
var tY = 0;
this.m_ground = this.m_bodyA.m_world.m_groundBody;
this.m_groundAnchor1.x = def.groundAnchorA.x - this.m_ground.m_xf.position.x;
this.m_groundAnchor1.y = def.groundAnchorA.y - this.m_ground.m_xf.position.y;
this.m_groundAnchor2.x = def.groundAnchorB.x - this.m_ground.m_xf.position.x;
this.m_groundAnchor2.y = def.groundAnchorB.y - this.m_ground.m_xf.position.y;
this.m_localAnchor1.SetV(def.localAnchorA);
this.m_localAnchor2.SetV(def.localAnchorB);
this.m_ratio = def.ratio;
this.m_constant = def.lengthA + this.m_ratio * def.lengthB;
this.m_maxLength1 = b2Math.Min(def.maxLengthA, this.m_constant - this.m_ratio * b2PulleyJoint.b2_minPulleyLength);
this.m_maxLength2 = b2Math.Min(def.maxLengthB, (this.m_constant - b2PulleyJoint.b2_minPulleyLength) / this.m_ratio);
this.m_impulse = 0.0;
this.m_limitImpulse1 = 0.0;
this.m_limitImpulse2 = 0.0;
}
b2PulleyJoint.prototype.InitVelocityConstraints = function (step) {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var tMat;
tMat = bA.m_xf.R;
var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
var tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = bB.m_xf.R;
var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
var p1X = bA.m_sweep.c.x + r1X;
var p1Y = bA.m_sweep.c.y + r1Y;
var p2X = bB.m_sweep.c.x + r2X;
var p2Y = bB.m_sweep.c.y + r2Y;
var s1X = this.m_ground.m_xf.position.x + this.m_groundAnchor1.x;
var s1Y = this.m_ground.m_xf.position.y + this.m_groundAnchor1.y;
var s2X = this.m_ground.m_xf.position.x + this.m_groundAnchor2.x;
var s2Y = this.m_ground.m_xf.position.y + this.m_groundAnchor2.y;
this.m_u1.Set(p1X - s1X, p1Y - s1Y);
this.m_u2.Set(p2X - s2X, p2Y - s2Y);
var length1 = this.m_u1.Length();
var length2 = this.m_u2.Length();
if (length1 > b2Settings.b2_linearSlop) {
this.m_u1.Multiply(1.0 / length1);
}
else {
this.m_u1.SetZero();
}
if (length2 > b2Settings.b2_linearSlop) {
this.m_u2.Multiply(1.0 / length2);
}
else {
this.m_u2.SetZero();
}
var C = this.m_constant - length1 - this.m_ratio * length2;
if (C > 0.0) {
this.m_state = this.e_inactiveLimit;
this.m_impulse = 0.0;
}
else {
this.m_state = this.e_atUpperLimit;
}
if (length1 < this.m_maxLength1) {
this.m_limitState1 = this.e_inactiveLimit;
this.m_limitImpulse1 = 0.0;
}
else {
this.m_limitState1 = this.e_atUpperLimit;
}
if (length2 < this.m_maxLength2) {
this.m_limitState2 = this.e_inactiveLimit;
this.m_limitImpulse2 = 0.0;
}
else {
this.m_limitState2 = this.e_atUpperLimit;
}
var cr1u1 = r1X * this.m_u1.y - r1Y * this.m_u1.x;
var cr2u2 = r2X * this.m_u2.y - r2Y * this.m_u2.x;
this.m_limitMass1 = bA.m_invMass + bA.m_invI * cr1u1 * cr1u1;
this.m_limitMass2 = bB.m_invMass + bB.m_invI * cr2u2 * cr2u2;
this.m_pulleyMass = this.m_limitMass1 + this.m_ratio * this.m_ratio * this.m_limitMass2;
this.m_limitMass1 = 1.0 / this.m_limitMass1;
this.m_limitMass2 = 1.0 / this.m_limitMass2;
this.m_pulleyMass = 1.0 / this.m_pulleyMass;
if (step.warmStarting) {
this.m_impulse *= step.dtRatio;
this.m_limitImpulse1 *= step.dtRatio;
this.m_limitImpulse2 *= step.dtRatio;
var P1X = ((-this.m_impulse) - this.m_limitImpulse1) * this.m_u1.x;
var P1Y = ((-this.m_impulse) - this.m_limitImpulse1) * this.m_u1.y;
var P2X = ((-this.m_ratio * this.m_impulse) - this.m_limitImpulse2) * this.m_u2.x;
var P2Y = ((-this.m_ratio * this.m_impulse) - this.m_limitImpulse2) * this.m_u2.y;
bA.m_linearVelocity.x += bA.m_invMass * P1X;
bA.m_linearVelocity.y += bA.m_invMass * P1Y;
bA.m_angularVelocity += bA.m_invI * (r1X * P1Y - r1Y * P1X);
bB.m_linearVelocity.x += bB.m_invMass * P2X;
bB.m_linearVelocity.y += bB.m_invMass * P2Y;
bB.m_angularVelocity += bB.m_invI * (r2X * P2Y - r2Y * P2X);
}
else {
this.m_impulse = 0.0;
this.m_limitImpulse1 = 0.0;
this.m_limitImpulse2 = 0.0;
}
}
b2PulleyJoint.prototype.SolveVelocityConstraints = function (step) {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var tMat;
tMat = bA.m_xf.R;
var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
var tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = bB.m_xf.R;
var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
var v1X = 0;
var v1Y = 0;
var v2X = 0;
var v2Y = 0;
var P1X = 0;
var P1Y = 0;
var P2X = 0;
var P2Y = 0;
var Cdot = 0;
var impulse = 0;
var oldImpulse = 0;
if (this.m_state == this.e_atUpperLimit) {
v1X = bA.m_linearVelocity.x + ((-bA.m_angularVelocity * r1Y));
v1Y = bA.m_linearVelocity.y + (bA.m_angularVelocity * r1X);
v2X = bB.m_linearVelocity.x + ((-bB.m_angularVelocity * r2Y));
v2Y = bB.m_linearVelocity.y + (bB.m_angularVelocity * r2X);
Cdot = (-(this.m_u1.x * v1X + this.m_u1.y * v1Y)) - this.m_ratio * (this.m_u2.x * v2X + this.m_u2.y * v2Y);
impulse = this.m_pulleyMass * ((-Cdot));
oldImpulse = this.m_impulse;
this.m_impulse = b2Math.Max(0.0, this.m_impulse + impulse);
impulse = this.m_impulse - oldImpulse;
P1X = (-impulse * this.m_u1.x);
P1Y = (-impulse * this.m_u1.y);
P2X = (-this.m_ratio * impulse * this.m_u2.x);
P2Y = (-this.m_ratio * impulse * this.m_u2.y);
bA.m_linearVelocity.x += bA.m_invMass * P1X;
bA.m_linearVelocity.y += bA.m_invMass * P1Y;
bA.m_angularVelocity += bA.m_invI * (r1X * P1Y - r1Y * P1X);
bB.m_linearVelocity.x += bB.m_invMass * P2X;
bB.m_linearVelocity.y += bB.m_invMass * P2Y;
bB.m_angularVelocity += bB.m_invI * (r2X * P2Y - r2Y * P2X);
}
if (this.m_limitState1 == this.e_atUpperLimit) {
v1X = bA.m_linearVelocity.x + ((-bA.m_angularVelocity * r1Y));
v1Y = bA.m_linearVelocity.y + (bA.m_angularVelocity * r1X);
Cdot = (-(this.m_u1.x * v1X + this.m_u1.y * v1Y));
impulse = (-this.m_limitMass1 * Cdot);
oldImpulse = this.m_limitImpulse1;
this.m_limitImpulse1 = b2Math.Max(0.0, this.m_limitImpulse1 + impulse);
impulse = this.m_limitImpulse1 - oldImpulse;
P1X = (-impulse * this.m_u1.x);
P1Y = (-impulse * this.m_u1.y);
bA.m_linearVelocity.x += bA.m_invMass * P1X;
bA.m_linearVelocity.y += bA.m_invMass * P1Y;
bA.m_angularVelocity += bA.m_invI * (r1X * P1Y - r1Y * P1X);
}
if (this.m_limitState2 == this.e_atUpperLimit) {
v2X = bB.m_linearVelocity.x + ((-bB.m_angularVelocity * r2Y));
v2Y = bB.m_linearVelocity.y + (bB.m_angularVelocity * r2X);
Cdot = (-(this.m_u2.x * v2X + this.m_u2.y * v2Y));
impulse = (-this.m_limitMass2 * Cdot);
oldImpulse = this.m_limitImpulse2;
this.m_limitImpulse2 = b2Math.Max(0.0, this.m_limitImpulse2 + impulse);
impulse = this.m_limitImpulse2 - oldImpulse;
P2X = (-impulse * this.m_u2.x);
P2Y = (-impulse * this.m_u2.y);
bB.m_linearVelocity.x += bB.m_invMass * P2X;
bB.m_linearVelocity.y += bB.m_invMass * P2Y;
bB.m_angularVelocity += bB.m_invI * (r2X * P2Y - r2Y * P2X);
}
}
b2PulleyJoint.prototype.SolvePositionConstraints = function (baumgarte) {
if (baumgarte === undefined) baumgarte = 0;
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var tMat;
var s1X = this.m_ground.m_xf.position.x + this.m_groundAnchor1.x;
var s1Y = this.m_ground.m_xf.position.y + this.m_groundAnchor1.y;
var s2X = this.m_ground.m_xf.position.x + this.m_groundAnchor2.x;
var s2Y = this.m_ground.m_xf.position.y + this.m_groundAnchor2.y;
var r1X = 0;
var r1Y = 0;
var r2X = 0;
var r2Y = 0;
var p1X = 0;
var p1Y = 0;
var p2X = 0;
var p2Y = 0;
var length1 = 0;
var length2 = 0;
var C = 0;
var impulse = 0;
var oldImpulse = 0;
var oldLimitPositionImpulse = 0;
var tX = 0;
var linearError = 0.0;
if (this.m_state == this.e_atUpperLimit) {
tMat = bA.m_xf.R;
r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = bB.m_xf.R;
r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
p1X = bA.m_sweep.c.x + r1X;
p1Y = bA.m_sweep.c.y + r1Y;
p2X = bB.m_sweep.c.x + r2X;
p2Y = bB.m_sweep.c.y + r2Y;
this.m_u1.Set(p1X - s1X, p1Y - s1Y);
this.m_u2.Set(p2X - s2X, p2Y - s2Y);
length1 = this.m_u1.Length();
length2 = this.m_u2.Length();
if (length1 > b2Settings.b2_linearSlop) {
this.m_u1.Multiply(1.0 / length1);
}
else {
this.m_u1.SetZero();
}
if (length2 > b2Settings.b2_linearSlop) {
this.m_u2.Multiply(1.0 / length2);
}
else {
this.m_u2.SetZero();
}
C = this.m_constant - length1 - this.m_ratio * length2;
linearError = b2Math.Max(linearError, (-C));
C = b2Math.Clamp(C + b2Settings.b2_linearSlop, (-b2Settings.b2_maxLinearCorrection), 0.0);
impulse = (-this.m_pulleyMass * C);
p1X = (-impulse * this.m_u1.x);
p1Y = (-impulse * this.m_u1.y);
p2X = (-this.m_ratio * impulse * this.m_u2.x);
p2Y = (-this.m_ratio * impulse * this.m_u2.y);
bA.m_sweep.c.x += bA.m_invMass * p1X;
bA.m_sweep.c.y += bA.m_invMass * p1Y;
bA.m_sweep.a += bA.m_invI * (r1X * p1Y - r1Y * p1X);
bB.m_sweep.c.x += bB.m_invMass * p2X;
bB.m_sweep.c.y += bB.m_invMass * p2Y;
bB.m_sweep.a += bB.m_invI * (r2X * p2Y - r2Y * p2X);
bA.SynchronizeTransform();
bB.SynchronizeTransform();
}
if (this.m_limitState1 == this.e_atUpperLimit) {
tMat = bA.m_xf.R;
r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
p1X = bA.m_sweep.c.x + r1X;
p1Y = bA.m_sweep.c.y + r1Y;
this.m_u1.Set(p1X - s1X, p1Y - s1Y);
length1 = this.m_u1.Length();
if (length1 > b2Settings.b2_linearSlop) {
this.m_u1.x *= 1.0 / length1;
this.m_u1.y *= 1.0 / length1;
}
else {
this.m_u1.SetZero();
}
C = this.m_maxLength1 - length1;
linearError = b2Math.Max(linearError, (-C));
C = b2Math.Clamp(C + b2Settings.b2_linearSlop, (-b2Settings.b2_maxLinearCorrection), 0.0);
impulse = (-this.m_limitMass1 * C);
p1X = (-impulse * this.m_u1.x);
p1Y = (-impulse * this.m_u1.y);
bA.m_sweep.c.x += bA.m_invMass * p1X;
bA.m_sweep.c.y += bA.m_invMass * p1Y;
bA.m_sweep.a += bA.m_invI * (r1X * p1Y - r1Y * p1X);
bA.SynchronizeTransform();
}
if (this.m_limitState2 == this.e_atUpperLimit) {
tMat = bB.m_xf.R;
r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
p2X = bB.m_sweep.c.x + r2X;
p2Y = bB.m_sweep.c.y + r2Y;
this.m_u2.Set(p2X - s2X, p2Y - s2Y);
length2 = this.m_u2.Length();
if (length2 > b2Settings.b2_linearSlop) {
this.m_u2.x *= 1.0 / length2;
this.m_u2.y *= 1.0 / length2;
}
else {
this.m_u2.SetZero();
}
C = this.m_maxLength2 - length2;
linearError = b2Math.Max(linearError, (-C));
C = b2Math.Clamp(C + b2Settings.b2_linearSlop, (-b2Settings.b2_maxLinearCorrection), 0.0);
impulse = (-this.m_limitMass2 * C);
p2X = (-impulse * this.m_u2.x);
p2Y = (-impulse * this.m_u2.y);
bB.m_sweep.c.x += bB.m_invMass * p2X;
bB.m_sweep.c.y += bB.m_invMass * p2Y;
bB.m_sweep.a += bB.m_invI * (r2X * p2Y - r2Y * p2X);
bB.SynchronizeTransform();
}
return linearError < b2Settings.b2_linearSlop;
}
_A2J_postDefs.push(function () {
Box2D.Dynamics.Joints.b2PulleyJoint.b2_minPulleyLength = 2.0;
Box2D.Dynamics.Joints.b2PulleyJoint.prototype.b2_minPulleyLength = Box2D.Dynamics.Joints.b2PulleyJoint.b2_minPulleyLength;
});
b2PulleyJointDef.inherit(Box2D.Dynamics.Joints.b2JointDef);
b2PulleyJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
b2PulleyJointDef.b2PulleyJointDef = function () {
Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
this.groundAnchorA = new b2Vec2();
this.groundAnchorB = new b2Vec2();
this.localAnchorA = new b2Vec2();
this.localAnchorB = new b2Vec2();
};
b2PulleyJointDef.prototype.b2PulleyJointDef = function () {
this.__super.b2JointDef.call(this);
this.type = b2Joint.e_pulleyJoint;
this.groundAnchorA.Set((-1.0), 1.0);
this.groundAnchorB.Set(1.0, 1.0);
this.localAnchorA.Set((-1.0), 0.0);
this.localAnchorB.Set(1.0, 0.0);
this.lengthA = 0.0;
this.maxLengthA = 0.0;
this.lengthB = 0.0;
this.maxLengthB = 0.0;
this.ratio = 1.0;
this.collideConnected = true;
}
b2PulleyJointDef.prototype.Initialize = function (bA, bB, gaA, gaB, anchorA, anchorB, r) {
if (r === undefined) r = 0;
this.bodyA = bA;
this.bodyB = bB;
this.groundAnchorA.SetV(gaA);
this.groundAnchorB.SetV(gaB);
this.localAnchorA = this.bodyA.GetLocalPoint(anchorA);
this.localAnchorB = this.bodyB.GetLocalPoint(anchorB);
var d1X = anchorA.x - gaA.x;
var d1Y = anchorA.y - gaA.y;
this.lengthA = Math.sqrt(d1X * d1X + d1Y * d1Y);
var d2X = anchorB.x - gaB.x;
var d2Y = anchorB.y - gaB.y;
this.lengthB = Math.sqrt(d2X * d2X + d2Y * d2Y);
this.ratio = r;
var C = this.lengthA + this.ratio * this.lengthB;
this.maxLengthA = C - this.ratio * b2PulleyJoint.b2_minPulleyLength;
this.maxLengthB = (C - b2PulleyJoint.b2_minPulleyLength) / this.ratio;
}
b2RevoluteJoint.inherit(Box2D.Dynamics.Joints.b2Joint);
b2RevoluteJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
b2RevoluteJoint.b2RevoluteJoint = function () {
Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
this.K = new b2Mat22();
this.K1 = new b2Mat22();
this.K2 = new b2Mat22();
this.K3 = new b2Mat22();
this.impulse3 = new b2Vec3();
this.impulse2 = new b2Vec2();
this.reduced = new b2Vec2();
this.m_localAnchor1 = new b2Vec2();
this.m_localAnchor2 = new b2Vec2();
this.m_impulse = new b2Vec3();
this.m_mass = new b2Mat33();
};
b2RevoluteJoint.prototype.GetAnchorA = function () {
return this.m_bodyA.GetWorldPoint(this.m_localAnchor1);
}
b2RevoluteJoint.prototype.GetAnchorB = function () {
return this.m_bodyB.GetWorldPoint(this.m_localAnchor2);
}
b2RevoluteJoint.prototype.GetReactionForce = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return new b2Vec2(inv_dt * this.m_impulse.x, inv_dt * this.m_impulse.y);
}
b2RevoluteJoint.prototype.GetReactionTorque = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return inv_dt * this.m_impulse.z;
}
b2RevoluteJoint.prototype.GetJointAngle = function () {
return this.m_bodyB.m_sweep.a - this.m_bodyA.m_sweep.a - this.m_referenceAngle;
}
b2RevoluteJoint.prototype.GetJointSpeed = function () {
return this.m_bodyB.m_angularVelocity - this.m_bodyA.m_angularVelocity;
}
b2RevoluteJoint.prototype.IsLimitEnabled = function () {
return this.m_enableLimit;
}
b2RevoluteJoint.prototype.EnableLimit = function (flag) {
this.m_enableLimit = flag;
}
b2RevoluteJoint.prototype.GetLowerLimit = function () {
return this.m_lowerAngle;
}
b2RevoluteJoint.prototype.GetUpperLimit = function () {
return this.m_upperAngle;
}
b2RevoluteJoint.prototype.SetLimits = function (lower, upper) {
if (lower === undefined) lower = 0;
if (upper === undefined) upper = 0;
this.m_lowerAngle = lower;
this.m_upperAngle = upper;
}
b2RevoluteJoint.prototype.IsMotorEnabled = function () {
this.m_bodyA.SetAwake(true);
this.m_bodyB.SetAwake(true);
return this.m_enableMotor;
}
b2RevoluteJoint.prototype.EnableMotor = function (flag) {
this.m_enableMotor = flag;
}
b2RevoluteJoint.prototype.SetMotorSpeed = function (speed) {
if (speed === undefined) speed = 0;
this.m_bodyA.SetAwake(true);
this.m_bodyB.SetAwake(true);
this.m_motorSpeed = speed;
}
b2RevoluteJoint.prototype.GetMotorSpeed = function () {
return this.m_motorSpeed;
}
b2RevoluteJoint.prototype.SetMaxMotorTorque = function (torque) {
if (torque === undefined) torque = 0;
this.m_maxMotorTorque = torque;
}
b2RevoluteJoint.prototype.GetMotorTorque = function () {
return this.m_maxMotorTorque;
}
b2RevoluteJoint.prototype.b2RevoluteJoint = function (def) {
this.__super.b2Joint.call(this, def);
this.m_localAnchor1.SetV(def.localAnchorA);
this.m_localAnchor2.SetV(def.localAnchorB);
this.m_referenceAngle = def.referenceAngle;
this.m_impulse.SetZero();
this.m_motorImpulse = 0.0;
this.m_lowerAngle = def.lowerAngle;
this.m_upperAngle = def.upperAngle;
this.m_maxMotorTorque = def.maxMotorTorque;
this.m_motorSpeed = def.motorSpeed;
this.m_enableLimit = def.enableLimit;
this.m_enableMotor = def.enableMotor;
this.m_limitState = this.e_inactiveLimit;
}
b2RevoluteJoint.prototype.InitVelocityConstraints = function (step) {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var tMat;
var tX = 0;
if (this.m_enableMotor || this.m_enableLimit) {}
tMat = bA.m_xf.R;
var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = bB.m_xf.R;
var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
var m1 = bA.m_invMass;
var m2 = bB.m_invMass;
var i1 = bA.m_invI;
var i2 = bB.m_invI;
this.m_mass.col1.x = m1 + m2 + r1Y * r1Y * i1 + r2Y * r2Y * i2;
this.m_mass.col2.x = (-r1Y * r1X * i1) - r2Y * r2X * i2;
this.m_mass.col3.x = (-r1Y * i1) - r2Y * i2;
this.m_mass.col1.y = this.m_mass.col2.x;
this.m_mass.col2.y = m1 + m2 + r1X * r1X * i1 + r2X * r2X * i2;
this.m_mass.col3.y = r1X * i1 + r2X * i2;
this.m_mass.col1.z = this.m_mass.col3.x;
this.m_mass.col2.z = this.m_mass.col3.y;
this.m_mass.col3.z = i1 + i2;
this.m_motorMass = 1.0 / (i1 + i2);
if (this.m_enableMotor == false) {
this.m_motorImpulse = 0.0;
}
if (this.m_enableLimit) {
var jointAngle = bB.m_sweep.a - bA.m_sweep.a - this.m_referenceAngle;
if (b2Math.Abs(this.m_upperAngle - this.m_lowerAngle) < 2.0 * b2Settings.b2_angularSlop) {
this.m_limitState = this.e_equalLimits;
}
else if (jointAngle <= this.m_lowerAngle) {
if (this.m_limitState != this.e_atLowerLimit) {
this.m_impulse.z = 0.0;
}
this.m_limitState = this.e_atLowerLimit;
}
else if (jointAngle >= this.m_upperAngle) {
if (this.m_limitState != this.e_atUpperLimit) {
this.m_impulse.z = 0.0;
}
this.m_limitState = this.e_atUpperLimit;
}
else {
this.m_limitState = this.e_inactiveLimit;
this.m_impulse.z = 0.0;
}
}
else {
this.m_limitState = this.e_inactiveLimit;
}
if (step.warmStarting) {
this.m_impulse.x *= step.dtRatio;
this.m_impulse.y *= step.dtRatio;
this.m_motorImpulse *= step.dtRatio;
var PX = this.m_impulse.x;
var PY = this.m_impulse.y;
bA.m_linearVelocity.x -= m1 * PX;
bA.m_linearVelocity.y -= m1 * PY;
bA.m_angularVelocity -= i1 * ((r1X * PY - r1Y * PX) + this.m_motorImpulse + this.m_impulse.z);
bB.m_linearVelocity.x += m2 * PX;
bB.m_linearVelocity.y += m2 * PY;
bB.m_angularVelocity += i2 * ((r2X * PY - r2Y * PX) + this.m_motorImpulse + this.m_impulse.z);
}
else {
this.m_impulse.SetZero();
this.m_motorImpulse = 0.0;
}
}
b2RevoluteJoint.prototype.SolveVelocityConstraints = function (step) {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var tMat;
var tX = 0;
var newImpulse = 0;
var r1X = 0;
var r1Y = 0;
var r2X = 0;
var r2Y = 0;
var v1 = bA.m_linearVelocity;
var w1 = bA.m_angularVelocity;
var v2 = bB.m_linearVelocity;
var w2 = bB.m_angularVelocity;
var m1 = bA.m_invMass;
var m2 = bB.m_invMass;
var i1 = bA.m_invI;
var i2 = bB.m_invI;
if (this.m_enableMotor && this.m_limitState != this.e_equalLimits) {
var Cdot = w2 - w1 - this.m_motorSpeed;
var impulse = this.m_motorMass * ((-Cdot));
var oldImpulse = this.m_motorImpulse;
var maxImpulse = step.dt * this.m_maxMotorTorque;
this.m_motorImpulse = b2Math.Clamp(this.m_motorImpulse + impulse, (-maxImpulse), maxImpulse);
impulse = this.m_motorImpulse - oldImpulse;
w1 -= i1 * impulse;
w2 += i2 * impulse;
}
if (this.m_enableLimit && this.m_limitState != this.e_inactiveLimit) {
tMat = bA.m_xf.R;
r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = bB.m_xf.R;
r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
var Cdot1X = v2.x + ((-w2 * r2Y)) - v1.x - ((-w1 * r1Y));
var Cdot1Y = v2.y + (w2 * r2X) - v1.y - (w1 * r1X);
var Cdot2 = w2 - w1;
this.m_mass.Solve33(this.impulse3, (-Cdot1X), (-Cdot1Y), (-Cdot2));
if (this.m_limitState == this.e_equalLimits) {
this.m_impulse.Add(this.impulse3);
}
else if (this.m_limitState == this.e_atLowerLimit) {
newImpulse = this.m_impulse.z + this.impulse3.z;
if (newImpulse < 0.0) {
this.m_mass.Solve22(this.reduced, (-Cdot1X), (-Cdot1Y));
this.impulse3.x = this.reduced.x;
this.impulse3.y = this.reduced.y;
this.impulse3.z = (-this.m_impulse.z);
this.m_impulse.x += this.reduced.x;
this.m_impulse.y += this.reduced.y;
this.m_impulse.z = 0.0;
}
}
else if (this.m_limitState == this.e_atUpperLimit) {
newImpulse = this.m_impulse.z + this.impulse3.z;
if (newImpulse > 0.0) {
this.m_mass.Solve22(this.reduced, (-Cdot1X), (-Cdot1Y));
this.impulse3.x = this.reduced.x;
this.impulse3.y = this.reduced.y;
this.impulse3.z = (-this.m_impulse.z);
this.m_impulse.x += this.reduced.x;
this.m_impulse.y += this.reduced.y;
this.m_impulse.z = 0.0;
}
}
v1.x -= m1 * this.impulse3.x;
v1.y -= m1 * this.impulse3.y;
w1 -= i1 * (r1X * this.impulse3.y - r1Y * this.impulse3.x + this.impulse3.z);
v2.x += m2 * this.impulse3.x;
v2.y += m2 * this.impulse3.y;
w2 += i2 * (r2X * this.impulse3.y - r2Y * this.impulse3.x + this.impulse3.z);
}
else {
tMat = bA.m_xf.R;
r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = bB.m_xf.R;
r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
var CdotX = v2.x + ((-w2 * r2Y)) - v1.x - ((-w1 * r1Y));
var CdotY = v2.y + (w2 * r2X) - v1.y - (w1 * r1X);
this.m_mass.Solve22(this.impulse2, (-CdotX), (-CdotY));
this.m_impulse.x += this.impulse2.x;
this.m_impulse.y += this.impulse2.y;
v1.x -= m1 * this.impulse2.x;
v1.y -= m1 * this.impulse2.y;
w1 -= i1 * (r1X * this.impulse2.y - r1Y * this.impulse2.x);
v2.x += m2 * this.impulse2.x;
v2.y += m2 * this.impulse2.y;
w2 += i2 * (r2X * this.impulse2.y - r2Y * this.impulse2.x);
}
bA.m_linearVelocity.SetV(v1);
bA.m_angularVelocity = w1;
bB.m_linearVelocity.SetV(v2);
bB.m_angularVelocity = w2;
}
b2RevoluteJoint.prototype.SolvePositionConstraints = function (baumgarte) {
if (baumgarte === undefined) baumgarte = 0;
var oldLimitImpulse = 0;
var C = 0;
var tMat;
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var angularError = 0.0;
var positionError = 0.0;
var tX = 0;
var impulseX = 0;
var impulseY = 0;
if (this.m_enableLimit && this.m_limitState != this.e_inactiveLimit) {
var angle = bB.m_sweep.a - bA.m_sweep.a - this.m_referenceAngle;
var limitImpulse = 0.0;
if (this.m_limitState == this.e_equalLimits) {
C = b2Math.Clamp(angle - this.m_lowerAngle, (-b2Settings.b2_maxAngularCorrection), b2Settings.b2_maxAngularCorrection);
limitImpulse = (-this.m_motorMass * C);
angularError = b2Math.Abs(C);
}
else if (this.m_limitState == this.e_atLowerLimit) {
C = angle - this.m_lowerAngle;
angularError = (-C);
C = b2Math.Clamp(C + b2Settings.b2_angularSlop, (-b2Settings.b2_maxAngularCorrection), 0.0);
limitImpulse = (-this.m_motorMass * C);
}
else if (this.m_limitState == this.e_atUpperLimit) {
C = angle - this.m_upperAngle;
angularError = C;
C = b2Math.Clamp(C - b2Settings.b2_angularSlop, 0.0, b2Settings.b2_maxAngularCorrection);
limitImpulse = (-this.m_motorMass * C);
}
bA.m_sweep.a -= bA.m_invI * limitImpulse;
bB.m_sweep.a += bB.m_invI * limitImpulse;
bA.SynchronizeTransform();
bB.SynchronizeTransform();
} {
tMat = bA.m_xf.R;
var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
r1X = tX;
tMat = bB.m_xf.R;
var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
r2X = tX;
var CX = bB.m_sweep.c.x + r2X - bA.m_sweep.c.x - r1X;
var CY = bB.m_sweep.c.y + r2Y - bA.m_sweep.c.y - r1Y;
var CLengthSquared = CX * CX + CY * CY;
var CLength = Math.sqrt(CLengthSquared);
positionError = CLength;
var invMass1 = bA.m_invMass;
var invMass2 = bB.m_invMass;
var invI1 = bA.m_invI;
var invI2 = bB.m_invI;
var k_allowedStretch = 10.0 * b2Settings.b2_linearSlop;
if (CLengthSquared > k_allowedStretch * k_allowedStretch) {
var uX = CX / CLength;
var uY = CY / CLength;
var k = invMass1 + invMass2;
var m = 1.0 / k;
impulseX = m * ((-CX));
impulseY = m * ((-CY));
var k_beta = 0.5;
bA.m_sweep.c.x -= k_beta * invMass1 * impulseX;
bA.m_sweep.c.y -= k_beta * invMass1 * impulseY;
bB.m_sweep.c.x += k_beta * invMass2 * impulseX;
bB.m_sweep.c.y += k_beta * invMass2 * impulseY;
CX = bB.m_sweep.c.x + r2X - bA.m_sweep.c.x - r1X;
CY = bB.m_sweep.c.y + r2Y - bA.m_sweep.c.y - r1Y;
}
this.K1.col1.x = invMass1 + invMass2;
this.K1.col2.x = 0.0;
this.K1.col1.y = 0.0;
this.K1.col2.y = invMass1 + invMass2;
this.K2.col1.x = invI1 * r1Y * r1Y;
this.K2.col2.x = (-invI1 * r1X * r1Y);
this.K2.col1.y = (-invI1 * r1X * r1Y);
this.K2.col2.y = invI1 * r1X * r1X;
this.K3.col1.x = invI2 * r2Y * r2Y;
this.K3.col2.x = (-invI2 * r2X * r2Y);
this.K3.col1.y = (-invI2 * r2X * r2Y);
this.K3.col2.y = invI2 * r2X * r2X;
this.K.SetM(this.K1);
this.K.AddM(this.K2);
this.K.AddM(this.K3);
this.K.Solve(b2RevoluteJoint.tImpulse, (-CX), (-CY));
impulseX = b2RevoluteJoint.tImpulse.x;
impulseY = b2RevoluteJoint.tImpulse.y;
bA.m_sweep.c.x -= bA.m_invMass * impulseX;
bA.m_sweep.c.y -= bA.m_invMass * impulseY;
bA.m_sweep.a -= bA.m_invI * (r1X * impulseY - r1Y * impulseX);
bB.m_sweep.c.x += bB.m_invMass * impulseX;
bB.m_sweep.c.y += bB.m_invMass * impulseY;
bB.m_sweep.a += bB.m_invI * (r2X * impulseY - r2Y * impulseX);
bA.SynchronizeTransform();
bB.SynchronizeTransform();
}
return positionError <= b2Settings.b2_linearSlop && angularError <= b2Settings.b2_angularSlop;
}
_A2J_postDefs.push(function () {
Box2D.Dynamics.Joints.b2RevoluteJoint.tImpulse = new b2Vec2();
Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.tImpulse = Box2D.Dynamics.Joints.b2RevoluteJoint.tImpulse;
});
b2RevoluteJointDef.inherit(Box2D.Dynamics.Joints.b2JointDef);
b2RevoluteJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
b2RevoluteJointDef.b2RevoluteJointDef = function () {
Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
this.localAnchorA = new b2Vec2();
this.localAnchorB = new b2Vec2();
};
b2RevoluteJointDef.prototype.b2RevoluteJointDef = function () {
this.__super.b2JointDef.call(this);
this.type = b2Joint.e_revoluteJoint;
this.localAnchorA.Set(0.0, 0.0);
this.localAnchorB.Set(0.0, 0.0);
this.referenceAngle = 0.0;
this.lowerAngle = 0.0;
this.upperAngle = 0.0;
this.maxMotorTorque = 0.0;
this.motorSpeed = 0.0;
this.enableLimit = false;
this.enableMotor = false;
}
b2RevoluteJointDef.prototype.Initialize = function (bA, bB, anchor) {
this.bodyA = bA;
this.bodyB = bB;
this.localAnchorA = this.bodyA.GetLocalPoint(anchor);
this.localAnchorB = this.bodyB.GetLocalPoint(anchor);
this.referenceAngle = this.bodyB.GetAngle() - this.bodyA.GetAngle();
}
b2WeldJoint.inherit(Box2D.Dynamics.Joints.b2Joint);
b2WeldJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
b2WeldJoint.b2WeldJoint = function () {
Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
this.m_localAnchorA = new b2Vec2();
this.m_localAnchorB = new b2Vec2();
this.m_impulse = new b2Vec3();
this.m_mass = new b2Mat33();
};
b2WeldJoint.prototype.GetAnchorA = function () {
return this.m_bodyA.GetWorldPoint(this.m_localAnchorA);
}
b2WeldJoint.prototype.GetAnchorB = function () {
return this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
}
b2WeldJoint.prototype.GetReactionForce = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return new b2Vec2(inv_dt * this.m_impulse.x, inv_dt * this.m_impulse.y);
}
b2WeldJoint.prototype.GetReactionTorque = function (inv_dt) {
if (inv_dt === undefined) inv_dt = 0;
return inv_dt * this.m_impulse.z;
}
b2WeldJoint.prototype.b2WeldJoint = function (def) {
this.__super.b2Joint.call(this, def);
this.m_localAnchorA.SetV(def.localAnchorA);
this.m_localAnchorB.SetV(def.localAnchorB);
this.m_referenceAngle = def.referenceAngle;
this.m_impulse.SetZero();
this.m_mass = new b2Mat33();
}
b2WeldJoint.prototype.InitVelocityConstraints = function (step) {
var tMat;
var tX = 0;
var bA = this.m_bodyA;
var bB = this.m_bodyB;
tMat = bA.m_xf.R;
var rAX = this.m_localAnchorA.x - bA.m_sweep.localCenter.x;
var rAY = this.m_localAnchorA.y - bA.m_sweep.localCenter.y;
tX = (tMat.col1.x * rAX + tMat.col2.x * rAY);
rAY = (tMat.col1.y * rAX + tMat.col2.y * rAY);
rAX = tX;
tMat = bB.m_xf.R;
var rBX = this.m_localAnchorB.x - bB.m_sweep.localCenter.x;
var rBY = this.m_localAnchorB.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * rBX + tMat.col2.x * rBY);
rBY = (tMat.col1.y * rBX + tMat.col2.y * rBY);
rBX = tX;
var mA = bA.m_invMass;
var mB = bB.m_invMass;
var iA = bA.m_invI;
var iB = bB.m_invI;
this.m_mass.col1.x = mA + mB + rAY * rAY * iA + rBY * rBY * iB;
this.m_mass.col2.x = (-rAY * rAX * iA) - rBY * rBX * iB;
this.m_mass.col3.x = (-rAY * iA) - rBY * iB;
this.m_mass.col1.y = this.m_mass.col2.x;
this.m_mass.col2.y = mA + mB + rAX * rAX * iA + rBX * rBX * iB;
this.m_mass.col3.y = rAX * iA + rBX * iB;
this.m_mass.col1.z = this.m_mass.col3.x;
this.m_mass.col2.z = this.m_mass.col3.y;
this.m_mass.col3.z = iA + iB;
if (step.warmStarting) {
this.m_impulse.x *= step.dtRatio;
this.m_impulse.y *= step.dtRatio;
this.m_impulse.z *= step.dtRatio;
bA.m_linearVelocity.x -= mA * this.m_impulse.x;
bA.m_linearVelocity.y -= mA * this.m_impulse.y;
bA.m_angularVelocity -= iA * (rAX * this.m_impulse.y - rAY * this.m_impulse.x + this.m_impulse.z);
bB.m_linearVelocity.x += mB * this.m_impulse.x;
bB.m_linearVelocity.y += mB * this.m_impulse.y;
bB.m_angularVelocity += iB * (rBX * this.m_impulse.y - rBY * this.m_impulse.x + this.m_impulse.z);
}
else {
this.m_impulse.SetZero();
}
}
b2WeldJoint.prototype.SolveVelocityConstraints = function (step) {
var tMat;
var tX = 0;
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var vA = bA.m_linearVelocity;
var wA = bA.m_angularVelocity;
var vB = bB.m_linearVelocity;
var wB = bB.m_angularVelocity;
var mA = bA.m_invMass;
var mB = bB.m_invMass;
var iA = bA.m_invI;
var iB = bB.m_invI;
tMat = bA.m_xf.R;
var rAX = this.m_localAnchorA.x - bA.m_sweep.localCenter.x;
var rAY = this.m_localAnchorA.y - bA.m_sweep.localCenter.y;
tX = (tMat.col1.x * rAX + tMat.col2.x * rAY);
rAY = (tMat.col1.y * rAX + tMat.col2.y * rAY);
rAX = tX;
tMat = bB.m_xf.R;
var rBX = this.m_localAnchorB.x - bB.m_sweep.localCenter.x;
var rBY = this.m_localAnchorB.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * rBX + tMat.col2.x * rBY);
rBY = (tMat.col1.y * rBX + tMat.col2.y * rBY);
rBX = tX;
var Cdot1X = vB.x - wB * rBY - vA.x + wA * rAY;
var Cdot1Y = vB.y + wB * rBX - vA.y - wA * rAX;
var Cdot2 = wB - wA;
var impulse = new b2Vec3();
this.m_mass.Solve33(impulse, (-Cdot1X), (-Cdot1Y), (-Cdot2));
this.m_impulse.Add(impulse);
vA.x -= mA * impulse.x;
vA.y -= mA * impulse.y;
wA -= iA * (rAX * impulse.y - rAY * impulse.x + impulse.z);
vB.x += mB * impulse.x;
vB.y += mB * impulse.y;
wB += iB * (rBX * impulse.y - rBY * impulse.x + impulse.z);
bA.m_angularVelocity = wA;
bB.m_angularVelocity = wB;
}
b2WeldJoint.prototype.SolvePositionConstraints = function (baumgarte) {
if (baumgarte === undefined) baumgarte = 0;
var tMat;
var tX = 0;
var bA = this.m_bodyA;
var bB = this.m_bodyB;
tMat = bA.m_xf.R;
var rAX = this.m_localAnchorA.x - bA.m_sweep.localCenter.x;
var rAY = this.m_localAnchorA.y - bA.m_sweep.localCenter.y;
tX = (tMat.col1.x * rAX + tMat.col2.x * rAY);
rAY = (tMat.col1.y * rAX + tMat.col2.y * rAY);
rAX = tX;
tMat = bB.m_xf.R;
var rBX = this.m_localAnchorB.x - bB.m_sweep.localCenter.x;
var rBY = this.m_localAnchorB.y - bB.m_sweep.localCenter.y;
tX = (tMat.col1.x * rBX + tMat.col2.x * rBY);
rBY = (tMat.col1.y * rBX + tMat.col2.y * rBY);
rBX = tX;
var mA = bA.m_invMass;
var mB = bB.m_invMass;
var iA = bA.m_invI;
var iB = bB.m_invI;
var C1X = bB.m_sweep.c.x + rBX - bA.m_sweep.c.x - rAX;
var C1Y = bB.m_sweep.c.y + rBY - bA.m_sweep.c.y - rAY;
var C2 = bB.m_sweep.a - bA.m_sweep.a - this.m_referenceAngle;
var k_allowedStretch = 10.0 * b2Settings.b2_linearSlop;
var positionError = Math.sqrt(C1X * C1X + C1Y * C1Y);
var angularError = b2Math.Abs(C2);
if (positionError > k_allowedStretch) {
iA *= 1.0;
iB *= 1.0;
}
this.m_mass.col1.x = mA + mB + rAY * rAY * iA + rBY * rBY * iB;
this.m_mass.col2.x = (-rAY * rAX * iA) - rBY * rBX * iB;
this.m_mass.col3.x = (-rAY * iA) - rBY * iB;
this.m_mass.col1.y = this.m_mass.col2.x;
this.m_mass.col2.y = mA + mB + rAX * rAX * iA + rBX * rBX * iB;
this.m_mass.col3.y = rAX * iA + rBX * iB;
this.m_mass.col1.z = this.m_mass.col3.x;
this.m_mass.col2.z = this.m_mass.col3.y;
this.m_mass.col3.z = iA + iB;
var impulse = new b2Vec3();
this.m_mass.Solve33(impulse, (-C1X), (-C1Y), (-C2));
bA.m_sweep.c.x -= mA * impulse.x;
bA.m_sweep.c.y -= mA * impulse.y;
bA.m_sweep.a -= iA * (rAX * impulse.y - rAY * impulse.x + impulse.z);
bB.m_sweep.c.x += mB * impulse.x;
bB.m_sweep.c.y += mB * impulse.y;
bB.m_sweep.a += iB * (rBX * impulse.y - rBY * impulse.x + impulse.z);
bA.SynchronizeTransform();
bB.SynchronizeTransform();
return positionError <= b2Settings.b2_linearSlop && angularError <= b2Settings.b2_angularSlop;
}
b2WeldJointDef.inherit(Box2D.Dynamics.Joints.b2JointDef);
b2WeldJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
b2WeldJointDef.b2WeldJointDef = function () {
Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
this.localAnchorA = new b2Vec2();
this.localAnchorB = new b2Vec2();
};
b2WeldJointDef.prototype.b2WeldJointDef = function () {
this.__super.b2JointDef.call(this);
this.type = b2Joint.e_weldJoint;
this.referenceAngle = 0.0;
}
b2WeldJointDef.prototype.Initialize = function (bA, bB, anchor) {
this.bodyA = bA;
this.bodyB = bB;
this.localAnchorA.SetV(this.bodyA.GetLocalPoint(anchor));
this.localAnchorB.SetV(this.bodyB.GetLocalPoint(anchor));
this.referenceAngle = this.bodyB.GetAngle() - this.bodyA.GetAngle();
}
})();
var Vector_a2j_Number = a2j.NVector;
//post-definitions
for (var i = 0; i < _A2J_postDefs.length; ++i) _A2J_postDefs[i]();(function() {
function b2DebugDraw() {
b2DebugDraw.b2DebugDraw.apply(this, arguments);
if (this.constructor === b2DebugDraw) this.b2DebugDraw.apply(this, arguments);
}
Box2D.Dynamics.b2DebugDraw = b2DebugDraw;
})();
_A2J_postDefs = [];
(function() {
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
b2DebugDraw.b2DebugDraw = function () {
this.m_drawScale = 1.0;
this.m_lineThickness = 1.0;
this.m_alpha = 1.0;
this.m_fillAlpha = 1.0;
this.m_xformScale = 1.0;
var __this = this;
//#WORKAROUND
this.m_sprite = {graphics: {clear:
function() {__this.m_ctx.clearRect(0,0,__this.m_ctx.canvas.width,__this.m_ctx.canvas.height)}
}};
};
b2DebugDraw.prototype._color = function(color, alpha) {
return "rgba("+ ((color & 0xFF0000) >> 16) +","+ ((color & 0xFF00) >> 8) +","+
(color & 0xFF) +","+ alpha +")";
};
b2DebugDraw.prototype.b2DebugDraw = function () {
this.m_drawFlags = 0;
};
b2DebugDraw.prototype.SetFlags = function (flags) {
if (flags === undefined) flags = 0;
this.m_drawFlags = flags;
};
b2DebugDraw.prototype.GetFlags = function () {
return this.m_drawFlags;
};
b2DebugDraw.prototype.AppendFlags = function (flags) {
if (flags === undefined) flags = 0;
this.m_drawFlags |= flags;
};
b2DebugDraw.prototype.ClearFlags = function (flags) {
if (flags === undefined) flags = 0;
this.m_drawFlags &= ~flags;
};
b2DebugDraw.prototype.SetSprite = function (sprite) {
this.m_ctx = sprite;
};
b2DebugDraw.prototype.GetSprite = function () {
return this.m_ctx;
};
b2DebugDraw.prototype.SetDrawScale = function (drawScale) {
if (drawScale === undefined) drawScale = 0;
this.m_drawScale = drawScale;
};
b2DebugDraw.prototype.GetDrawScale = function () {
return this.m_drawScale;
};
b2DebugDraw.prototype.SetLineThickness = function (lineThickness) {
if (lineThickness === undefined) lineThickness = 0;
this.m_lineThickness = lineThickness;
this.m_ctx.strokeWidth = lineThickness;
};
b2DebugDraw.prototype.GetLineThickness = function () {
return this.m_lineThickness;
};
b2DebugDraw.prototype.SetAlpha = function (alpha) {
if (alpha === undefined) alpha = 0;
this.m_alpha = alpha;
};
b2DebugDraw.prototype.GetAlpha = function () {
return this.m_alpha;
};
b2DebugDraw.prototype.SetFillAlpha = function (alpha) {
if (alpha === undefined) alpha = 0;
this.m_fillAlpha = alpha;
};
b2DebugDraw.prototype.GetFillAlpha = function () {
return this.m_fillAlpha;
};
b2DebugDraw.prototype.SetXFormScale = function (xformScale) {
if (xformScale === undefined) xformScale = 0;
this.m_xformScale = xformScale;
};
b2DebugDraw.prototype.GetXFormScale = function () {
return this.m_xformScale;
};
b2DebugDraw.prototype.DrawPolygon = function (vertices, vertexCount, color) {
if(!vertexCount) return;
var s = this.m_ctx;
var drawScale = this.m_drawScale;
s.beginPath();
s.strokeStyle = this._color(color.color, this.m_alpha);
s.moveTo(vertices[0].x * drawScale, vertices[0].y * drawScale);
for (var i = 1; i < vertexCount; i++) {
s.lineTo(vertices[i].x * drawScale, vertices[i].y * drawScale);
}
s.lineTo(vertices[0].x * drawScale, vertices[0].y * drawScale);
s.closePath();
s.stroke();
};
b2DebugDraw.prototype.DrawSolidPolygon = function (vertices, vertexCount, color) {
if(!vertexCount) return;
var s = this.m_ctx;
var drawScale = this.m_drawScale;
s.beginPath();
s.strokeStyle = this._color(color.color, this.m_alpha);
s.fillStyle = this._color(color.color, this.m_fillAlpha);
s.moveTo(vertices[0].x * drawScale, vertices[0].y * drawScale);
for (var i = 1; i < vertexCount; i++) {
s.lineTo(vertices[i].x * drawScale, vertices[i].y * drawScale);
}
s.lineTo(vertices[0].x * drawScale, vertices[0].y * drawScale);
s.closePath();
s.fill();
s.stroke();
};
b2DebugDraw.prototype.DrawCircle = function (center, radius, color) {
if(!radius) return;
var s = this.m_ctx;
var drawScale = this.m_drawScale;
s.beginPath();
s.strokeStyle = this._color(color.color, this.m_alpha);
s.arc(center.x * drawScale, center.y * drawScale, radius * drawScale, 0, Math.PI*2, true);
s.closePath();
s.stroke();
};
b2DebugDraw.prototype.DrawSolidCircle = function (center, radius, axis, color) {
/*if (radius === undefined) radius = 0;
this.m_ctx.graphics.lineStyle(this.m_lineThickness, color.color, this.m_alpha);
this.m_ctx.graphics.moveTo(0, 0);
this.m_ctx.graphics.beginFill(color.color, this.m_fillAlpha);
this.m_ctx.graphics.drawCircle(center.x * this.m_drawScale, center.y * this.m_drawScale, radius * this.m_drawScale);
this.m_ctx.graphics.endFill();
this.m_ctx.graphics.moveTo(center.x * this.m_drawScale, center.y * this.m_drawScale);
this.m_ctx.graphics.lineTo((center.x + axis.x * radius) * this.m_drawScale, (center.y + axis.y * radius) * this.m_drawScale);
*/
if(!radius) return;
var s = this.m_ctx
, drawScale = this.m_drawScale
, cx = center.x * drawScale
, cy = center.y * drawScale
;
s.moveTo(0, 0);
s.beginPath();
s.strokeStyle = this._color(color.color, this.m_alpha);
s.fillStyle = this._color(color.color, this.m_fillAlpha);
s.arc(cx, cy, radius * drawScale, 0, Math.PI*2, true);
s.moveTo(cx, cy);
s.lineTo((center.x + axis.x * radius) * drawScale, (center.y + axis.y * radius) * drawScale);
s.closePath();
s.fill();
s.stroke();
};
b2DebugDraw.prototype.DrawSegment = function (p1, p2, color) {
var s = this.m_ctx
, drawScale = this.m_drawScale
;
s.strokeStyle = this._color(color.color, this.m_alpha);
s.beginPath();
s.moveTo(p1.x * drawScale, p1.y * drawScale);
s.lineTo(p2.x * drawScale, p2.y * drawScale);
s.closePath();
s.stroke();
};
b2DebugDraw.prototype.DrawTransform = function (xf) {
var s = this.m_ctx
, drawScale = this.m_drawScale
;
s.beginPath();
s.strokeStyle = this._color(0xff0000, this.m_alpha);
s.moveTo(xf.position.x * drawScale, xf.position.y * drawScale);
s.lineTo((xf.position.x + this.m_xformScale * xf.R.col1.x) * drawScale, (xf.position.y + this.m_xformScale * xf.R.col1.y) * drawScale);
s.strokeStyle = this._color(0xff00, this.m_alpha);
s.moveTo(xf.position.x * drawScale, xf.position.y * drawScale);
s.lineTo((xf.position.x + this.m_xformScale * xf.R.col2.x) * drawScale, (xf.position.y + this.m_xformScale * xf.R.col2.y) * drawScale);
s.closePath();
s.stroke();
};
_A2J_postDefs.push(function () {
Box2D.Dynamics.b2DebugDraw.e_shapeBit = 0x0001;
Box2D.Dynamics.b2DebugDraw.prototype.e_shapeBit = Box2D.Dynamics.b2DebugDraw.e_shapeBit;
Box2D.Dynamics.b2DebugDraw.e_jointBit = 0x0002;
Box2D.Dynamics.b2DebugDraw.prototype.e_jointBit = Box2D.Dynamics.b2DebugDraw.e_jointBit;
Box2D.Dynamics.b2DebugDraw.e_aabbBit = 0x0004;
Box2D.Dynamics.b2DebugDraw.prototype.e_aabbBit = Box2D.Dynamics.b2DebugDraw.e_aabbBit;
Box2D.Dynamics.b2DebugDraw.e_pairBit = 0x0008;
Box2D.Dynamics.b2DebugDraw.prototype.e_pairBit = Box2D.Dynamics.b2DebugDraw.e_pairBit;
Box2D.Dynamics.b2DebugDraw.e_centerOfMassBit = 0x0010;
Box2D.Dynamics.b2DebugDraw.prototype.e_centerOfMassBit = Box2D.Dynamics.b2DebugDraw.e_centerOfMassBit;
Box2D.Dynamics.b2DebugDraw.e_controllerBit = 0x0020;
Box2D.Dynamics.b2DebugDraw.prototype.e_controllerBit = Box2D.Dynamics.b2DebugDraw.e_controllerBit;
});
})();
//post-definitions
for (var i = 0; i < _A2J_postDefs.length; ++i) _A2J_postDefs[i](); | JavaScript |
/*
Package: progress
Utility classes to track and draw progress (for loading.... messages).
*/
/*
Class: ProgressMeter
A class that keeps two counters. A counter of the number of tasks left to be done
and a counter of how far the current task has progressed. Execution of the tasks
are outside of ProgressMeter but when progress is made on a task the executor
calls ProgressMeter.progress. This class then issues callbacks to listeners to
inform them of the progress being made. The listeners, typicaly GUI elements,
can inform the user of the progress.
Constructor:
tasknames - An Array of (String) names for the tasks to be performed. Used in
the callbacks to inform the listeners of the current task name.
listeners - An array of functions that are to be called on progress. The first
parameter on the callback is the (String) taskname. The second
parameters on the callback is the progress as a number between 0
and 1. The progress indicates overall total progress, not the
progress for a single task.
*/
function ProgressMeter(tasknames, listeners) {
this.tasknames = new Array() ;
this.tasknames = this.tasknames.concat(tasknames) ;
this.listeners = new Array() ;
this.listeners = this.listeners.concat(listeners) ;
this.activeTaskIndex = 0 ;
this.activeTaskProgress = 0 ;
this.progressPerTask = 1/this.tasknames.length ;
this.totalTaskProgress = 0 ;
}
ProgressMeter.prototype = {
/*
Function: progress
Used to inform the ProgressMeter that a task has progressed. Issues
callbacks to the registered listeners to inform of the progress. The callback
informs of the overall progress and which task is the current active one.
Parameters:
fractionComplete - A number between 0 and 1 indicating the progress for
the current task. When progress is >= 1.0 the ProgressMeter switches
the active task to the next.
*/
progress : function(fractionComplete) {
if (fractionComplete > 1.0) {
fractionComplete = 1.0 ;
}
if (fractionComplete < 0) {
fractionComplete = 0 ;
}
this.activeTaskProgress = fractionComplete ;
this.totalTaskProgress = this.activeTaskIndex*this.progressPerTask + (this.activeTaskProgress * this.progressPerTask) ;
this.fireProgress();
if (this.activeTaskProgress > 0.99) {
this.activeTaskIndex++ ;
}
},
/*
Function: fireProgress
Internal function, do not call. Issues callbacks to the registered listener
functions to indicate progress.
*/
fireProgress : function() {
for (var n=0; n<this.listeners.length; n++) {
this.listeners[n](this.tasknames[this.activeTaskIndex], this.totalTaskProgress);
}
}
};
/*
Class: ProgressBar
Draws a progress bar on the given canvas. Register an instance of this class on
a progress meter and watch the blinken bars.
Constructor:
ctx - The canvas 2D context to draw on.
appearance - Optional object defining the appearance of the progress bar.
appearance:
x - The left edge of the progress bar in the canvas. Defaults to 10.
y - The top edge of the progress bar in the canvas. Defaults to 10.
width - The width of the progress bar in the canvas. Defaults to 620.
height - The height of the progress bar in the canvas. Defaults to 40.
*/
function ProgressBar(ctx, appearance) {
this.ctx = ctx ;
this.x = 10 ;
this.y = 10 ;
this.width = 620 ;
this.height = 40 ;
if (appearance) {
if (appearance.x) {
this.x = appearance.x ;
}
if (appearance.y) {
this.y = appearance.y ;
}
if (appearance.width) {
this.width = appearance.width ;
}
if (appearance.height) {
this.height = appearance.height ;
}
}
this.gradient = ctx.createLinearGradient(0, 0, this.width, this.height);
this.gradient.addColorStop(0, "#0000ff");
this.gradient.addColorStop(1, "#00ff00");
var fontHeight = (this.height/2)-4 ;
fontHeight = Math.min(fontHeight, 30);
this.font = fontHeight + "px sans" ;
}
ProgressBar.prototype = {
/*
callback: progress
Callback from a <ProgressMeter> to update the progress bar GUI.
*/
progress : function(taskname, progressFraction) {
this.ctx.fillStyle="#000000" ;
this.ctx.fillRect(this.x, this.y, this.width, this.height) ;
this.ctx.fillStyle=this.gradient;
this.ctx.fillRect(this.x, this.y, this.width * progressFraction, this.height) ;
this.ctx.lineWidth = 2.0 ;
this.ctx.strokeStyle="#f0f0f0" ;
this.ctx.strokeRect(this.x, this.y, this.width, this.height) ;
this.ctx.font=this.font ;
this.ctx.textBaseline="middle";
var metrics = this.ctx.measureText(taskname) ;
var textx = this.width/2 - metrics.width/2 + this.x;
this.ctx.fillStyle="#f0f0f0" ;
this.ctx.fillText(taskname, textx, this.y+this.height/2, this.width) ;
}
};
| JavaScript |
/*
Copyright 2011 Johan Maasing
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
window.onload = function() {
reset() ;
}
var tasknames = ["Loading stuff", "Generating fake stuff"] ;
var progressMeter ;
var currentTask = 0 ;
var currentProgress = 0 ;
var timerId = -1;
function reset() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var bar = new ProgressBar(ctx, {x: 30, y:220, width: 580, height:40});
// Draw the bar
bar.progress(0) ;
var listeners = [ progress1, bind(bar, bar.progress) ] ;
// var listeners = [progress1,progress2] ;
progressMeter = new ProgressMeter(tasknames, listeners) ;
currentTask = 0 ;
currentProgress = 0 ;
timerId = window.setInterval(makeProgress, 200);
}
function makeProgress() {
if (currentTask < tasknames.length) {
progressMeter.progress(currentProgress) ;
currentProgress += 0.1 ;
if (currentProgress > 1) {
currentProgress = 0 ;
currentTask++;
}
} else {
window.clearInterval(timerId) ;
}
}
function progress1(taskname, fractionProgress) {
console.log("Progress1: " + taskname + " " + fractionProgress) ;
}
function bind(obj, fn) {
return function() {
fn.apply(obj, arguments) ;
};
}
| JavaScript |
/*
Copyright 2011 Johan Maasing
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
function bind(obj, fn) {
return function() {
fn.apply(obj, arguments) ;
};
}
window.onload = function() {
reset();
}
var tasknames = ["Loading images"] ;
var ctx ;
function reset() {
var canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
var bar = new ProgressBar(ctx, {x: 30, y:220, width: 580, height:40});
var listeners = [ bind(bar, bar.progress) ] ;
var progressMeter = new ProgressMeter(tasknames, listeners) ;
var loader = new ImageLoader(progressMeter) ;
googleImage = loader.createImage("http://www.google.se/images/nav_logo29.png");
loader.addListener(function() { console.log("Done processing images");}) ;
loader.addListener(imagesLoaded) ;
loader.start() ;
}
var googleImage ;
function imagesLoaded() {
ctx.drawImage(googleImage, 10, 10) ;
}
| JavaScript |
/*
Copyright 2011 Johan Maasing
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Package: Loader
Utility classes to load resources
*/
/*
Class: ImageLoader
A class that creates image objects and populate them with remote data. Use this
class by instantiating it. Then create all the image objects that are to be
loaded. Register callback listeners and finally start the loader.
After the loader has started it is not possible to add images or listeners.
Constructor:
progressMeter - An optional progress meter object that is to be updated with
loading progress.
*/
function ImageLoader(progressMeter) {
this.loading = false ;
this.images = new Array() ;
this.listeners = new Array() ;
this.progressMeter = progressMeter ;
this.imagesProcessed = 0 ;
this.numberOfImages = 0 ;
}
ImageLoader.prototype = {
/*
Function: createImage
Create an image object that is to be loaded by this loader.
Parameters:
src - The image src URL to be used to load the image.
*/
createImage : function(src) {
if (this.loading) {
throw "Loading started, can not add more images" ;
}
if (!src) {
throw "Must give the image src URL" ;
}
this.numberOfImages++;
var image = new Image() ;
image.onload = bind(this, this.onLoad) ;
image.onabort = bind(this, this.onAbort) ;
image.onerror = bind(this, this.onError) ;
this.images.push({image: image, src: src}) ;
return image ;
},
/*
Function: start
Start loading the images. No more images can be registered through <createImage>
*/
start : function() {
if (!this.loading) {
this.loading = true ;
for (var n=0; n<this.images.length; n++) {
this.images[n].image.src=this.images[n].src ;
}
}
},
/*
Function: addListener
Add a listener the is informed when all the images have been processed.
Parameters:
listener - The function to call when all images have been processed.
*/
addListener : function(listener) {
if (listener) {
this.listeners.push(listener) ;
}
},
/*
Function: fireProgress
Internal function, do not call. Issues callbacks to the progressMeter
*/
fireProgress : function() {
if (this.progressMeter) {
this.progressMeter.progress(this.imagesProcessed/this.numberOfImages) ;
}
if (this.imagesProcessed == this.numberOfImages) {
for (var n=0; n<this.listeners.length; n++) {
this.listeners[n]() ;
}
}
},
/*
Callback: onLoad
Internal function, do not call.
*/
onLoad : function(event) {
this.imagesProcessed++ ;
this.fireProgress() ;
if (console) {
console.log("Loaded : " + this.getSrc(event)) ;
}
},
/*
Callback: onAbort
Internal function, do not call.
*/
onAbort : function(event) {
this.imagesProcessed++ ;
this.fireProgress() ;
if (console) {
console.log("Aborted :" + this.getSrc(event)) ;
}
},
/*
Callback: onError
Internal function, do not call.
*/
onError : function(event) {
this.imagesProcessed++ ;
this.fireProgress() ;
if (console) {
console.log("Error :" + this.getSrc(event)) ;
}
},
/*
Function: getSrc
Internal function, do not call
*/
getSrc : function(event) {
if (event) {
if (event.target) {
if (event.target.src) {
return event.target.src ;
} else {
return event.target ;
}
} else {
return event ;
}
} else {
return "?" ;
}
}
};
| JavaScript |
/* JPEGCam v1.0.9 */
/* Webcam library for capturing JPEG images and submitting to a server */
/* Copyright (c) 2008 - 2009 Joseph Huckaby <jhuckaby@goldcartridge.com> */
/* Licensed under the GNU Lesser Public License */
/* http://www.gnu.org/licenses/lgpl.html */
/* Usage:
<script language="JavaScript">
document.write( webcam.get_html(320, 240) );
webcam.set_api_url( 'test.php' );
webcam.set_hook( 'onComplete', 'my_callback_function' );
function my_callback_function(response) {
alert("Success! PHP returned: " + response);
}
</script>
<a href="javascript:void(webcam.snap())">Take Snapshot</a>
*/
// Everything is under a 'webcam' Namespace
window.webcam = {
version: '1.0.9',
// globals
ie: !!navigator.userAgent.match(/MSIE/),
protocol: location.protocol.match(/https/i) ? 'https' : 'http',
callback: null, // user callback for completed uploads
swf_url: 'webcam.swf', // URI to webcam.swf movie (defaults to cwd)
shutter_url: 'shutter.mp3', // URI to shutter.mp3 sound
api_url: '', // URL to upload script
loaded: false, // true when webcam movie finishes loading
quality: 90, // JPEG quality (1 - 100)
shutter_sound: true, // shutter sound effect on/off
stealth: false, // stealth mode (do not freeze image upon capture)
hooks: {
onLoad: null,
onComplete: null,
onError: null
}, // callback hook functions
set_hook: function(name, callback) {
// set callback hook
// supported hooks: onLoad, onComplete, onError
if (typeof(this.hooks[name]) == 'undefined')
return alert("Hook type not supported: " + name);
this.hooks[name] = callback;
},
fire_hook: function(name, value) {
// fire hook callback, passing optional value to it
if (this.hooks[name]) {
if (typeof(this.hooks[name]) == 'function') {
// callback is function reference, call directly
this.hooks[name](value);
}
else if (typeof(this.hooks[name]) == 'array') {
// callback is PHP-style object instance method
this.hooks[name][0][this.hooks[name][1]](value);
}
else if (window[this.hooks[name]]) {
// callback is global function name
window[ this.hooks[name] ](value);
}
return true;
}
return false; // no hook defined
},
set_api_url: function(url) {
// set location of upload API script
this.api_url = url;
},
set_swf_url: function(url) {
// set location of SWF movie (defaults to webcam.swf in cwd)
this.swf_url = url;
},
get_html: function(width, height, server_width, server_height) {
// Return HTML for embedding webcam capture movie
// Specify pixel width and height (640x480, 320x240, etc.)
// Server width and height are optional, and default to movie width/height
if (!server_width) server_width = width;
if (!server_height) server_height = height;
var html = '';
var flashvars = 'shutter_enabled=' + (this.shutter_sound ? 1 : 0) +
'&shutter_url=' + escape(this.shutter_url) +
'&width=' + width +
'&height=' + height +
'&server_width=' + server_width +
'&server_height=' + server_height;
if (this.ie) {
html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+this.protocol+'://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="webcam_movie" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+this.swf_url+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/></object>';
}
else {
html += '<embed id="webcam_movie" src="'+this.swf_url+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="webcam_movie" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" />';
}
this.loaded = false;
return html;
},
get_movie: function() {
// get reference to movie object/embed in DOM
if (!this.loaded) return alert("ERROR: Movie is not loaded yet");
var movie = document.getElementById('webcam_movie');
if (!movie) alert("ERROR: Cannot locate movie 'webcam_movie' in DOM");
return movie;
},
set_stealth: function(stealth) {
// set or disable stealth mode
this.stealth = stealth;
},
snap: function(url, callback, stealth) {
// take snapshot and send to server
// specify fully-qualified URL to server API script
// and callback function (string or function object)
if (callback) this.set_hook('onComplete', callback);
if (url) this.set_api_url(url);
if (typeof(stealth) != 'undefined') this.set_stealth( stealth );
this.get_movie()._snap( this.api_url, this.quality, this.shutter_sound ? 1 : 0, this.stealth ? 1 : 0 );
},
freeze: function() {
// freeze webcam image (capture but do not upload)
this.get_movie()._snap('', this.quality, this.shutter_sound ? 1 : 0, 0 );
},
upload: function(url, callback) {
// upload image to server after taking snapshot
// specify fully-qualified URL to server API script
// and callback function (string or function object)
if (callback) this.set_hook('onComplete', callback);
if (url) this.set_api_url(url);
this.get_movie()._upload( this.api_url );
},
reset: function() {
// reset movie after taking snapshot
this.get_movie()._reset();
},
configure: function(panel) {
// open flash configuration panel -- specify tab name:
// "camera", "privacy", "default", "localStorage", "microphone", "settingsManager"
if (!panel) panel = "camera";
this.get_movie()._configure(panel);
},
set_quality: function(new_quality) {
// set the JPEG quality (1 - 100)
// default is 90
this.quality = new_quality;
},
set_shutter_sound: function(enabled, url) {
// enable or disable the shutter sound effect
// defaults to enabled
this.shutter_sound = enabled;
this.shutter_url = url ? url : 'shutter.mp3';
},
flash_notify: function(type, msg) {
// receive notification from flash about event
switch (type) {
case 'flashLoadComplete':
// movie loaded successfully
this.loaded = true;
this.fire_hook('onLoad');
break;
case 'error':
// HTTP POST error most likely
if (!this.fire_hook('onError', msg)) {
alert("JPEGCam Flash Error: " + msg);
}
break;
case 'success':
// upload complete, execute user callback function
// and pass raw API script results to function
this.fire_hook('onComplete', msg.toString());
break;
default:
// catch-all, just in case
alert("jpegcam flash_notify: " + type + ": " + msg);
break;
}
}
};
| JavaScript |
var progressArea="progressArea";
var progressMessageHolder="progressMessageHolder";
A4J.AJAX.onError = function(req, status, message)
{
if(status==500)
{
window.alert("Your session has expired !\nError: "+message);
onAppTimeOut();
alert("Please LogIn again...");
document.location.href='LogIn.jsf';
}
// else
// window.alert("Server Error...\nMessage: "+message);
}
A4J.AJAX.onExpired = function(loc, expiredMsg){
if(window.confirm("Custom onExpired handler "+expiredMsg+" for a location: "+loc)){
return loc;
} else {
return false;
}
}
function setMessage(src,msg)
{
document.getElementById(src).innerHTML=msg;
}
function setVisible(src,flag)
{
if(flag)
document.getElementById(src).style.visibility="visible";
else
document.getElementById(src).style.visibility="hidden";
}
function showProgress(msg)
{
document.getElementById(progressMessageHolder).innerHTML=msg;
document.getElementById(progressArea).style.visibility="visible";
}
function hideProgress()
{
document.getElementById(progressArea).style.visibility="hidden";
}
/*
* Shows alert, converts each , with \n
*/
function showAlert(data)
{
var d = data.toString();
alert( d.replace(/;/g,"\n") );
}
/*
* Validate the characters entered as soon as they are entered
* Arguments
* Control inputObject : The input component object to work on
* Boolean flag : show alert or not
*/
function validateInteger(inputObject,flag,message)
{
var re = /[^0-9]/;
if (re.exec(inputObject.value))
{
if(flag)
alert(message);
inputObject.value = "0";
}
}
function validateDouble(inputObject,flag,message)
{
if ( isNaN(inputObject.value))
{
if(flag)
alert(message);
inputObject.value = "0";
}
}
function validateTimeRegular(inputObject,flag,message)
{
var re = /^((0[1-9])|(1[0-2])):[0-5][0-9] [aApP][mM]/;
if (!re.exec(inputObject.value))
{
if(flag)
alert(message);
//inputObject.value = "09:00 AM";
}
}
function validateTime(inputObject,flag,message)
{
var re = /^(([01][0-9])|(2[0-3])):[0-5][0-9]$/;
if (!re.exec(inputObject.value))
{
if(flag)
alert(message);
inputObject.value = "09:00";
}
}
// validate length of inputObject, if flag is set, popup alert
function validateLength(inputObject,size,flag,message)
{
var str ="";
try
{
if(inputObject.value.length>size)
{
if(flag)
alert(message);
str = inputObject.value.toString();
inputObject.value = str.substring(0, size);
}
}
catch(e)
{
}
return true;
}
// 'This Process is irreversible !!!\nAre you sure to submit ?'
function showConfirmation(message)
{
if(!confirm(message))
return false;
return true;
}
function showBusy()
{
Richfaces.showModalPanel('mpBusy');
}
function showLoading()
{
Richfaces.showModalPanel('loadingWindow');
}
function hideLoading()
{
Richfaces.hideModalPanel('loadingWindow');
}
function showWarning(msg)
{
var ele = document.getElementById('mpWarningMessage');
ele.innerHTML = "<span>"+ msg +"</span>";
Richfaces.showModalPanel('mpWarning');
}
function hideWarning()
{
Richfaces.hideModalPanel('mpWarning');
}
function showWarningAutoClose(msg,closeAfter)
{
showWarning(msg);
setTimeout("hideWarning()",closeAfter );
}
function hideBusy()
{
Richfaces.hideModalPanel('mpBusy');
}
function isTableEmpty(formId,tableId)
{
var table = document.getElementById(formId+':'+tableId);
var rowCount = table.rows.length;
return rowCount <= 0;
}
function showElement(eleId, flag)
{
if(flag)
{
document.getElementById(eleId).style.display='';
}
else
{
document.getElementById(eleId).style.display='none';
}
}
function toggleDisplay(eleId)
{
var displayStyle = document.getElementById(eleId).style.display;
if( "none" == displayStyle )
{
document.getElementById(eleId).style.display='';
}
else
{
document.getElementById(eleId).style.display='none';
}
}
function showLarge(ev,tar,url) {
var ee = document.getElementById('imageEnlarged');
ee.style.left = (ev.pageX + 50)+"px";
ee.style.top = (ev.pageY - 120 )+"px";
ee.src=url;
ee.style.visibility="visible";
}
function hideLarge() {
var ee = document.getElementById('imageEnlarged');
ee.src="";
ee.style.visibility="hidden";
}
function launchChildWindow(url) {
wopts = 'width=600,height=500,resizable=1,alwaysRaised=1,scrollbars=1';
var neww = window.open(url,'Popup',wopts);
if (window.focus) {neww.focus();}
}
/*
function launchChildWindow(url) {
wopts = 'width=300,height=300,resizable=1,alwaysRaised=1,scrollbars=1';
var neww = window.open(url,'Popup',wopts);
if (window.focus) {neww.focus();}
}
*/
function allert(idd) {
var v = idd;
alert(v);
}
function getTodayStr() {
return ""+($.datepicker.formatDate('dd/mm/yyy', new Date()));
}
function validateDate(input) {
var validformat=/^\d{2}\/\d{2}\/\d{4}$/;
var returnval=false;
if (!validformat.test(input)) {
return false;
}
var monthfield=input.split("/")[1];
var dayfield=input.split("/")[0];
var yearfield=input.split("/")[2];
var dayobj = new Date(yearfield, monthfield-1, dayfield);
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield)) {
return false;
}
return true;
}
| JavaScript |
/**
* jQuery webcam
* Copyright (c) 2010, Robert Eisele (robert@xarg.org)
* Dual licensed under the MIT or GPL Version 2 licenses.
* Date: 09/12/2010
*
* @author Robert Eisele
* @version 1.0
*
* @see http://www.xarg.org/project/jquery-webcam-plugin/
**/
(function ($) {
var webcam = {
extern: null, // external select token to support jQuery dialogs
append: true, // append object instead of overwriting
width: 320,
height: 240,
mode: "callback", // callback | save | stream
swffile: "jscam.swf",
quality: 85,
debug: function () {},
onCapture: function () {},
onTick: function () {},
onSave: function () {},
onLoad: function () {}
};
window.webcam = webcam;
$.fn.webcam = function(options) {
if (typeof options === "object") {
for (var ndx in webcam) {
if (options[ndx] !== undefined) {
webcam[ndx] = options[ndx];
}
}
}
var source = '<object id="XwebcamXobjectX" type="application/x-shockwave-flash" data="'+webcam.swffile+'" width="'+webcam.width+'" height="'+webcam.height+'"><param name="movie" value="'+webcam.swffile+'" /><param name="FlashVars" value="mode='+webcam.mode+'&quality='+webcam.quality+'" /><param name="allowScriptAccess" value="always" /></object>';
if (null !== webcam.extern) {
$(webcam.extern)[webcam.append ? "append" : "html"](source);
} else {
this[webcam.append ? "append" : "html"](source);
}
(_register = function(run) {
var cam = document.getElementById('XwebcamXobjectX');
if (cam.capture !== undefined) {
/* Simple callback methods are not allowed :-/ */
webcam.capture = function(x) {
try {
return cam.capture(x);
} catch(e) {}
}
webcam.save = function(x) {
try {
return cam.save(x);
} catch(e) {}
}
webcam.setCamera = function(x) {
try {
return cam.setCamera(x);
} catch(e) {}
}
webcam.getCameraList = function() {
try {
return cam.getCameraList();
} catch(e) {}
}
webcam.onLoad();
} else if (0 == run) {
webcam.debug("error", "Flash movie not yet registered!");
} else {
/* Flash interface not ready yet */
window.setTimeout(_register, 1000 * (4 - run), run - 1);
}
})(3);
}
})(jQuery);
| JavaScript |
/**
* jQuery webcam
* Copyright (c) 2010, Robert Eisele (robert@xarg.org)
* Dual licensed under the MIT or GPL Version 2 licenses.
* Date: 09/12/2010
*
* @author Robert Eisele
* @version 1.0
*
* @see http://www.xarg.org/project/jquery-webcam-plugin/
**/
(function ($) {
var webcam = {
extern: null, // external select token to support jQuery dialogs
append: true, // append object instead of overwriting
width: 320,
height: 240,
mode: "callback", // callback | save | stream
swffile: "jscam.swf",
quality: 85,
debug: function () {},
onCapture: function () {},
onTick: function () {},
onSave: function () {},
onLoad: function () {}
};
window.webcam = webcam;
$.fn.webcam = function(options) {
if (typeof options === "object") {
for (var ndx in webcam) {
if (options[ndx] !== undefined) {
webcam[ndx] = options[ndx];
}
}
}
var source = '<object id="XwebcamXobjectX" type="application/x-shockwave-flash" data="'+webcam.swffile+'" width="'+webcam.width+'" height="'+webcam.height+'"><param name="movie" value="'+webcam.swffile+'" /><param name="FlashVars" value="mode='+webcam.mode+'&quality='+webcam.quality+'" /><param name="allowScriptAccess" value="always" /></object>';
if (null !== webcam.extern) {
$(webcam.extern)[webcam.append ? "append" : "html"](source);
} else {
this[webcam.append ? "append" : "html"](source);
}
(_register = function(run) {
var cam = document.getElementById('XwebcamXobjectX');
if (cam.capture !== undefined) {
/* Simple callback methods are not allowed :-/ */
webcam.capture = function(x) {
try {
return cam.capture(x);
} catch(e) {}
}
webcam.save = function(x) {
try {
return cam.save(x);
} catch(e) {}
}
webcam.setCamera = function(x) {
try {
return cam.setCamera(x);
} catch(e) {}
}
webcam.getCameraList = function() {
try {
return cam.getCameraList();
} catch(e) {}
}
webcam.onLoad();
} else if (0 == run) {
webcam.debug("error", "Flash movie not yet registered!");
} else {
/* Flash interface not ready yet */
window.setTimeout(_register, 1000 * (4 - run), run - 1);
}
})(3);
}
})(jQuery);
| JavaScript |
/* JPEGCam v1.0.9 */
/* Webcam library for capturing JPEG images and submitting to a server */
/* Copyright (c) 2008 - 2009 Joseph Huckaby <jhuckaby@goldcartridge.com> */
/* Licensed under the GNU Lesser Public License */
/* http://www.gnu.org/licenses/lgpl.html */
/* Usage:
<script language="JavaScript">
document.write( webcam.get_html(320, 240) );
webcam.set_api_url( 'test.php' );
webcam.set_hook( 'onComplete', 'my_callback_function' );
function my_callback_function(response) {
alert("Success! PHP returned: " + response);
}
</script>
<a href="javascript:void(webcam.snap())">Take Snapshot</a>
*/
// Everything is under a 'webcam' Namespace
window.webcam = {
version: '1.0.9',
// globals
ie: !!navigator.userAgent.match(/MSIE/),
protocol: location.protocol.match(/https/i) ? 'https' : 'http',
callback: null, // user callback for completed uploads
swf_url: 'webcam.swf', // URI to webcam.swf movie (defaults to cwd)
shutter_url: 'shutter.mp3', // URI to shutter.mp3 sound
api_url: '', // URL to upload script
loaded: false, // true when webcam movie finishes loading
quality: 90, // JPEG quality (1 - 100)
shutter_sound: true, // shutter sound effect on/off
stealth: false, // stealth mode (do not freeze image upon capture)
hooks: {
onLoad: null,
onComplete: null,
onError: null
}, // callback hook functions
set_hook: function(name, callback) {
// set callback hook
// supported hooks: onLoad, onComplete, onError
if (typeof(this.hooks[name]) == 'undefined')
return alert("Hook type not supported: " + name);
this.hooks[name] = callback;
},
fire_hook: function(name, value) {
// fire hook callback, passing optional value to it
if (this.hooks[name]) {
if (typeof(this.hooks[name]) == 'function') {
// callback is function reference, call directly
this.hooks[name](value);
}
else if (typeof(this.hooks[name]) == 'array') {
// callback is PHP-style object instance method
this.hooks[name][0][this.hooks[name][1]](value);
}
else if (window[this.hooks[name]]) {
// callback is global function name
window[ this.hooks[name] ](value);
}
return true;
}
return false; // no hook defined
},
set_api_url: function(url) {
// set location of upload API script
this.api_url = url;
},
set_swf_url: function(url) {
// set location of SWF movie (defaults to webcam.swf in cwd)
this.swf_url = url;
},
get_html: function(width, height, server_width, server_height) {
// Return HTML for embedding webcam capture movie
// Specify pixel width and height (640x480, 320x240, etc.)
// Server width and height are optional, and default to movie width/height
if (!server_width) server_width = width;
if (!server_height) server_height = height;
var html = '';
var flashvars = 'shutter_enabled=' + (this.shutter_sound ? 1 : 0) +
'&shutter_url=' + escape(this.shutter_url) +
'&width=' + width +
'&height=' + height +
'&server_width=' + server_width +
'&server_height=' + server_height;
if (this.ie) {
html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+this.protocol+'://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="webcam_movie" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+this.swf_url+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/></object>';
}
else {
html += '<embed id="webcam_movie" src="'+this.swf_url+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="webcam_movie" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" />';
}
this.loaded = false;
return html;
},
get_movie: function() {
// get reference to movie object/embed in DOM
if (!this.loaded) return alert("ERROR: Movie is not loaded yet");
var movie = document.getElementById('webcam_movie');
if (!movie) alert("ERROR: Cannot locate movie 'webcam_movie' in DOM");
return movie;
},
set_stealth: function(stealth) {
// set or disable stealth mode
this.stealth = stealth;
},
snap: function(url, callback, stealth) {
// take snapshot and send to server
// specify fully-qualified URL to server API script
// and callback function (string or function object)
if (callback) this.set_hook('onComplete', callback);
if (url) this.set_api_url(url);
if (typeof(stealth) != 'undefined') this.set_stealth( stealth );
try{
this.get_movie()._snap( this.api_url, this.quality, this.shutter_sound ? 1 : 0, this.stealth ? 1 : 0 );
} catch(e) {
alert('ERROR in getmovue '+e);
}
},
freeze: function() {
// freeze webcam image (capture but do not upload)
this.get_movie()._snap('', this.quality, this.shutter_sound ? 1 : 0, 0 );
},
upload: function(url, callback) {
// upload image to server after taking snapshot
// specify fully-qualified URL to server API script
// and callback function (string or function object)
if (callback) this.set_hook('onComplete', callback);
if (url) this.set_api_url(url);
this.get_movie()._upload( this.api_url );
},
reset: function() {
// reset movie after taking snapshot
this.get_movie()._reset();
},
configure: function(panel) {
// open flash configuration panel -- specify tab name:
// "camera", "privacy", "default", "localStorage", "microphone", "settingsManager"
if (!panel) panel = "camera";
this.get_movie()._configure(panel);
},
set_quality: function(new_quality) {
// set the JPEG quality (1 - 100)
// default is 90
this.quality = new_quality;
},
set_shutter_sound: function(enabled, url) {
// enable or disable the shutter sound effect
// defaults to enabled
this.shutter_sound = enabled;
this.shutter_url = url ? url : 'shutter.mp3';
},
flash_notify: function(type, msg) {
// receive notification from flash about event
switch (type) {
case 'flashLoadComplete':
// movie loaded successfully
this.loaded = true;
this.fire_hook('onLoad');
break;
case 'error':
// HTTP POST error most likely
if (!this.fire_hook('onError', msg)) {
alert("JPEGCam Flash Error: " + msg);
}
break;
case 'success':
// upload complete, execute user callback function
// and pass raw API script results to function
this.fire_hook('onComplete', msg.toString());
break;
default:
// catch-all, just in case
alert("jpegcam flash_notify: " + type + ": " + msg);
break;
}
}
};
| JavaScript |
function ajaxGet(strURL, inputArgs, successFunc) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
successFunc(self.xmlHttpReq.responseText);
}
};
self.xmlHttpReq.send(inputArgs);
}
function popupdemo()
{
alert('This is Demo Popup');
} | JavaScript |
/**
* jQuery webcam
* Copyright (c) 2010, Robert Eisele (robert@xarg.org)
* Dual licensed under the MIT or GPL Version 2 licenses.
* Date: 09/12/2010
*
* @author Robert Eisele
* @version 1.0
*
* @see http://www.xarg.org/project/jquery-webcam-plugin/
**/
(function ($) {
var webcam = {
extern: null, // external select token to support jQuery dialogs
append: true, // append object instead of overwriting
width: 320,
height: 240,
mode: "callback", // callback | save | stream
swffile: "jscam.swf",
quality: 85,
debug: function () {},
onCapture: function () {},
onTick: function () {},
onSave: function () {},
onLoad: function () {}
};
window.webcam = webcam;
$.fn.webcam = function(options) {
if (typeof options === "object") {
for (var ndx in webcam) {
if (options[ndx] !== undefined) {
webcam[ndx] = options[ndx];
}
}
}
var source = '<object id="XwebcamXobjectX" type="application/x-shockwave-flash" data="'+webcam.swffile+'" width="'+webcam.width+'" height="'+webcam.height+'"><param name="movie" value="'+webcam.swffile+'" /><param name="FlashVars" value="mode='+webcam.mode+'&quality='+webcam.quality+'" /><param name="allowScriptAccess" value="always" /></object>';
if (null !== webcam.extern) {
$(webcam.extern)[webcam.append ? "append" : "html"](source);
} else {
this[webcam.append ? "append" : "html"](source);
}
(_register = function(run) {
var cam = document.getElementById('XwebcamXobjectX');
if (cam.capture !== undefined) {
/* Simple callback methods are not allowed :-/ */
webcam.capture = function(x) {
try {
return cam.capture(x);
} catch(e) {}
}
webcam.save = function(x) {
try {
return cam.save(x);
} catch(e) {}
}
webcam.setCamera = function(x) {
try {
return cam.setCamera(x);
} catch(e) {}
}
webcam.getCameraList = function() {
try {
return cam.getCameraList();
} catch(e) {}
}
webcam.onLoad();
} else if (0 == run) {
webcam.debug("error", "Flash movie not yet registered!");
} else {
/* Flash interface not ready yet */
window.setTimeout(_register, 1000 * (4 - run), run - 1);
}
})(3);
}
})(jQuery);
| JavaScript |
/**
* jQuery webcam
* Copyright (c) 2010, Robert Eisele (robert@xarg.org)
* Dual licensed under the MIT or GPL Version 2 licenses.
* Date: 09/12/2010
*
* @author Robert Eisele
* @version 1.0
*
* @see http://www.xarg.org/project/jquery-webcam-plugin/
**/
(function ($) {
var webcam = {
extern: null, // external select token to support jQuery dialogs
append: true, // append object instead of overwriting
width: 320,
height: 240,
mode: "callback", // callback | save | stream
swffile: "jscam.swf",
quality: 85,
debug: function () {},
onCapture: function () {},
onTick: function () {},
onSave: function () {},
onLoad: function () {}
};
window.webcam = webcam;
$.fn.webcam = function(options) {
if (typeof options === "object") {
for (var ndx in webcam) {
if (options[ndx] !== undefined) {
webcam[ndx] = options[ndx];
}
}
}
var source = '<object id="XwebcamXobjectX" type="application/x-shockwave-flash" data="'+webcam.swffile+'" width="'+webcam.width+'" height="'+webcam.height+'"><param name="movie" value="'+webcam.swffile+'" /><param name="FlashVars" value="mode='+webcam.mode+'&quality='+webcam.quality+'" /><param name="allowScriptAccess" value="always" /></object>';
if (null !== webcam.extern) {
$(webcam.extern)[webcam.append ? "append" : "html"](source);
} else {
this[webcam.append ? "append" : "html"](source);
}
(_register = function(run) {
var cam = document.getElementById('XwebcamXobjectX');
if (cam.capture !== undefined) {
/* Simple callback methods are not allowed :-/ */
webcam.capture = function(x) {
try {
return cam.capture(x);
} catch(e) {}
}
webcam.save = function(x) {
try {
return cam.save(x);
} catch(e) {}
}
webcam.setCamera = function(x) {
try {
return cam.setCamera(x);
} catch(e) {}
}
webcam.getCameraList = function() {
try {
return cam.getCameraList();
} catch(e) {}
}
webcam.onLoad();
} else if (0 == run) {
webcam.debug("error", "Flash movie not yet registered!");
} else {
/* Flash interface not ready yet */
window.setTimeout(_register, 1000 * (4 - run), run - 1);
}
})(3);
}
})(jQuery);
| JavaScript |
function taust(asi1, col1)
{ asi1.bgColor = col1; } | JavaScript |
var xmlHttp;
/******************************************************************************
variable to keep track if the page is changed
*****************************************************************************/
var pageChanged = false;
/******************************************************************************
variable to keep track no. of questions ansered
*****************************************************************************/
var answeredCount=0;
/******************************************************************************
*FunctionName :isblank()
*Description :The function to check if the given string is blank
*Input Parameters :sring to be schecked for blank
*Returns :true if blank else false
*****************************************************************************/
function isblank(s){
for(var i = 0; i < s.length; i++){
var c = s.charAt(i);
if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
}
return true;
}
/******************************************************************************
*FunctionName :verify()
*Description :the function to verify the values given in form are
not empty
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function verify(f){
var msg;
var empty_fields = "";
for(var i = 0; i < f.length; i++){
var e = f.elements[i];
if (((e.type == "text") || (e.type == "password")) && !e.optional){
// first check if the field is empty
if ((e.value == null) || (e.value == "") || isblank(e.value)) {
if(e.name == "uid"){
empty_fields += "\n" + "User name";
}else if(e.name == "strPassword"){
empty_fields += "\n" + "Password";
}
continue;
}
}
}
if (!empty_fields){
loginSubmit(f);
}
if (empty_fields) {
msg = "The following required field(s) are empty:"
+ empty_fields + "\n";
}
if (empty_fields) {
alert(msg);
document.login.action="login.jsp"
return false;
}
return true;
}
/******************************************************************************
*FunctionName :verify_1()
*Description :the function to verify the values given in form are
not empty
*Input Parameters :chnage password form name
*Returns :none
*****************************************************************************/
function verify_1(f){
var msg;
var empty_fields = "";
for(var i = 0; i < f.length; i++){
var e = f.elements[i];
if (((e.type == "text") || (e.type == "password")) && !e.optional){
// first check if the field is empty
if ((e.value == null) || (e.value == "") || isblank(e.value)) {
if(e.name == "uid"){
empty_fields += "\n" + "User name";
}else if(e.name == "strPassword"){
empty_fields += "\n" + "Password";
}else if(e.name == "newPassword"){
empty_fields += "\n" + "NEW Password";
}else if(e.name == "confirmPassword"){
empty_fields += "\n" + " Confirm Password";
}
continue;
}
}
}
if (!empty_fields){
loginSubmit(f);
}
if (empty_fields) {
msg = "The following required field(s) are empty:"
+ empty_fields + "\n";
}
if (empty_fields) {
alert(msg);
document.login.action="changepassword.jsp"
return false;
}
return true;
}
/******************************************************************************
*FunctionName :verify_1()
*Description :the function to verify the values given in form are
not empty
*Input Parameters :add new user form name
*Returns :none
*****************************************************************************/
function verify_2(f){
var msg;
var empty_fields = "";
var password = "";
var uid="";
for(var i = 0; i < f.length; i++){
var e = f.elements[i];
if (((e.type == "text") || (e.type == "password")) && !e.optional){
// first check if the field is empty
if ((e.value == null) || (e.value == "") || isblank(e.value)) {
if(e.name == "uid"){
empty_fields += "\n" + "User name";
uid=e.value;
}else if(e.name == "Password"){
empty_fields += "\n" + "Password";
password=e.value;
}else if(e.name == "confirmPassword"){
empty_fields += "\n" + " Confirm Password";
}
}
}
if(e.name == "uid"){
uid=e.value;
}
else if(e.name == "Password"){
password=e.value;
}
if(e.name == "invalidusername" && e.value==uid)
{
empty_fields += "\n" + " User Id Already Present";
}else if(e.name == "confirmPassword" && e.value != password){
empty_fields += "\n" + " Password and Confirm Password Don't Match";
}
if(e.name == "usertype" && e.value == -1)
{
empty_fields += "\n" + " User Type";
}
}
/*if(f.elements[3].value=="-1")
{
empty_fields += "\n" + " USER TYPE";
}
if(f.elements[1].value!=f.elements[2].value)
{
empty_fields += "\n" + "!! Password and confirm password dosent match!!!";
}*/
if (!empty_fields){
loginSubmit(f);
}
if (empty_fields) {
msg = "The following required field(s) are empty:"
+ empty_fields + "\n";
}
if (empty_fields) {
alert(msg);
document.login.action="addnewuser.jsp"
return false;
}
return true;
}
/******************************************************************************
*FunctionName :verify_3()
*Description :the function to verify the values given in form are
not empty
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function verify_3(f){
var msg;
var empty_fields = "";
var sexchecked=false;
for(var i = 0; i < f.length; i++){
var e = f.elements[i];
if (((e.type == "text") ) && !e.optional){
// first check if the field is empty
if ((e.value == null) || (e.value == "") || isblank(e.value)) {
if(e.name == "firstname"){
empty_fields += "\n" + "First Name";
}else if(e.name == "lastname"){
empty_fields += "\n" + "Last Name";
}
else if(e.name == "address"){
empty_fields += "\n" + "Address";
}else if(e.name == "idcardtype"){
empty_fields += "\n" + "ID Card Type";
}else if(e.name == "idcardno"){
empty_fields += "\n" + "Id Card Number";
}else if(e.name == "medical"){
empty_fields += "\n" + "Medical Problem";
}
continue;
}
}
if(e.name == "profession" && e.value == -1)
{
empty_fields += "\n" + " Patient Profession";
}
else if(e.name == "sex" && e.checked==true)
{
sexchecked=true;
f.elements["patientsex"].value=e.value;
}
}
if(sexchecked==false)
{
empty_fields += "\n" + " SEX";
}
if (!empty_fields){
loginSubmit(f);
}
if (empty_fields) {
msg = "The following required field(s) are empty:"
+ empty_fields + "\n";
}
if (empty_fields) {
alert(msg);
//document.login.action="addnewpatient.jsp";
return false;
}
return true;
}
/******************************************************************************
*FunctionName :verify_3()
*Description :the function to verify the values given in form are
not empty
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function verify_4(f){
var msg;
var empty_fields = "";
var sexchecked=false;
for(var i = 0; i < f.length; i++){
var e = f.elements[i];
if (((e.type == "text") ) && !e.optional){
// first check if the field is empty
if ((e.value == null) || (e.value == "") || isblank(e.value)) {
if(e.name == "roomno"){
empty_fields += "\n" + "Room Number";
}else if(e.name == "charges"){
empty_fields += "\n" + "Room Charges";
}
continue;
}
}
if(e.name == "dom" && e.checked==true)
{
sexchecked=true;
f.elements["isdom"].value=e.value;
}
}
if(sexchecked==false)
{
empty_fields += "\n" + " IS Dom";
}
if (!empty_fields){
loginSubmit(f);
}
if (empty_fields) {
msg = "The following required field(s) are empty:"
+ empty_fields + "\n";
}
if (empty_fields) {
alert(msg);
document.login.action="addnewroom.jsp";
return false;
}
return true;
}
/******************************************************************************
*FunctionName :verify_3()
*Description :the function to verify the values given in form are
not empty
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function verify_5(f){
var msg;
var empty_fields = "";
var sexchecked=false;
for(var i = 0; i < f.length; i++){
var e = f.elements[i];
if (((e.type == "text") ) && !e.optional){
// first check if the field is empty
if ((e.value == null) || (e.value == "") || isblank(e.value)) {
if(e.name == "bedno"){
empty_fields += "\n" + "Bed Number";
}else if(e.name == "charges"){
empty_fields += "\n" + "Room Charges";
}
continue;
}
}
}
if (!empty_fields){
loginSubmit(f);
}
if (empty_fields) {
msg = "The following required field(s) are empty:"
+ empty_fields + "\n";
}
if (empty_fields) {
alert(msg);
document.login.action="addnewbed.jsp";
return false;
}
return true;
}
/******************************************************************************
*FunctionName :verifyWelcome()
*Description :the function to verify the values given in form are
not empty
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function verifyWelcome(f){
var msg;
var empty_fields = "";
for(var i = 0; i < f.length; i++){
var e = f.elements[i];
if (e.type == "select" && !e.optional){
// first check if the field is empty
if ((!e.value == null) || !(e.value == "") || !isblank(e.value)) {
if(e.name == "userType"){
empty_fields += "\n" + "User Type";
}
continue;
}
}
}
if (!empty_fields){
welcomeSubmit(f);
}
if (empty_fields) {
msg = "The following required field(s) are empty:"
+ empty_fields + "\n";
}
if (empty_fields) {
alert(msg);
return false;
}
}
/******************************************************************************
*FunctionName :verifyExamDetails()
*Description :the function to verify the values given in form are
not empty
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function verifyExamDetails(f){
detailsSubmit(f);
}
/******************************************************************************
*FunctionName :submitAddQuestions()
*Description :the function to verify the values given in form are
not empty
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function submitAddQuestions(f){
var msg;
var empty_fields = "";
for(var i = 0; i < f.length; i++){
var e = f.elements[i];
if ((e.type == "text") && !e.optional){
// first check if the field is empty
if ((e.value == null) || (e.value == "") || isblank(e.value)) {
if(e.name == "examType"){
empty_fields += "\n" + "Exam type";
}else if(e.name == "question"){
empty_fields += "\n" + "question";
}else if(e.name == "answerOptions"){
empty_fields += "\n" + "answerOptions";
}else if(e.name == "correctAnswer"){
empty_fields += "\n" + "correctAnswer";
}
continue;
}
}
}
if (!empty_fields){
addQuestionSubmit(f);
}
if (empty_fields) {
msg = "The following required field(s) are empty:"
+ empty_fields + "\n";
}
if (empty_fields) {
alert(msg);
return false;
}
}
/******************************************************************************
*FunctionName :loginSubmit()
*Description :The function submit the login form
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function loginSubmit(formName){
document.getElementById("event").value = "loginEvent";
formName.submit();
}
/******************************************************************************
*FunctionName :detailsSubmit()
*Description :The function submit the exam details form
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function detailsSubmit(formName){
document.getElementById("event").value = "examDetails";
formName.submit();
}
/******************************************************************************
*FunctionName :welcomeSubmit()
*Description :The function submit the welcome form
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function welcomeSubmit(formName){
document.getElementById("event").value = "welcomeEvent";
formName.submit();
}
/******************************************************************************
*FunctionName :addQuestionSubmit()
*Description :The function submit the welcome form
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function addQuestionSubmit(formName){
document.getElementById("event").value = "questionEvent";
formName.submit();
}
function editQuesAnswer(formName){
document.getElementById("event").value = "editQuesAnswerEvent";
formName.submit();
}
/******************************************************************************
*FunctionName :submitExamType()
*Description :The function to submit the exam type and open
questions window
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function submitExamType(formName){
if(formName.examtype.options[0].selected){
alert("Please select an examination type")
return;
}
else{
var selectedVal = formName.examtype.value;
window.opener= "x";
window.close();
questionsWindow= window.open("/OnlineExamination/examServlet?event=fetchquestionsEvent&examtype="+selectedVal, "QuestionsWindow",
"location=1,status=1,scrollbars=1,toolbar=0,resizable=1,width=screen.availWidth,height=screen.availHeight,menubar=0,fullscreen=1");
questionsWindow.moveTo(0,0);
}
}
/******************************************************************************
*FunctionName :submitViewReport()
*Description :The function to submit the exam type and open
questions window
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function submitViewReport(formName){
if(formName.examtype.options[0].selected){
alert("Please select an examination type")
return;
}
else{
var selectedVal = formName.examtype.value;
document.getElementById("event").value = "reportGenerateEvent";
formName.submit();
}
}
/******************************************************************************
*FunctionName :submitViewReport()
*Description :The function to submit the exam type and open
questions window
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function submitUser(formName){
if(formName.selectUser.options[0].selected){
alert("Please Select a User")
return;
}
else{
var selectedVal = formName.selectUser.value;
document.getElementById("event").value = "selectUserEvent";
formName.submit();
}
}
/******************************************************************************
*FunctionName :submitUserExam()
*Description :The function to submit the exam type and open
questions window
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function submitUserExam(formName){
if(formName.selectUser.options[0].selected){
alert("Please select a User")
}else if(formName.examtype.options[0].selected){
alert("Please select examId")
return;
}
else{
var selectedVal = formName.selectUser.value;
var selectVal = formName.examtype.value;
document.getElementById("event").value = "selectUserExamEvent";
formName.submit();
}
}
/******************************************************************************
*FunctionName :submitUserExam()
*Description :The function to submit the exam type and open
questions window
*Input Parameters :form name
*Returns :none
*****************************************************************************/
function deleteEdit(formName){
if(formName.examtype.options[0].selected){
alert("Please select Exam for Edit")
return;
}
else{
document.getElementById("event").value = "editDeleteEvent";
formName.submit();
}
}
function selectExamForDeletion(formName){
if(formName.examtype.options[0].selected){
alert("Please Select Exam for Deactivation")
return;
}
else{
document.getElementById("event").value = "QuesDeleteEvent";
formName.submit();
}
}
function selectExamForActive(formName){
if(formName.examtype.options[0].selected){
alert("Please select Exam for Activation")
return;
}
else{
document.getElementById("event").value = "QuesActiveEvent";
formName.submit();
}
}
function deletQues(formName){
var radioOptns = document.getElementsByName("radioBut");
for(var i=0;i<radioOptns.length;i++) {
if(radioOptns[i].checked == true)
{
document.getElementById("event").value = "deleteQuesEvent";
formName.submit();
}
}
}
function ActivateQues(formName){
var radioOptns = document.getElementsByName("radioBut");
for(var i=0;i<radioOptns.length;i++) {
if(radioOptns[i].checked == true)
{
document.getElementById("event").value = "activeQuesEvent";
formName.submit();
}
}
}
function deleteAnswer(formName){
var count = 0;
var inputElems = document.getElementsByTagName("input");
for(var i=0;i<inputElems.length;i++) {
if(inputElems[i].type == "checkbox" ) {
if(inputElems[i].checked == true){
count = count+1;
}
}
}
if(count == 0){
alert("Please select some answers to be deleted")
return false;
}else {
document.getElementById("event").value = "deleteEditQuesEvent";
formName.submit();
}
}
function editAQuestion(formName){
var radioOptns = document.getElementsByName("radioBut");
for(var i=0;i<radioOptns.length;i++) {
if(radioOptns[i].checked == true)
{
document.getElementById("event").value = "editQuesEvent";
formName.submit();
}
}
}
/****************************************************************************
*****************************************************************************/
/****************************************************************************
*****************************************************************************/
function userExamMap(f){
var selectType = document.getElementById('examType').value;
var count = 0;
var inputElems = document.getElementsByTagName("input");
for(var i=0;i<inputElems.length;i++) {
if(inputElems[i].type == "checkbox" ) {
if(inputElems[i].checked == true){
count = count+1;
}
}
}
if(count == 0){
alert("Please select some users to be mapped")
return false;
}else if(selectType == -1) {
alert("please select exam type");
document.getElementById('examType').focus;
return false;
}
else{
document.getElementById("event").value = "userMapEvent";
frmUserExam.submit();
}
}
/******************************************************************************
*FunctionName :autoSubmit()
*Description :The function to auto submit the form after
specified duration
*Input Parameters :none
*Returns :none
*****************************************************************************/
function autoSubmit(){
alert("Exam duration is finished. Form will be autosubmitted");
//if(document.getElementById("timeOut").Value="true";
document.questions.action="/OnlineExamination/examServlet";
//alert(document.questions2.action);
document.getElementById("currTime").value=gCurrTime;
document.getElementById("event").value = "calculateResultEvent";
document.questions.submit();
//alert("Exam duration is finished. Form will be autosubmitted");
//document.form[0].submit();
displayTime(0);
clearTimeout(time);
//fnValidate1(true);
}
/******************************************************************************
*FunctionName :returnHome()
*Description :The function to return to login page frmo home button
click
*Input Parameters :none
*Returns :none
*****************************************************************************/
function returnHome(){
var obj=document.getElementById("examtype");
if(obj.value != -1) {
if(confirm("The choice you have made will be lost..."))
document.location.href="jsp/Login.jsp";
else
return;
}
else
document.location.href="jsp/Login.jsp";
}
/******************************************************************************
*FunctionName :examTypeSelected()
*Description :The function to check any of the exam type is selected
*Input Parameters :none
*Returns :none
*****************************************************************************/
function examTypeSelected(){
pageChanged = true;
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("copy").innerHTML=xmlHttp.responseText;
}
}
function useridcheck(str)
{
//alert("Button Pressed");
if (str.length==0)
{
//alert("length is zero");
document.getElementById("copy").innerHTML="";
return;
}
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="checkusernames.jsp";
url=url+"?q="+str;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function searchpatient(str)
{
//alert("Button Pressed");
/*if (str.length==0)
{
//alert("length is zero");
document.getElementById("copy").innerHTML="";
return;
}*/
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="searchpatient.jsp";
url=url+"?q="+str;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
| JavaScript |
function openWindow(url, width, height)
{
if ((width + 30 > screen.width) || (height + 60 > screen.height))
{
width = width + 50;
if (width > screen.width - 80)
width = screen.width - 80;
height = height + 50;
if (height > screen.height - 110)
height = screen.height - 110;
popupWin = window.open(url, "Image", "resizable,scrollbars,width=" + width + ",height=" + height + ",top=40,left=40,screenX=40,screenY=40");
}
else
{
width = width + 18;
height = height + 26;
popupWin = window.open(url, "Image", "resizable,width=" + width + ",height=" + height + ",top=40,left=40,screenX=40,screenY=40");
}
}
function imageover(file)
{
document.form1.img1.src = file;
}
function contents(file)
{
self.location.replace(file);
}
function mHigh()
{
event.srcElement.style.filter = "invert";
}
function mBack()
{
event.srcElement.style.filter = "";
}
| JavaScript |
<!--
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_swapImgRestore() { //v3.0
var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_findObj(n, d) { //v4.01
var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
//--> | JavaScript |
/* JPEGCam v1.0.9 */
/* Webcam library for capturing JPEG images and submitting to a server */
/* Copyright (c) 2008 - 2009 Joseph Huckaby <jhuckaby@goldcartridge.com> */
/* Licensed under the GNU Lesser Public License */
/* http://www.gnu.org/licenses/lgpl.html */
/* Usage:
<script language="JavaScript">
document.write( webcam.get_html(320, 240) );
webcam.set_api_url( 'test.php' );
webcam.set_hook( 'onComplete', 'my_callback_function' );
function my_callback_function(response) {
alert("Success! PHP returned: " + response);
}
</script>
<a href="javascript:void(webcam.snap())">Take Snapshot</a>
*/
// Everything is under a 'webcam' Namespace
window.webcam = {
version: '1.0.9',
// globals
ie: !!navigator.userAgent.match(/MSIE/),
protocol: location.protocol.match(/https/i) ? 'https' : 'http',
callback: null, // user callback for completed uploads
swf_url: 'scripts/webcam/webcam.swf', // URI to webcam.swf movie (defaults to cwd)
shutter_url: 'scripts/webcam/shutter.mp3', // URI to shutter.mp3 sound
api_url: '', // URL to upload script
loaded: false, // true when webcam movie finishes loading
quality: 90, // JPEG quality (1 - 100)
shutter_sound: true, // shutter sound effect on/off
stealth: false, // stealth mode (do not freeze image upon capture)
hooks: {
onLoad: null,
onComplete: null,
onError: null
}, // callback hook functions
set_hook: function(name, callback) {
// set callback hook
// supported hooks: onLoad, onComplete, onError
if (typeof(this.hooks[name]) == 'undefined')
return alert("Hook type not supported: " + name);
this.hooks[name] = callback;
},
fire_hook: function(name, value) {
// fire hook callback, passing optional value to it
if (this.hooks[name]) {
if (typeof(this.hooks[name]) == 'function') {
// callback is function reference, call directly
this.hooks[name](value);
}
else if (typeof(this.hooks[name]) == 'array') {
// callback is PHP-style object instance method
this.hooks[name][0][this.hooks[name][1]](value);
}
else if (window[this.hooks[name]]) {
// callback is global function name
window[ this.hooks[name] ](value);
}
return true;
}
return false; // no hook defined
},
set_api_url: function(url) {
// set location of upload API script
this.api_url = url;
},
set_swf_url: function(url) {
// set location of SWF movie (defaults to webcam.swf in cwd)
this.swf_url = url;
},
get_html: function(width, height, server_width, server_height) {
// Return HTML for embedding webcam capture movie
// Specify pixel width and height (640x480, 320x240, etc.)
// Server width and height are optional, and default to movie width/height
if (!server_width) server_width = width;
if (!server_height) server_height = height;
var html = '';
var flashvars = 'shutter_enabled=' + (this.shutter_sound ? 1 : 0) +
'&shutter_url=' + escape(this.shutter_url) +
'&width=' + width +
'&height=' + height +
'&server_width=' + server_width +
'&server_height=' + server_height;
if (this.ie) {
html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+this.protocol+'://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="webcam_movie" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+this.swf_url+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/></object>';
}
else {
html += '<embed id="webcam_movie" src="'+this.swf_url+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="webcam_movie" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" />';
}
this.loaded = false;
return html;
},
get_movie: function() {
// get reference to movie object/embed in DOM
if (!this.loaded) return alert("ERROR: Movie is not loaded yet");
var movie = document.getElementById('webcam_movie');
if (!movie) alert("ERROR: Cannot locate movie 'webcam_movie' in DOM");
return movie;
},
set_stealth: function(stealth) {
// set or disable stealth mode
this.stealth = stealth;
},
snap: function(url, callback, stealth) {
// take snapshot and send to server
// specify fully-qualified URL to server API script
// and callback function (string or function object)
if (callback) this.set_hook('onComplete', callback);
if (url) this.set_api_url(url);
if (typeof(stealth) != 'undefined') this.set_stealth( stealth );
this.get_movie()._snap( this.api_url, this.quality, this.shutter_sound ? 1 : 0, this.stealth ? 1 : 0 );
},
freeze: function() {
// freeze webcam image (capture but do not upload)
this.get_movie()._snap('', this.quality, this.shutter_sound ? 1 : 0, 0 );
},
upload: function(url, callback) {
// upload image to server after taking snapshot
// specify fully-qualified URL to server API script
// and callback function (string or function object)
if (callback) this.set_hook('onComplete', callback);
if (url) this.set_api_url(url);
this.get_movie()._upload( this.api_url );
},
reset: function() {
// reset movie after taking snapshot
this.get_movie()._reset();
},
configure: function(panel) {
// open flash configuration panel -- specify tab name:
// "camera", "privacy", "default", "localStorage", "microphone", "settingsManager"
if (!panel) panel = "camera";
this.get_movie()._configure(panel);
},
set_quality: function(new_quality) {
// set the JPEG quality (1 - 100)
// default is 90
this.quality = new_quality;
},
set_shutter_sound: function(enabled, url) {
// enable or disable the shutter sound effect
// defaults to enabled
this.shutter_sound = enabled;
this.shutter_url = url ? url : 'shutter.mp3';
},
flash_notify: function(type, msg) {
// receive notification from flash about event
switch (type) {
case 'flashLoadComplete':
// movie loaded successfully
this.loaded = true;
this.fire_hook('onLoad');
break;
case 'error':
// HTTP POST error most likely
if (!this.fire_hook('onError', msg)) {
alert("JPEGCam Flash Error: " + msg);
}
break;
case 'success':
// upload complete, execute user callback function
// and pass raw API script results to function
this.fire_hook('onComplete', msg.toString());
break;
default:
// catch-all, just in case
alert("jpegcam flash_notify: " + type + ": " + msg);
break;
}
}
};
| JavaScript |
var progressArea="progressArea";
var progressMessageHolder="progressMessageHolder";
A4J.AJAX.onError = function(req, status, message)
{
if(status==500)
{
window.alert("Your session has expired !\nError: "+message);
onAppTimeOut();
alert("Please LogIn again...");
document.location.href='LogIn.jsf';
}
// else
// window.alert("Server Error...\nMessage: "+message);
}
A4J.AJAX.onExpired = function(loc, expiredMsg){
if(window.confirm("Custom onExpired handler "+expiredMsg+" for a location: "+loc)){
return loc;
} else {
return false;
}
}
function setMessage(src,msg)
{
document.getElementById(src).innerHTML=msg;
}
function setVisible(src,flag)
{
if(flag)
document.getElementById(src).style.visibility="visible";
else
document.getElementById(src).style.visibility="hidden";
}
function showProgress(msg)
{
document.getElementById(progressMessageHolder).innerHTML=msg;
document.getElementById(progressArea).style.visibility="visible";
}
function hideProgress()
{
document.getElementById(progressArea).style.visibility="hidden";
}
/*
* Shows alert, converts each , with \n
*/
function showAlert(data)
{
var d = data.toString();
alert( d.replace(/;/g,"\n") );
}
/*
* Validate the characters entered as soon as they are entered
* Arguments
* Control inputObject : The input component object to work on
* Boolean flag : show alert or not
*/
function validateInteger(inputObject,flag,message)
{
var re = /[^0-9]/;
if (re.exec(inputObject.value))
{
if(flag)
alert(message);
inputObject.value = "0";
}
}
function validateDouble(inputObject,flag,message)
{
if ( isNaN(inputObject.value))
{
if(flag)
alert(message);
inputObject.value = "0";
}
}
function validateTimeRegular(inputObject,flag,message)
{
var re = /^((0[1-9])|(1[0-2])):[0-5][0-9] [aApP][mM]/;
if (!re.exec(inputObject.value))
{
if(flag)
alert(message);
//inputObject.value = "09:00 AM";
}
}
function validateTime(inputObject,flag,message)
{
var re = /^(([01][0-9])|(2[0-3])):[0-5][0-9]$/;
if (!re.exec(inputObject.value))
{
if(flag)
alert(message);
inputObject.value = "09:00";
}
}
// validate length of inputObject, if flag is set, popup alert
function validateLength(inputObject,size,flag,message)
{
var str ="";
try
{
if(inputObject.value.length>size)
{
if(flag)
alert(message);
str = inputObject.value.toString();
inputObject.value = str.substring(0, size);
}
}
catch(e)
{
}
return true;
}
// 'This Process is irreversible !!!\nAre you sure to submit ?'
function showConfirmation(message)
{
if(!confirm(message))
return false;
return true;
}
function showBusy()
{
Richfaces.showModalPanel('mpBusy');
}
function showWarning(msg)
{
var ele = document.getElementById('mpWarningMessage');
ele.innerHTML = "<span>"+ msg +"</span>";
Richfaces.showModalPanel('mpWarning');
}
function hideWarning()
{
Richfaces.hideModalPanel('mpWarning');
}
function showWarningAutoClose(msg,closeAfter)
{
showWarning(msg);
setTimeout("hideWarning()",closeAfter );
}
function hideBusy()
{
Richfaces.hideModalPanel('mpBusy');
}
function isTableEmpty(formId,tableId)
{
var table = document.getElementById(formId+':'+tableId);
var rowCount = table.rows.length;
return rowCount <= 0;
}
function showElement(eleId, flag)
{
if(flag)
{
document.getElementById(eleId).style.display='';
}
else
{
document.getElementById(eleId).style.display='none';
}
}
function toggleDisplay(eleId)
{
var displayStyle = document.getElementById(eleId).style.display;
if( "none" == displayStyle )
{
document.getElementById(eleId).style.display='';
}
else
{
document.getElementById(eleId).style.display='none';
}
}
function showLarge(ev,tar,url) {
var ee = document.getElementById('imageEnlarged');
ee.style.left = (ev.pageX + 50)+"px";
ee.style.top = (ev.pageY - 120 )+"px";
ee.src=url;
ee.style.visibility="visible";
}
function hideLarge() {
var ee = document.getElementById('imageEnlarged');
ee.src="";
ee.style.visibility="hidden";
}
function launchChildWindow(url) {
wopts = 'width=300,height=300,resizable=1,alwaysRaised=1,scrollbars=1';
var neww = window.open(url,'Popup',wopts);
if (window.focus) {neww.focus();}
}
function launchChildWindow(url) {
wopts = 'width=300,height=300,resizable=1,alwaysRaised=1,scrollbars=1';
var neww = window.open(url,'Popup',wopts);
if (window.focus) {neww.focus();}
}
| JavaScript |
/**
* jQuery webcam
* Copyright (c) 2010, Robert Eisele (robert@xarg.org)
* Dual licensed under the MIT or GPL Version 2 licenses.
* Date: 09/12/2010
*
* @author Robert Eisele
* @version 1.0
*
* @see http://www.xarg.org/project/jquery-webcam-plugin/
**/
(function ($) {
var webcam = {
extern: null, // external select token to support jQuery dialogs
append: true, // append object instead of overwriting
width: 320,
height: 240,
mode: "callback", // callback | save | stream
swffile: "jscam.swf",
quality: 85,
debug: function () {},
onCapture: function () {},
onTick: function () {},
onSave: function () {},
onLoad: function () {}
};
window.webcam = webcam;
$.fn.webcam = function(options) {
if (typeof options === "object") {
for (var ndx in webcam) {
if (options[ndx] !== undefined) {
webcam[ndx] = options[ndx];
}
}
}
var source = '<object id="XwebcamXobjectX" type="application/x-shockwave-flash" data="'+webcam.swffile+'" width="'+webcam.width+'" height="'+webcam.height+'"><param name="movie" value="'+webcam.swffile+'" /><param name="FlashVars" value="mode='+webcam.mode+'&quality='+webcam.quality+'" /><param name="allowScriptAccess" value="always" /></object>';
if (null !== webcam.extern) {
$(webcam.extern)[webcam.append ? "append" : "html"](source);
} else {
this[webcam.append ? "append" : "html"](source);
}
(_register = function(run) {
var cam = document.getElementById('XwebcamXobjectX');
if (cam.capture !== undefined) {
/* Simple callback methods are not allowed :-/ */
webcam.capture = function(x) {
try {
return cam.capture(x);
} catch(e) {}
}
webcam.save = function(x) {
try {
return cam.save(x);
} catch(e) {}
}
webcam.setCamera = function(x) {
try {
return cam.setCamera(x);
} catch(e) {}
}
webcam.getCameraList = function() {
try {
return cam.getCameraList();
} catch(e) {}
}
webcam.onLoad();
} else if (0 == run) {
webcam.debug("error", "Flash movie not yet registered!");
} else {
/* Flash interface not ready yet */
window.setTimeout(_register, 1000 * (4 - run), run - 1);
}
})(3);
}
})(jQuery);
| JavaScript |
/**
* jQuery webcam
* Copyright (c) 2010, Robert Eisele (robert@xarg.org)
* Dual licensed under the MIT or GPL Version 2 licenses.
* Date: 09/12/2010
*
* @author Robert Eisele
* @version 1.0
*
* @see http://www.xarg.org/project/jquery-webcam-plugin/
**/
(function ($) {
var webcam = {
extern: null, // external select token to support jQuery dialogs
append: true, // append object instead of overwriting
width: 320,
height: 240,
mode: "callback", // callback | save | stream
swffile: "jscam.swf",
quality: 85,
debug: function () {},
onCapture: function () {},
onTick: function () {},
onSave: function () {},
onLoad: function () {}
};
window.webcam = webcam;
$.fn.webcam = function(options) {
if (typeof options === "object") {
for (var ndx in webcam) {
if (options[ndx] !== undefined) {
webcam[ndx] = options[ndx];
}
}
}
var source = '<object id="XwebcamXobjectX" type="application/x-shockwave-flash" data="'+webcam.swffile+'" width="'+webcam.width+'" height="'+webcam.height+'"><param name="movie" value="'+webcam.swffile+'" /><param name="FlashVars" value="mode='+webcam.mode+'&quality='+webcam.quality+'" /><param name="allowScriptAccess" value="always" /></object>';
if (null !== webcam.extern) {
$(webcam.extern)[webcam.append ? "append" : "html"](source);
} else {
this[webcam.append ? "append" : "html"](source);
}
(_register = function(run) {
var cam = document.getElementById('XwebcamXobjectX');
if (cam.capture !== undefined) {
/* Simple callback methods are not allowed :-/ */
webcam.capture = function(x) {
try {
return cam.capture(x);
} catch(e) {}
}
webcam.save = function(x) {
try {
return cam.save(x);
} catch(e) {}
}
webcam.setCamera = function(x) {
try {
return cam.setCamera(x);
} catch(e) {}
}
webcam.getCameraList = function() {
try {
return cam.getCameraList();
} catch(e) {}
}
webcam.onLoad();
} else if (0 == run) {
webcam.debug("error", "Flash movie not yet registered!");
} else {
/* Flash interface not ready yet */
window.setTimeout(_register, 1000 * (4 - run), run - 1);
}
})(3);
}
})(jQuery);
| JavaScript |
/*
* Formy JS library
* by Luiszuno.com
*/
jQuery(document).ready(function($) {
// Hide messages
$("#formy-success").hide();
$("#formy-error").hide();
// on submit...
$("#formy #submit").click(function() {
// Required fields:
//name
var name = $("#name").val();
if(name == "" || name == "Name"){
$("#name").focus();
$("#formy-error").fadeIn().text("Name required");
return false;
}
//surname
var surname = $("#surname").val();
if(surname == "" || surname == "Surname"){
$("#surname").focus();
$("#formy-error").fadeIn().text("Surname required");
return false;
}
//surname
var phone = $("#phone").val();
if(phone == "" || phone == "Phone"){
$("#phone").focus();
$("#formy-error").fadeIn().text("Phone required");
return false;
}
// email
var email = $("#email").val();
if(email == "" || email == "Email address"){
$("#email").focus();
$("#error").fadeIn().text("Email required");
return false;
}
// comments
var comments = $("#comments").val();
if(comments == "" || comments == "Please type your comment or question"){
$("#comments").focus();
return false;
}
// send mail php
var sendMailUrl = $("#sendMailUrl").val();
// Retrieve values for to, from & subject at the form
var to = $("#to").val();
var from = $("#from").val();
var subject = $("#subject").val();
// Create the data string
var dataString = 'name='+ name
+ '&surname=' + surname
+ '&phone=' + phone
+ '&email=' + email
+ '&comments=' + comments
+ '&to=' + to
+ '&from=' + from
+ '&subject=' + subject;
// ajax
$.ajax({
type:"POST",
url: sendMailUrl,
data: dataString,
success: success()
});
});
// On success...
function success(){
$("#formy-success").fadeIn().text("Message sent, thank you!");
$("#formy-error").hide();
$("#formy").fadeOut();
return false;
}
return false;
});
| JavaScript |
/*
---
description: SIMPLE MODAL is a small plugin to create modal windows. It can be used to generate alert or confirm messages with few lines of code. Confirm configuration involves the use of callbacks to be applied to affirmative action;i t can work in asynchronous mode and retrieve content from external pages or getting the inline content.
license: MIT-style
authors:
- Marco Dell'Anna
- Juan Lago
requires:
- core/1.3: '*'
provides:
- SimpleModal
...
* Mootools Simple Modal
* Version 1.0
* Copyright (c) 2011 Marco Dell'Anna - http://www.plasm.it
*
* Version 1.1
* Copyright (c) 2013 Juan Lago - http://www.livespanske.com
*
* Requires:
* MooTools http://mootools.net
*
* 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.
*
* Log:
* 1.0 - Inizio implementazione release stabile [Tested on: ie7/ie8/ie9/Chrome/Firefox7/Safari]
* 1.1 - Extend functionality: Lightbox
*/
var SimpleModal = new Class({
// Implements
Implements: [Options],
request:null,
buttons:[],
// Protected section for lightbox
lightbox:{},
// Options
options: {
onAppend: Function, // callback inject in DOM
offsetTop: 40,
overlayOpacity:.3,
overlayColor: "#000000",
width: 400,
draggable: true,
keyEsc: true,
overlayClick: true,
closeButton: true, // X close button
hideHeader: false,
hideFooter: false,
lightboxExcessWidth:40, // Only for Modal Image (excess pixels created from skin)
lightboxExcessHeight:120, // Only for Modal Image (excess pixels created from skin)
btn_ok: "OK", // Label
btn_cancel: "Cancel", // Label
template:"<div class=\"simple-modal-header\"> \
<h1>{_TITLE_}</h1> \
</div> \
<div class=\"simple-modal-body\"> \
<div class=\"contents\">{_CONTENTS_}</div> \
</div> \
<div class=\"simple-modal-footer\"></div>"
},
/**
* Initialization
*/
initialize: function(options) {
//set options
this.setOptions(options);
},
/**
* public method show
* Open Modal
* @options: param to rewrite
* @return node HTML
*/
show: function(options){
if(!options) options = {};
// Require redraw?
options.draw = options.draw == undefined ? true : options.draw;
// Inserisce Overlay
if (options.draw)
this._overlay("show");
// Switch different modal
switch( options.model ){
// Require title && contents && callback
case "confirm":
// Add button confirm
this.addButton(this.options.btn_ok, "btn primary btn-margin", function(){
try{ options.callback() } catch(err){};
this.hide();
})
// Add button cancel
this.addButton(this.options.btn_cancel, "btn secondary");
// Rendering
var node = this._drawWindow(options);
// Add Esc Behaviour
this._addEscBehaviour();
break;
// Require title && contents (define the action buttons externally)
case "modal":
// Rendering
var node = this._drawWindow(options);
// Add Esc Behaviour
this._addEscBehaviour();
break;
// Require title && url contents (define the action buttons externally)
case "modal-ajax":
// Rendering
var node = this._drawWindow(options);
this._loadContents({
"url":options.param.url || "",
"onRequestComplete":options.param.onRequestComplete||Function
})
break;
// Require title, url contents, lightbox group and the order inside of the group
case "lightbox":
// lightbox require render the arrows
options.arrows = true;
// Set information about the current lightbox
this.lightbox.element = options.lightbox.element;
this.lightbox.group = options.lightbox.group;
this.lightbox.order = options.lightbox.order;
// Rendering
var node = this._drawWindow(options);
this._loadContents({
"url": options.param.url || "",
"order": this.lightbox.order,
"draw": options.draw,
"onRequestComplete": options.param.onRequestComplete||Function
});
break;
// Require title && contents
default:
// Alert
// Add button
this.addButton(this.options.btn_ok, "btn primary");
// Rendering
var node = this._drawWindow(options);
// Add Esc Behaviour
this._addEscBehaviour();
break;
}
// Custom size Modal
node.setStyles({width:this.options.width});
// Hide Header &&/|| Footer
if( this.options.hideHeader ) node.addClass("hide-header");
if( this.options.hideFooter ) node.addClass("hide-footer");
// Add Button X
if( this.options.closeButton ) this._addCloseButton();
// Enabled Drag Window
if( this.options.draggable ){
var headDrag = node.getElement(".simple-modal-header");
new Drag(node, { handle:headDrag });
// Set handle cursor
headDrag.setStyle("cursor", "move")
node.addClass("draggable");
}
// Resize Stage
this._display();
},
/**
* public method hide
* Close model window
* return
*/
hide: function(){
try{
if( typeof(this.request) == "object" ) this.request.cancel();
}catch(err){}
this._overlay('hide');
return;
},
/**
* private method _drawWindow
* Rendering window
* return node SM
*/
_drawWindow: function(options) {
var node;
if (options.draw)
{
// Add Node in DOM
node = new Element("div#simple-modal", {"class":"simple-modal"});
node.inject($$("body")[0]);
}
else
node = document.getElement('#simple-modal.simple-modal');
// Set Contents
var html = this._template(this.options.template, {"_TITLE_":options.title || "Untitled", "_CONTENTS_":options.contents || ""});
node.set("html", html);
// Add all buttons
this._injectAllButtons();
// Add arrows
if (options.arrows)
this._addArrows();
// Callback append
this.options.onAppend();
return node;
},
/**
* public method addButton
* Add button to Modal button array
* require @label:string, @classe:string, @clickEvent:event
* @return node HTML
*/
addButton: function(label, classe, clickEvent){
var bt = new Element('a',{
"title" : label,
"text" : label,
"class" : classe,
"events": {
click: (clickEvent || this.hide).bind(this)
}
});
this.buttons.push(bt);
return bt;
},
/**
* private method _injectAllButtons
* Inject all buttons in simple-modal-footer
* @return
*/
_injectAllButtons: function(){
this.buttons.each( function(e, i){
e.inject( $("simple-modal").getElement(".simple-modal-footer") );
});
return;
},
/**
* private method _addCloseButton
* Inject Close botton (X button)
* @return node HTML
*/
_addCloseButton: function(){
var b = new Element("a", {"class":"close", "href":"#", "html":"x"});
b.inject($("simple-modal"), "top");
// Aggiunge bottome X Close
b.addEvent("click", function(e){
if(e) e.stop();
this.hide();
}.bind( this ))
return b;
},
/**
* private method _addArrows
* Inject arrows (Left and Right arrows)
*/
_addArrows: function(){
// Create and inject next image button
var btnnext = new Element("a", {"class":"next-image", "style":"display:none", "href":"#", "html":"»"});
btnnext.inject($("simple-modal"), "top");
btnnext.addEvent("click", function(e){
if(e) e.stop();
this._viewNextElement();
}.bind(this));
// Create and inject previous image button
var btnprevious = new Element("a", {"class":"previous-image", "style":"display:none", "href":"#", "html":"«"});
btnprevious.inject($("simple-modal"), "top");
btnprevious.addEvent("click", function(e){
if(e) e.stop();
this._viewPreviousElement();
}.bind(this));
// Set visibility of arrows
this._setArrowsVisibility();
},
/**
* private method _viewNextElement
* Load the next element relative to the lightbox in the simple modal
*/
_viewNextElement: function(){
var elements = this._getElementsByGroup(this.lightbox.group);
this.lightbox.order++;
var next_element = elements[this.lightbox.order];
this.show({
"model": "lightbox",
"title": next_element.get('title'),
"draw": false, // Is not required redraw
"param":{
"url": next_element.get('href'),
"onRequestComplete": function(){ }
},
"lightbox": {
"element" : next_element,
"group": this.lightbox.group,
"order": this.lightbox.order
}
});
},
/**
* private method _viewPreviousElement
* Load the next element relative to the lightbox in the simple modal
*/
_viewPreviousElement: function(){
var elements = this._getElementsByGroup(this.lightbox.group);
this.lightbox.order--;
var previous_element = elements[this.lightbox.order];
this.show({
"model": "lightbox",
"title": previous_element.get('title'),
"draw": false, // Is not required redraw
"param":{
"url": previous_element.get('href'),
"onRequestComplete": function(){ }
},
"lightbox": {
"element" : previous_element,
"group": this.lightbox.group,
"order": this.lightbox.order
}
});
},
/**
* private method _setArrowsVisibility
* Automatically set the visibility of the Arrows
*/
_setArrowsVisibility: function(){
var left_arrow = document.getElement('.simple-modal a.previous-image');
var right_arrow = document.getElement('.simple-modal a.next-image');
var total_slides = this.getTotalByGroup(this.lightbox.group);
// Set visibility of the left arrow (Previous image)
if (this.lightbox.order == 0)
left_arrow.setStyle('display', 'none');
else
left_arrow.setStyle('display', 'inline');
// Set visibility of the right arrow (Next image)
if (total_slides > 0 && this.lightbox.order < total_slides - 1)
right_arrow.setStyle('display', 'inline');
else
right_arrow.setStyle('display', 'none');
},
/**
* private method _getElementsByGroup
* Retrieve all elements by group
* @options string Group Name
* @return DOM Nodes
*/
_getElementsByGroup: function(group) {
var links = $$("a").filter(function(el) {
return el.rel && el.rel.contains('simplemodal[' + group + ']');
});
return links;
},
/**
* public method _getTotalByGroup
* Count the number of lightboxes are in a certain group
* @options string Group Name
* @return integer Number of lightboxes by group
*/
getTotalByGroup: function(group) {
return this._getElementsByGroup(group).length;
},
/**
* private method _overlay
* Create/Destroy overlay and Modal
* @return
*/
_overlay: function(status) {
switch( status ) {
case 'show':
this._overlay('hide');
var overlay = new Element("div", {"id":"simple-modal-overlay"});
overlay.inject( $$("body")[0] );
overlay.setStyle("background-color", this.options.overlayColor);
overlay.fade("hide").fade(this.options.overlayOpacity);
// Behaviour
if( this.options.overlayClick){
overlay.addEvent("click", function(e){
if(e) e.stop();
this.hide();
}.bind(this))
}
// Add Control Resize
this.__resize = this._display.bind(this);
window.addEvent("resize", this.__resize );
break;
case 'hide':
// Remove Event Resize
window.removeEvent("resize", this._display);
// Remove Event Resize
if(this.options.keyEsc)
{
var fixEV = Browser.name != 'ie' ? "keydown" : "onkeydown";
window.removeEvent(fixEV, this._removeSM);
}
// Remove Overlay
try
{
$('simple-modal-overlay').destroy();
}
catch(err){}
// Remove Modal
try{
$('simple-modal').destroy();
}
catch(err){}
break;
}
return;
},
/**
* private method _loadContents
* Async request for modal ajax
* @return
*/
_loadContents: function(param){
// Set Loading
$('simple-modal').addClass("loading");
// Match image file
var re = new RegExp( /([^\/\\]+)\.(jpg|png|gif)$/i );
if( param.url.match(re) ){
// Hide Header/Footer
$('simple-modal').addClass("hide-footer");
// Remove All Event on Overlay
$("simple-modal-overlay").removeEvents(); // Prevent Abort
// Immagine
var images = [param.url];
new Asset.images(images, {
onProgress: function(i) {
immagine = this;
},
onComplete: function() {
try{
// Remove loading
$('simple-modal').removeClass("loading");
// Imposta dimensioni
var content = $('simple-modal').getElement(".simple-modal-body");
var padding = content.getStyle("padding").split(" ");
var width = immagine.get("width").toInt();
var height = immagine.get("height").toInt();
// Porportional scale
var ns = this._scaleImage(width, height);
width = ns.width
height = ns.height
// Width
var myFx1 = new Fx.Tween($("simple-modal"), {
duration: 'normal',
transition: 'sine:out',
link: 'cancel',
property: 'width'
}).start($("simple-modal").getCoordinates().width, width + padding[1].toInt() + padding[3].toInt() + $('simple-modal').getStyle('border-left-width').toInt() + $('simple-modal').getStyle('border-right-width').toInt())
// Height
var myFx2 = new Fx.Tween(content, {
duration: 'normal',
transition: 'sine:out',
link: 'cancel',
property: 'height'
}).start(content.getCoordinates().height, height).chain(function(){
// Inject
immagine.inject( $('simple-modal').getElement(".contents").empty() ).fade("hide").setStyles({"width":width, "height":height}).fade("in");
this._display();
// Add Esc Behaviour
this._addEscBehaviour();
}.bind(this));
// Left
var myFx3 = new Fx.Tween($("simple-modal"), {
duration: 'normal',
transition: 'sine:out',
link: 'cancel',
property: 'left'
}).start($("simple-modal").getCoordinates().left, (window.getCoordinates().width - width)/2);
}catch(err){}
}.bind(this)
});
}
else
{
// Request HTML
this.request = new Request.HTML({
evalScripts:false,
url: param.url,
method: 'get',
onRequest: function(){},
onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
$('simple-modal').removeClass("loading");
$('simple-modal').getElement(".contents").set("html", responseHTML);
param.onRequestComplete();
// Execute script page loaded
eval(responseJavaScript)
// Resize
this._display();
// Add Esc Behaviour
this._addEscBehaviour();
}.bind(this),
onFailure: function(){
$('simple-modal').removeClass("loading");
$('simple-modal').getElement(".contents").set("html", "loading failed")
}
}).send();
}
},
/**
* private method _scaleImage
* Calculate scale image proportional
* @return {width, height}
*/
_scaleImage: function(w, h){
var removeH = this.options.lightboxExcessHeight + this.options.offsetTop;
var removeW = this.options.lightboxExcessWidth;
var width = w ;
var height = h ;
var newWidth = window.getSize().x - removeW;
var newHeight = window.getSize().y - removeH;
ratio = (width <= height) ? height / newHeight : width / newWidth;
// Ratio
ratio = Math.max(ratio, 1.0);
// New sizes
w = parseInt(width / ratio);
h = parseInt(height / ratio);
return {"width":w, "height":h}
},
/**
* private method _display
* Move interface
* @return
*/
_display: function(){
// Update overlay
try{
$("simple-modal-overlay").setStyles({
height: window.getCoordinates().height //$$("body")[0].getScrollSize().y
});
}
catch(err){}
// Update position popup
try{
var offsetTop = this.options.offsetTop || 0; //this.options.offsetTop != null ? this.options.offsetTop : window.getScroll().y;
$("simple-modal").setStyles({
top: offsetTop,
left: ((window.getCoordinates().width - $("simple-modal").getCoordinates().width)/2 )
});
} catch(err){}
return;
},
/**
* private method _addEscBehaviour
* add Event ESC
* @return
*/
_addEscBehaviour: function(){
if(this.options.keyEsc){
this._removeSM = function(e){
if( e.key == "esc" ) this.hide();
}.bind(this)
// Remove Event Resize
if(this.options.keyEsc){
var fixEV = Browser.name != 'ie' ? "keydown" : "onkeydown";
window.addEvent(fixEV, this._removeSM );
}
}
},
/**
* private method _template
* simple template by Thomas Fuchs
* @return
*/
_template:function(s,d){
for(var p in d)
s=s.replace(new RegExp('{'+p+'}','g'), d[p]);
return s;
}
});
/**
* Lightbox loader
*/
SimpleModal.autoload = function() {
var links = $$("a").filter(function(el) {
return el.rel && el.rel.test(/^simplemodal/i);
});
var order = [];
// Instance to SimpleModal (One instance for all lightboxes)
var SM = new SimpleModal();
$$(links).each(function(el) {
// Obtain lightbox group
var relation= el.rel.replace(/[[]|]/gi," ");
var rel0 = relation.split(" ");
// Obtain order
order[rel0[1]] = order[rel0[1]] == null ? 0 : order[rel0[1]] + 1;
// Avoid group order as static var
var group_order = order[rel0[1]];
// Create custom event per link
el.addEvent('click', function(e) {
e.stop();
SM.show({
"model": "lightbox",
"title": this.get('title'),
"param":{
"url": this.get('href'),
"onRequestComplete": function(){ }
},
"lightbox": {
"element" : this,
"group": rel0[1],
"order": group_order
}
});
});
});
}
/**
* Lightbox boot
*/
window.addEvent("domready", SimpleModal.autoload); | JavaScript |
/*!
* Buttons helper for fancyBox
* version: 1.0.5 (Mon, 15 Oct 2012)
* @requires fancyBox v2.0 or later
*
* Usage:
* $(".fancybox").fancybox({
* helpers : {
* buttons: {
* position : 'top'
* }
* }
* });
*
*/
(function ($) {
//Shortcut for fancyBox object
var F = $.fancybox;
//Add helper object
F.helpers.buttons = {
defaults : {
skipSingle : false, // disables if gallery contains single image
position : 'top', // 'top' or 'bottom'
tpl : '<div id="fancybox-buttons"><ul><li><a class="btnPrev" title="Previous" href="javascript:;"></a></li><li><a class="btnPlay" title="Start slideshow" href="javascript:;"></a></li><li><a class="btnNext" title="Next" href="javascript:;"></a></li><li><a class="btnToggle" title="Toggle size" href="javascript:;"></a></li><li><a class="btnClose" title="Close" href="javascript:;"></a></li></ul></div>'
},
list : null,
buttons: null,
beforeLoad: function (opts, obj) {
//Remove self if gallery do not have at least two items
if (opts.skipSingle && obj.group.length < 2) {
obj.helpers.buttons = false;
obj.closeBtn = true;
return;
}
//Increase top margin to give space for buttons
obj.margin[ opts.position === 'bottom' ? 2 : 0 ] += 30;
},
onPlayStart: function () {
if (this.buttons) {
this.buttons.play.attr('title', 'Pause slideshow').addClass('btnPlayOn');
}
},
onPlayEnd: function () {
if (this.buttons) {
this.buttons.play.attr('title', 'Start slideshow').removeClass('btnPlayOn');
}
},
afterShow: function (opts, obj) {
var buttons = this.buttons;
if (!buttons) {
this.list = $(opts.tpl).addClass(opts.position).appendTo('body');
buttons = {
prev : this.list.find('.btnPrev').click( F.prev ),
next : this.list.find('.btnNext').click( F.next ),
play : this.list.find('.btnPlay').click( F.play ),
toggle : this.list.find('.btnToggle').click( F.toggle ),
close : this.list.find('.btnClose').click( F.close )
}
}
//Prev
if (obj.index > 0 || obj.loop) {
buttons.prev.removeClass('btnDisabled');
} else {
buttons.prev.addClass('btnDisabled');
}
//Next / Play
if (obj.loop || obj.index < obj.group.length - 1) {
buttons.next.removeClass('btnDisabled');
buttons.play.removeClass('btnDisabled');
} else {
buttons.next.addClass('btnDisabled');
buttons.play.addClass('btnDisabled');
}
this.buttons = buttons;
this.onUpdate(opts, obj);
},
onUpdate: function (opts, obj) {
var toggle;
if (!this.buttons) {
return;
}
toggle = this.buttons.toggle.removeClass('btnDisabled btnToggleOn');
//Size toggle button
if (obj.canShrink) {
toggle.addClass('btnToggleOn');
} else if (!obj.canExpand) {
toggle.addClass('btnDisabled');
}
},
beforeClose: function () {
if (this.list) {
this.list.remove();
}
this.list = null;
this.buttons = null;
}
};
}(jQuery));
| JavaScript |
/*!
* Thumbnail helper for fancyBox
* version: 1.0.7 (Mon, 01 Oct 2012)
* @requires fancyBox v2.0 or later
*
* Usage:
* $(".fancybox").fancybox({
* helpers : {
* thumbs: {
* width : 50,
* height : 50
* }
* }
* });
*
*/
(function ($) {
//Shortcut for fancyBox object
var F = $.fancybox;
//Add helper object
F.helpers.thumbs = {
defaults : {
width : 50, // thumbnail width
height : 50, // thumbnail height
position : 'bottom', // 'top' or 'bottom'
source : function ( item ) { // function to obtain the URL of the thumbnail image
var href;
if (item.element) {
href = $(item.element).find('img').attr('src');
}
if (!href && item.type === 'image' && item.href) {
href = item.href;
}
return href;
}
},
wrap : null,
list : null,
width : 0,
init: function (opts, obj) {
var that = this,
list,
thumbWidth = opts.width,
thumbHeight = opts.height,
thumbSource = opts.source;
//Build list structure
list = '';
for (var n = 0; n < obj.group.length; n++) {
list += '<li><a style="width:' + thumbWidth + 'px;height:' + thumbHeight + 'px;" href="javascript:jQuery.fancybox.jumpto(' + n + ');"></a></li>';
}
this.wrap = $('<div id="fancybox-thumbs"></div>').addClass(opts.position).appendTo('body');
this.list = $('<ul>' + list + '</ul>').appendTo(this.wrap);
//Load each thumbnail
$.each(obj.group, function (i) {
var href = thumbSource( obj.group[ i ] );
if (!href) {
return;
}
$("<img />").load(function () {
var width = this.width,
height = this.height,
widthRatio, heightRatio, parent;
if (!that.list || !width || !height) {
return;
}
//Calculate thumbnail width/height and center it
widthRatio = width / thumbWidth;
heightRatio = height / thumbHeight;
parent = that.list.children().eq(i).find('a');
if (widthRatio >= 1 && heightRatio >= 1) {
if (widthRatio > heightRatio) {
width = Math.floor(width / heightRatio);
height = thumbHeight;
} else {
width = thumbWidth;
height = Math.floor(height / widthRatio);
}
}
$(this).css({
width : width,
height : height,
top : Math.floor(thumbHeight / 2 - height / 2),
left : Math.floor(thumbWidth / 2 - width / 2)
});
parent.width(thumbWidth).height(thumbHeight);
$(this).hide().appendTo(parent).fadeIn(300);
}).attr('src', href);
});
//Set initial width
this.width = this.list.children().eq(0).outerWidth(true);
this.list.width(this.width * (obj.group.length + 1)).css('left', Math.floor($(window).width() * 0.5 - (obj.index * this.width + this.width * 0.5)));
},
beforeLoad: function (opts, obj) {
//Remove self if gallery do not have at least two items
if (obj.group.length < 2) {
obj.helpers.thumbs = false;
return;
}
//Increase bottom margin to give space for thumbs
obj.margin[ opts.position === 'top' ? 0 : 2 ] += ((opts.height) + 15);
},
afterShow: function (opts, obj) {
//Check if exists and create or update list
if (this.list) {
this.onUpdate(opts, obj);
} else {
this.init(opts, obj);
}
//Set active element
this.list.children().removeClass('active').eq(obj.index).addClass('active');
},
//Center list
onUpdate: function (opts, obj) {
if (this.list) {
this.list.stop(true).animate({
'left': Math.floor($(window).width() * 0.5 - (obj.index * this.width + this.width * 0.5))
}, 150);
}
},
beforeClose: function () {
if (this.wrap) {
this.wrap.remove();
}
this.wrap = null;
this.list = null;
this.width = 0;
}
}
}(jQuery)); | JavaScript |
/*!
* Media helper for fancyBox
* version: 1.0.6 (Fri, 14 Jun 2013)
* @requires fancyBox v2.0 or later
*
* Usage:
* $(".fancybox").fancybox({
* helpers : {
* media: true
* }
* });
*
* Set custom URL parameters:
* $(".fancybox").fancybox({
* helpers : {
* media: {
* youtube : {
* params : {
* autoplay : 0
* }
* }
* }
* }
* });
*
* Or:
* $(".fancybox").fancybox({,
* helpers : {
* media: true
* },
* youtube : {
* autoplay: 0
* }
* });
*
* Supports:
*
* Youtube
* http://www.youtube.com/watch?v=opj24KnzrWo
* http://www.youtube.com/embed/opj24KnzrWo
* http://youtu.be/opj24KnzrWo
* http://www.youtube-nocookie.com/embed/opj24KnzrWo
* Vimeo
* http://vimeo.com/40648169
* http://vimeo.com/channels/staffpicks/38843628
* http://vimeo.com/groups/surrealism/videos/36516384
* http://player.vimeo.com/video/45074303
* Metacafe
* http://www.metacafe.com/watch/7635964/dr_seuss_the_lorax_movie_trailer/
* http://www.metacafe.com/watch/7635964/
* Dailymotion
* http://www.dailymotion.com/video/xoytqh_dr-seuss-the-lorax-premiere_people
* Twitvid
* http://twitvid.com/QY7MD
* Twitpic
* http://twitpic.com/7p93st
* Instagram
* http://instagr.am/p/IejkuUGxQn/
* http://instagram.com/p/IejkuUGxQn/
* Google maps
* http://maps.google.com/maps?q=Eiffel+Tower,+Avenue+Gustave+Eiffel,+Paris,+France&t=h&z=17
* http://maps.google.com/?ll=48.857995,2.294297&spn=0.007666,0.021136&t=m&z=16
* http://maps.google.com/?ll=48.859463,2.292626&spn=0.000965,0.002642&t=m&z=19&layer=c&cbll=48.859524,2.292532&panoid=YJ0lq28OOy3VT2IqIuVY0g&cbp=12,151.58,,0,-15.56
*/
(function ($) {
"use strict";
//Shortcut for fancyBox object
var F = $.fancybox,
format = function( url, rez, params ) {
params = params || '';
if ( $.type( params ) === "object" ) {
params = $.param(params, true);
}
$.each(rez, function(key, value) {
url = url.replace( '$' + key, value || '' );
});
if (params.length) {
url += ( url.indexOf('?') > 0 ? '&' : '?' ) + params;
}
return url;
};
//Add helper object
F.helpers.media = {
defaults : {
youtube : {
matcher : /(youtube\.com|youtu\.be|youtube-nocookie\.com)\/(watch\?v=|v\/|u\/|embed\/?)?(videoseries\?list=(.*)|[\w-]{11}|\?listType=(.*)&list=(.*)).*/i,
params : {
autoplay : 1,
autohide : 1,
fs : 1,
rel : 0,
hd : 1,
wmode : 'opaque',
enablejsapi : 1
},
type : 'iframe',
url : '//www.youtube.com/embed/$3'
},
vimeo : {
matcher : /(?:vimeo(?:pro)?.com)\/(?:[^\d]+)?(\d+)(?:.*)/,
params : {
autoplay : 1,
hd : 1,
show_title : 1,
show_byline : 1,
show_portrait : 0,
fullscreen : 1
},
type : 'iframe',
url : '//player.vimeo.com/video/$1'
},
metacafe : {
matcher : /metacafe.com\/(?:watch|fplayer)\/([\w\-]{1,10})/,
params : {
autoPlay : 'yes'
},
type : 'swf',
url : function( rez, params, obj ) {
obj.swf.flashVars = 'playerVars=' + $.param( params, true );
return '//www.metacafe.com/fplayer/' + rez[1] + '/.swf';
}
},
dailymotion : {
matcher : /dailymotion.com\/video\/(.*)\/?(.*)/,
params : {
additionalInfos : 0,
autoStart : 1
},
type : 'swf',
url : '//www.dailymotion.com/swf/video/$1'
},
twitvid : {
matcher : /twitvid\.com\/([a-zA-Z0-9_\-\?\=]+)/i,
params : {
autoplay : 0
},
type : 'iframe',
url : '//www.twitvid.com/embed.php?guid=$1'
},
twitpic : {
matcher : /twitpic\.com\/(?!(?:place|photos|events)\/)([a-zA-Z0-9\?\=\-]+)/i,
type : 'image',
url : '//twitpic.com/show/full/$1/'
},
instagram : {
matcher : /(instagr\.am|instagram\.com)\/p\/([a-zA-Z0-9_\-]+)\/?/i,
type : 'image',
url : '//$1/p/$2/media/?size=l'
},
google_maps : {
matcher : /maps\.google\.([a-z]{2,3}(\.[a-z]{2})?)\/(\?ll=|maps\?)(.*)/i,
type : 'iframe',
url : function( rez ) {
return '//maps.google.' + rez[1] + '/' + rez[3] + '' + rez[4] + '&output=' + (rez[4].indexOf('layer=c') > 0 ? 'svembed' : 'embed');
}
}
},
beforeLoad : function(opts, obj) {
var url = obj.href || '',
type = false,
what,
item,
rez,
params;
for (what in opts) {
if (opts.hasOwnProperty(what)) {
item = opts[ what ];
rez = url.match( item.matcher );
if (rez) {
type = item.type;
params = $.extend(true, {}, item.params, obj[ what ] || ($.isPlainObject(opts[ what ]) ? opts[ what ].params : null));
url = $.type( item.url ) === "function" ? item.url.call( this, rez, params, obj ) : format( item.url, rez, params );
break;
}
}
}
if (type) {
obj.href = url;
obj.type = type;
obj.autoHeight = false;
}
}
};
}(jQuery)); | JavaScript |
jQuery(
function($) {
$(document).ready(function(){
var contentButton = [];
var contentTop = [];
var content = [];
var lastScrollTop = 0;
var scrollDir = '';
var itemClass = '';
var itemHover = '';
var menuSize = null;
var stickyHeight = 0;
var stickyMarginB = 0;
var currentMarginT = 0;
var topMargin = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
scrollDir = 'down';
} else {
scrollDir = 'up';
}
lastScrollTop = st;
});
$.fn.stickUp = function( options ) {
// adding a class to users div
$(this).addClass('stuckMenu');
//getting options
var objn = 0;
if(options != null) {
for(var o in options.parts) {
if (options.parts.hasOwnProperty(o)){
content[objn] = options.parts[objn];
objn++;
}
}
if(objn == 0) {
console.log('error:needs arguments');
}
itemClass = options.itemClass;
itemHover = options.itemHover;
if(options.topMargin != null) {
if(options.topMargin == 'auto') {
topMargin = parseInt($('.stuckMenu').css('margin-top'));
} else {
if(isNaN(options.topMargin) && options.topMargin.search("px") > 0){
topMargin = parseInt(options.topMargin.replace("px",""));
} else if(!isNaN(parseInt(options.topMargin))) {
topMargin = parseInt(options.topMargin);
} else {
console.log("incorrect argument, ignored.");
topMargin = 0;
}
}
} else {
topMargin = 0;
}
menuSize = $('.'+itemClass).size();
}
stickyHeight = parseInt($(this).height());
stickyMarginB = parseInt($(this).css('margin-bottom'));
currentMarginT = parseInt($(this).next().closest('div').css('margin-top'));
vartop = parseInt($(this).offset().top);
//$(this).find('*').removeClass(itemHover);
}
$(document).on('scroll', function() {
varscroll = parseInt($(document).scrollTop());
if(menuSize != null){
for(var i=0;i < menuSize;i++)
{
contentTop[i] = $('#'+content[i]+'').offset().top;
function bottomView(i) {
contentView = $('#'+content[i]+'').height()*.4;
testView = contentTop[i] - contentView;
//console.log(varscroll);
if(varscroll > testView){
$('.'+itemClass).removeClass(itemHover);
$('.'+itemClass+':eq('+i+')').addClass(itemHover);
} else if(varscroll < 50){
$('.'+itemClass).removeClass(itemHover);
$('.'+itemClass+':eq(0)').addClass(itemHover);
}
}
if(scrollDir == 'down' && varscroll > contentTop[i]-50 && varscroll < contentTop[i]+50) {
$('.'+itemClass).removeClass(itemHover);
$('.'+itemClass+':eq('+i+')').addClass(itemHover);
}
if(scrollDir == 'up') {
bottomView(i);
}
}
}
});
});
});
| JavaScript |
/*
Helios 1.5 by HTML5 UP
html5up.net | @n33co
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
*/
/*********************************************************************************/
/* Settings */
/*********************************************************************************/
var helios_settings = {
// Header (homepage only)
header: {
fullScreen: true,
fadeIn: true,
fadeDelay: 50
},
// Carousels
carousels: {
speed: 4,
fadeIn: true,
fadeDelay: 250
},
// Dropotron (dropdown menus)
dropotron: {
mode: 'fade',
speed: 350,
noOpenerFade: true,
alignment: 'center',
offsetX: -1,
offsetY: -16
},
// skelJS (probably don't need to change anything here unless you know what you're doing)
skelJS: {
prefix: 'css/style',
resetCSS: true,
boxModel: 'border',
grid: {
gutters: 48
},
breakpoints: {
'widest': { range: '1680-', hasStyleSheet: false, containers: 1400 },
'wide': { range: '-1680', containers: 1200 },
'normal': { range: '-1280', containers: 'fluid', grid: { gutters: 36 }, viewportWidth: 1140 },
'narrow': { range: '-960', containers: 'fluid', grid: { gutters: 32 } },
'narrower': { range: '-840', containers: 'fluid', grid: { gutters: 32, collapse: true } },
'mobile': { range: '-640', containers: 'fluid', grid: { gutters: 32, collapse: true }, lockViewport: true }
}
},
// skelJS Plugins (ditto; don't change unless you know what you're doing)
skelJSPlugins: {
panels: {
transformBreakpoints: 'mobile',
panels: {
navPanel: {
breakpoints: 'mobile',
position: 'top',
size: '75%',
html: '<div data-action="navList" data-args="nav"></div>'
}
},
overlays: {
navButton: {
breakpoints: 'mobile',
position: 'top-center',
width: 100,
height: 50,
html: '<div class="toggle" data-action="togglePanel" data-args="navPanel"></div>'
}
}
}
}
}
/*********************************************************************************/
/* Don't modify beyond this point unless you know what you're doing! */
/*********************************************************************************/
// Initialize skelJS
skel.init(helios_settings.skelJS, helios_settings.skelJSPlugins);
// jQuery functions
// scrolly
jQuery.fn.n33_scrolly = function() {
jQuery(this).click(function(e) {
var h = jQuery(this).attr('href'), target;
if (h.charAt(0) == '#' && h.length > 1 && (target = jQuery(h)).length > 0)
{
var pos = Math.max(target.offset().top, 0);
e.preventDefault();
jQuery('body,html').animate({ scrollTop: pos }, 'slow', 'swing');
}
});
};
// preloadImage
jQuery.n33_preloadImage = function(url, onload) {
var $img = $('<img />'),
_IEVersion = (navigator.userAgent.match(/MSIE ([0-9]+)\./) ? parseInt(RegExp.$1) : 99);
$img.attr('src', url);
if ($img.get(0).complete
|| _IEVersion < 9)
(onload)();
else
$img.load(onload);
};
// formerize
jQuery.fn.n33_formerize=function(){var _fakes=new Array(),_form = jQuery(this);_form.find('input[type=text],textarea').each(function() { var e = jQuery(this); if (e.val() == '' || e.val() == e.attr('placeholder')) { e.addClass('formerize-placeholder'); e.val(e.attr('placeholder')); } }).blur(function() { var e = jQuery(this); if (e.attr('name').match(/_fakeformerizefield$/)) return; if (e.val() == '') { e.addClass('formerize-placeholder'); e.val(e.attr('placeholder')); } }).focus(function() { var e = jQuery(this); if (e.attr('name').match(/_fakeformerizefield$/)) return; if (e.val() == e.attr('placeholder')) { e.removeClass('formerize-placeholder'); e.val(''); } }); _form.find('input[type=password]').each(function() { var e = jQuery(this); var x = jQuery(jQuery('<div>').append(e.clone()).remove().html().replace(/type="password"/i, 'type="text"').replace(/type=password/i, 'type=text')); if (e.attr('id') != '') x.attr('id', e.attr('id') + '_fakeformerizefield'); if (e.attr('name') != '') x.attr('name', e.attr('name') + '_fakeformerizefield'); x.addClass('formerize-placeholder').val(x.attr('placeholder')).insertAfter(e); if (e.val() == '') e.hide(); else x.hide(); e.blur(function(event) { event.preventDefault(); var e = jQuery(this); var x = e.parent().find('input[name=' + e.attr('name') + '_fakeformerizefield]'); if (e.val() == '') { e.hide(); x.show(); } }); x.focus(function(event) { event.preventDefault(); var x = jQuery(this); var e = x.parent().find('input[name=' + x.attr('name').replace('_fakeformerizefield', '') + ']'); x.hide(); e.show().focus(); }); x.keypress(function(event) { event.preventDefault(); x.val(''); }); }); _form.submit(function() { jQuery(this).find('input[type=text],input[type=password],textarea').each(function(event) { var e = jQuery(this); if (e.attr('name').match(/_fakeformerizefield$/)) e.attr('name', ''); if (e.val() == e.attr('placeholder')) { e.removeClass('formerize-placeholder'); e.val(''); } }); }).bind("reset", function(event) { event.preventDefault(); jQuery(this).find('select').val(jQuery('option:first').val()); jQuery(this).find('input,textarea').each(function() { var e = jQuery(this); var x; e.removeClass('formerize-placeholder'); switch (this.type) { case 'submit': case 'reset': break; case 'password': e.val(e.attr('defaultValue')); x = e.parent().find('input[name=' + e.attr('name') + '_fakeformerizefield]'); if (e.val() == '') { e.hide(); x.show(); } else { e.show(); x.hide(); } break; case 'checkbox': case 'radio': e.attr('checked', e.attr('defaultValue')); break; case 'text': case 'textarea': e.val(e.attr('defaultValue')); if (e.val() == '') { e.addClass('formerize-placeholder'); e.val(e.attr('placeholder')); } break; default: e.val(e.attr('defaultValue')); break; } }); window.setTimeout(function() { for (x in _fakes) _fakes[x].trigger('formerize_sync'); }, 10); }); return _form; };
// onVisible
(function() {
// Vars
var $window = jQuery(window),
elements = [],
delay = 10,
pad = 0,
timerId,
poll = function() {
var l = elements.length,
x = $window.scrollTop() + $window.height(),
i, e;
for (i=0; i < l; i++)
{
e = elements[i];
if (!e.state && x - e.pad > e.o.offset().top)
{
e.state = true;
(e.fn)();
}
}
};
// Event bindings
$window.load(function() {
$window.on('scroll resize', function() {
// Clear existing timeout (if one exists)
window.clearTimeout(timerId);
// Set our poll function to run after (delay)ms (prevents it from running until the user's done scrolling/resizing)
timerId = window.setTimeout(function() { (poll)(); }, delay);
}).trigger('resize');
});
// onVisible jQuery function (pretty much just adds the element to our list of elements to poll)
jQuery.fn.n33_onVisible = function(fn, p) {
elements.push({ o: jQuery(this), fn: fn, pad: (p ? p : pad), state: false });
};
})();
// Ready stuff
jQuery(function() {
var $window = $(window),
$body = $('body'),
$header = $('#header'),
_IEVersion = (navigator.userAgent.match(/MSIE ([0-9]+)\./) ? parseInt(RegExp.$1) : 99),
_isTouch = !!('ontouchstart' in window),
_isMobile = !!(navigator.userAgent.match(/(iPod|iPhone|iPad|Android|IEMobile)/));
// Pause CSS transitions until the page has loaded (prevents "flickering")
$body.addClass('paused');
$window.load(function() {
$body.removeClass('paused');
});
// Add input "placeholder" support to IE <= 9
if (_IEVersion < 10)
$('form').n33_formerize();
// Initialize scrolly links
$('.scrolly').n33_scrolly();
// Initialize dropotron
$('#nav > ul').dropotron(helios_settings.dropotron);
// Initialize carousels
$('.carousel').each(function() {
var $t = $(this),
$forward = $('<span class="forward"></span>'),
$backward = $('<span class="backward"></span>'),
$reel = $t.children('.reel'),
$items = $reel.children('article');
var pos = 0,
leftLimit,
rightLimit,
itemWidth,
reelWidth,
timerId;
// Items
if (helios_settings.carousels.fadeIn)
{
$items.addClass('loading');
$t.n33_onVisible(function() {
var timerId,
limit = $items.length - Math.ceil($window.width() / itemWidth);
timerId = window.setInterval(function() {
var x = $items.filter('.loading'), xf = x.first();
if (x.length <= limit)
{
window.clearInterval(timerId);
$items.removeClass('loading');
return;
}
if (_IEVersion < 10)
{
xf.fadeTo(750, 1.0);
window.setTimeout(function() {
xf.removeClass('loading');
}, 50);
}
else
xf.removeClass('loading');
}, helios_settings.carousels.fadeDelay);
}, 50);
}
// Main
$t._update = function() {
pos = 0;
rightLimit = (-1 * reelWidth) + $window.width();
leftLimit = 0;
$t._updatePos();
};
if (_IEVersion < 9)
$t._updatePos = function() { $reel.css('left', pos); };
else
$t._updatePos = function() { $reel.css('transform', 'translate(' + pos + 'px, 0)'); };
// Forward
$forward
.appendTo($t)
.hide()
.mouseenter(function(e) {
timerId = window.setInterval(function() {
pos -= helios_settings.carousels.speed;
if (pos <= rightLimit)
{
window.clearInterval(timerId);
pos = rightLimit;
}
$t._updatePos();
}, 10);
})
.mouseleave(function(e) {
window.clearInterval(timerId);
});
// Backward
$backward
.appendTo($t)
.hide()
.mouseenter(function(e) {
timerId = window.setInterval(function() {
pos += helios_settings.carousels.speed;
if (pos >= leftLimit)
{
window.clearInterval(timerId);
pos = leftLimit;
}
$t._updatePos();
}, 10);
})
.mouseleave(function(e) {
window.clearInterval(timerId);
});
// Init
$window.load(function() {
reelWidth = $reel[0].scrollWidth;
skel.onStateChange(function() {
if (_isTouch)
{
$reel
.css('overflow-y', 'hidden')
.css('overflow-x', 'scroll')
.scrollLeft(0);
$forward.hide();
$backward.hide();
}
else
{
$reel
.css('overflow', 'visible')
.scrollLeft(0);
$forward.show();
$backward.show();
}
$t._update();
});
$window.resize(function() {
reelWidth = $reel[0].scrollWidth;
$t._update();
}).trigger('resize');
});
});
// Initialize header
// Mobile devices don't do so well with fixed backgrounds and the fullscreen header :/
if (_isMobile)
{
$header.css('background-attachment', 'scroll');
helios_settings.header.fullScreen = false;
}
// Homepage header
if ($body.hasClass('homepage'))
{
if (helios_settings.header.fullScreen)
{
$window.bind('resize.helios', function() {
window.setTimeout(function() {
var s = $header.children('.inner');
var sh = s.outerHeight(), hh = $window.height(), h = Math.ceil((hh - sh) / 2) + 1;
$header
.css('padding-top', h)
.css('padding-bottom', h);
}, 0);
}).trigger('resize');
}
if (helios_settings.header.fadeIn)
{
$('<div class="overlay" />').appendTo($header);
$window
.load(function() {
var imageURL = $header.css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
$.n33_preloadImage(imageURL, function() {
if (_IEVersion < 10)
$header.children('.overlay').fadeOut(1000);
else
window.setTimeout(function() {
$header.addClass('ready');
}, helios_settings.header.fadeDelay);
});
});
}
}
}); | JavaScript |
/**
* innerHTML property for SVGElement
* Copyright(c) 2010, Jeff Schiller
*
* Licensed under the Apache License, Version 2
*
* Works in a SVG document in Chrome 6+, Safari 5+, Firefox 4+ and IE9+.
* Works in a HTML5 document in Chrome 7+, Firefox 4+ and IE9+.
* Does not work in Opera since it doesn't support the SVGElement interface yet.
*
* I haven't decided on the best name for this property - thus the duplication.
*/
(function() {
var serializeXML = function(node, output) {
var nodeType = node.nodeType;
if (nodeType == 3) { // TEXT nodes.
// Replace special XML characters with their entities.
output.push(node.textContent.replace(/&/, '&').replace(/</, '<').replace('>', '>'));
} else if (nodeType == 1) { // ELEMENT nodes.
// Serialize Element nodes.
output.push('<', node.tagName);
if (node.hasAttributes()) {
var attrMap = node.attributes;
for (var i = 0, len = attrMap.length; i < len; ++i) {
var attrNode = attrMap.item(i);
output.push(' ', attrNode.name, '=\'', attrNode.value, '\'');
}
}
if (node.hasChildNodes()) {
output.push('>');
var childNodes = node.childNodes;
for (var i = 0, len = childNodes.length; i < len; ++i) {
serializeXML(childNodes.item(i), output);
}
output.push('</', node.tagName, '>');
} else {
output.push('/>');
}
} else if (nodeType == 8) {
// TODO(codedread): Replace special characters with XML entities?
output.push('<!--', node.nodeValue, '-->');
} else {
// TODO: Handle CDATA nodes.
// TODO: Handle ENTITY nodes.
// TODO: Handle DOCUMENT nodes.
throw 'Error serializing XML. Unhandled node of type: ' + nodeType;
}
}
// The innerHTML DOM property for SVGElement.
Object.defineProperty(SVGElement.prototype, 'innerHTML', {
get: function() {
var output = [];
var childNode = this.firstChild;
while (childNode) {
serializeXML(childNode, output);
childNode = childNode.nextSibling;
}
return output.join('');
},
set: function(markupText) {
// Wipe out the current contents of the element.
while (this.firstChild) {
this.removeChild(this.firstChild);
}
try {
// Parse the markup into valid nodes.
var dXML = new DOMParser();
dXML.async = false;
// Wrap the markup into a SVG node to ensure parsing works.
sXML = '<svg xmlns=\'http://www.w3.org/2000/svg\'>' + markupText + '</svg>';
var svgDocElement = dXML.parseFromString(sXML, 'text/xml').documentElement;
// Now take each node, import it and append to this element.
var childNode = svgDocElement.firstChild;
while(childNode) {
this.appendChild(this.ownerDocument.importNode(childNode, true));
childNode = childNode.nextSibling;
}
} catch(e) {
throw new Error('Error parsing XML string');
};
}
});
// The innerSVG DOM property for SVGElement.
Object.defineProperty(SVGElement.prototype, 'innerSVG', {
get: function() {
return this.innerHTML;
},
set: function(markupText) {
this.innerHTML = markupText;
}
});
})();
| JavaScript |
/*
* QUnit - A JavaScript Unit Testing Framework
*
* http://docs.jquery.com/QUnit
*
* Copyright (c) 2009 John Resig, Jörn Zaefferer
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*/
(function(window) {
var QUnit = {
// Initialize the configuration options
init: function() {
config = {
stats: { all: 0, bad: 0 },
moduleStats: { all: 0, bad: 0 },
started: +new Date,
blocking: false,
autorun: false,
assertions: [],
filters: [],
queue: []
};
var tests = id("qunit-tests"),
banner = id("qunit-banner"),
result = id("qunit-testresult");
if ( tests ) {
tests.innerHTML = "";
}
if ( banner ) {
banner.className = "";
}
if ( result ) {
result.parentNode.removeChild( result );
}
},
// call on start of module test to prepend name to all tests
module: function(name, testEnvironment) {
config.currentModule = name;
synchronize(function() {
if ( config.currentModule ) {
QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all );
}
config.currentModule = name;
config.moduleTestEnvironment = testEnvironment;
config.moduleStats = { all: 0, bad: 0 };
QUnit.moduleStart( name, testEnvironment );
});
},
asyncTest: function(testName, expected, callback) {
if ( arguments.length === 2 ) {
callback = expected;
expected = 0;
}
QUnit.test(testName, expected, callback, true);
},
test: function(testName, expected, callback, async) {
var name = testName, testEnvironment, testEnvironmentArg;
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
// is 2nd argument a testEnvironment?
if ( expected && typeof expected === 'object') {
testEnvironmentArg = expected;
expected = null;
}
if ( config.currentModule ) {
name = config.currentModule + " module: " + name;
}
if ( !validTest(name) ) {
return;
}
synchronize(function() {
QUnit.testStart( testName );
testEnvironment = extend({
setup: function() {},
teardown: function() {}
}, config.moduleTestEnvironment);
if (testEnvironmentArg) {
extend(testEnvironment,testEnvironmentArg);
}
// allow utility functions to access the current test environment
QUnit.current_testEnvironment = testEnvironment;
config.assertions = [];
config.expected = expected;
try {
if ( !config.pollution ) {
saveGlobal();
}
testEnvironment.setup.call(testEnvironment);
} catch(e) {
QUnit.ok( false, "Setup failed on " + name + ": " + e.message );
}
if ( async ) {
QUnit.stop();
}
try {
callback.call(testEnvironment);
} catch(e) {
fail("Test " + name + " died, exception and test follows", e, callback);
QUnit.ok( false, "Died on test #" + (config.assertions.length + 1) + ": " + e.message );
// else next test will carry the responsibility
saveGlobal();
// Restart the tests if they're blocking
if ( config.blocking ) {
start();
}
}
});
synchronize(function() {
try {
checkPollution();
testEnvironment.teardown.call(testEnvironment);
} catch(e) {
QUnit.ok( false, "Teardown failed on " + name + ": " + e.message );
}
try {
QUnit.reset();
} catch(e) {
fail("reset() failed, following Test " + name + ", exception and reset fn follows", e, reset);
}
if ( config.expected && config.expected != config.assertions.length ) {
QUnit.ok( false, "Expected " + config.expected + " assertions, but " + config.assertions.length + " were run" );
}
var good = 0, bad = 0,
tests = id("qunit-tests");
config.stats.all += config.assertions.length;
config.moduleStats.all += config.assertions.length;
if ( tests ) {
var ol = document.createElement("ol");
ol.style.display = "none";
for ( var i = 0; i < config.assertions.length; i++ ) {
var assertion = config.assertions[i];
var li = document.createElement("li");
li.className = assertion.result ? "pass" : "fail";
li.appendChild(document.createTextNode(assertion.message || "(no message)"));
ol.appendChild( li );
if ( assertion.result ) {
good++;
} else {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
var b = document.createElement("strong");
b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + config.assertions.length + ")</b>";
addEvent(b, "click", function() {
var next = b.nextSibling, display = next.style.display;
next.style.display = display === "none" ? "block" : "none";
});
addEvent(b, "dblclick", function(e) {
var target = e && e.target ? e.target : window.event.srcElement;
if ( target.nodeName.toLowerCase() === "strong" ) {
var text = "", node = target.firstChild;
while ( node.nodeType === 3 ) {
text += node.nodeValue;
node = node.nextSibling;
}
text = text.replace(/(^\s*|\s*$)/g, "");
if ( window.location ) {
window.location.href = window.location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent(text);
}
}
});
var li = document.createElement("li");
li.className = bad ? "fail" : "pass";
li.appendChild( b );
li.appendChild( ol );
tests.appendChild( li );
if ( bad ) {
var toolbar = id("qunit-testrunner-toolbar");
if ( toolbar ) {
toolbar.style.display = "block";
id("qunit-filter-pass").disabled = null;
id("qunit-filter-missing").disabled = null;
}
}
} else {
for ( var i = 0; i < config.assertions.length; i++ ) {
if ( !config.assertions[i].result ) {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
}
QUnit.testDone( testName, bad, config.assertions.length );
if ( !window.setTimeout && !config.queue.length ) {
done();
}
});
if ( window.setTimeout && !config.doneTimer ) {
config.doneTimer = window.setTimeout(function(){
if ( !config.queue.length ) {
done();
} else {
synchronize( done );
}
}, 13);
}
},
/**
* Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
*/
expect: function(asserts) {
config.expected = asserts;
},
/**
* Asserts true.
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
*/
ok: function(a, msg) {
QUnit.log(a, msg);
config.assertions.push({
result: !!a,
message: msg
});
},
/**
* Checks that the first two arguments are equal, with an optional message.
* Prints out both actual and expected values.
*
* Prefered to ok( actual == expected, message )
*
* @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
*
* @param Object actual
* @param Object expected
* @param String message (optional)
*/
equal: function(actual, expected, message) {
push(expected == actual, actual, expected, message);
},
notEqual: function(actual, expected, message) {
push(expected != actual, actual, expected, message);
},
deepEqual: function(a, b, message) {
push(QUnit.equiv(a, b), a, b, message);
},
notDeepEqual: function(a, b, message) {
push(!QUnit.equiv(a, b), a, b, message);
},
strictEqual: function(actual, expected, message) {
push(expected === actual, actual, expected, message);
},
notStrictEqual: function(actual, expected, message) {
push(expected !== actual, actual, expected, message);
},
start: function() {
// A slight delay, to avoid any current callbacks
if ( window.setTimeout ) {
window.setTimeout(function() {
if ( config.timeout ) {
clearTimeout(config.timeout);
}
config.blocking = false;
process();
}, 13);
} else {
config.blocking = false;
process();
}
},
stop: function(timeout) {
config.blocking = true;
if ( timeout && window.setTimeout ) {
config.timeout = window.setTimeout(function() {
QUnit.ok( false, "Test timed out" );
QUnit.start();
}, timeout);
}
},
/**
* Resets the test setup. Useful for tests that modify the DOM.
*/
reset: function() {
if ( window.jQuery ) {
jQuery("#main").html( config.fixture );
jQuery.event.global = {};
jQuery.ajaxSettings = extend({}, config.ajaxSettings);
}
},
/**
* Trigger an event on an element.
*
* @example triggerEvent( document.body, "click" );
*
* @param DOMElement elem
* @param String type
*/
triggerEvent: function( elem, type, event ) {
if ( document.createEvent ) {
event = document.createEvent("MouseEvents");
event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent( event );
} else if ( elem.fireEvent ) {
elem.fireEvent("on"+type);
}
},
// Safe object type checking
is: function( type, obj ) {
return Object.prototype.toString.call( obj ) === "[object "+ type +"]";
},
// Logging callbacks
done: function(failures, total) {},
log: function(result, message) {},
testStart: function(name) {},
testDone: function(name, failures, total) {},
moduleStart: function(name, testEnvironment) {},
moduleDone: function(name, failures, total) {}
};
// Backwards compatibility, deprecated
QUnit.equals = QUnit.equal;
QUnit.same = QUnit.deepEqual;
// Maintain internal state
var config = {
// The queue of tests to run
queue: [],
// block until document ready
blocking: true
};
// Load paramaters
(function() {
var location = window.location || { search: "", protocol: "file:" },
GETParams = location.search.slice(1).split('&');
for ( var i = 0; i < GETParams.length; i++ ) {
GETParams[i] = decodeURIComponent( GETParams[i] );
if ( GETParams[i] === "noglobals" ) {
GETParams.splice( i, 1 );
i--;
config.noglobals = true;
} else if ( GETParams[i].search('=') > -1 ) {
GETParams.splice( i, 1 );
i--;
}
}
// restrict modules/tests by get parameters
config.filters = GETParams;
// Figure out if we're running the tests from a server or not
QUnit.isLocal = !!(location.protocol === 'file:');
})();
// Expose the API as global variables, unless an 'exports'
// object exists, in that case we assume we're in CommonJS
if ( typeof exports === "undefined" || typeof require === "undefined" ) {
extend(window, QUnit);
window.QUnit = QUnit;
} else {
extend(exports, QUnit);
exports.QUnit = QUnit;
}
if ( typeof document === "undefined" || document.readyState === "complete" ) {
config.autorun = true;
}
addEvent(window, "load", function() {
// Initialize the config, saving the execution queue
var oldconfig = extend({}, config);
QUnit.init();
extend(config, oldconfig);
config.blocking = false;
var userAgent = id("qunit-userAgent");
if ( userAgent ) {
userAgent.innerHTML = navigator.userAgent;
}
var toolbar = id("qunit-testrunner-toolbar");
if ( toolbar ) {
toolbar.style.display = "none";
var filter = document.createElement("input");
filter.type = "checkbox";
filter.id = "qunit-filter-pass";
filter.disabled = true;
addEvent( filter, "click", function() {
var li = document.getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ) {
if ( li[i].className.indexOf("pass") > -1 ) {
li[i].style.display = filter.checked ? "none" : "";
}
}
});
toolbar.appendChild( filter );
var label = document.createElement("label");
label.setAttribute("for", "qunit-filter-pass");
label.innerHTML = "Hide passed tests";
toolbar.appendChild( label );
var missing = document.createElement("input");
missing.type = "checkbox";
missing.id = "qunit-filter-missing";
missing.disabled = true;
addEvent( missing, "click", function() {
var li = document.getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ) {
if ( li[i].className.indexOf("fail") > -1 && li[i].innerHTML.indexOf('missing test - untested code is broken code') > - 1 ) {
li[i].parentNode.parentNode.style.display = missing.checked ? "none" : "block";
}
}
});
toolbar.appendChild( missing );
label = document.createElement("label");
label.setAttribute("for", "qunit-filter-missing");
label.innerHTML = "Hide missing tests (untested code is broken code)";
toolbar.appendChild( label );
}
var main = id('main');
if ( main ) {
config.fixture = main.innerHTML;
}
if ( window.jQuery ) {
config.ajaxSettings = window.jQuery.ajaxSettings;
}
QUnit.start();
});
function done() {
if ( config.doneTimer && window.clearTimeout ) {
window.clearTimeout( config.doneTimer );
config.doneTimer = null;
}
if ( config.queue.length ) {
config.doneTimer = window.setTimeout(function(){
if ( !config.queue.length ) {
done();
} else {
synchronize( done );
}
}, 13);
return;
}
config.autorun = true;
// Log the last module results
if ( config.currentModule ) {
QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all );
}
var banner = id("qunit-banner"),
tests = id("qunit-tests"),
html = ['Tests completed in ',
+new Date - config.started, ' milliseconds.<br/>',
'<span class="passed">', config.stats.all - config.stats.bad, '</span> tests of <span class="total">', config.stats.all, '</span> passed, <span class="failed">', config.stats.bad,'</span> failed.'].join('');
if ( banner ) {
banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass");
}
if ( tests ) {
var result = id("qunit-testresult");
if ( !result ) {
result = document.createElement("p");
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore( result, tests.nextSibling );
}
result.innerHTML = html;
}
QUnit.done( config.stats.bad, config.stats.all );
}
function validTest( name ) {
var i = config.filters.length,
run = false;
if ( !i ) {
return true;
}
while ( i-- ) {
var filter = config.filters[i],
not = filter.charAt(0) == '!';
if ( not ) {
filter = filter.slice(1);
}
if ( name.indexOf(filter) !== -1 ) {
return !not;
}
if ( not ) {
run = true;
}
}
return run;
}
function push(result, actual, expected, message) {
message = message || (result ? "okay" : "failed");
QUnit.ok( result, result ? message + ": " + expected : message + ", expected: " + QUnit.jsDump.parse(expected) + " result: " + QUnit.jsDump.parse(actual) );
}
function synchronize( callback ) {
config.queue.push( callback );
if ( config.autorun && !config.blocking ) {
process();
}
}
function process() {
while ( config.queue.length && !config.blocking ) {
config.queue.shift()();
}
}
function saveGlobal() {
config.pollution = [];
if ( config.noglobals ) {
for ( var key in window ) {
config.pollution.push( key );
}
}
}
function checkPollution( name ) {
var old = config.pollution;
saveGlobal();
var newGlobals = diff( old, config.pollution );
if ( newGlobals.length > 0 ) {
ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
config.expected++;
}
var deletedGlobals = diff( config.pollution, old );
if ( deletedGlobals.length > 0 ) {
ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
config.expected++;
}
}
// returns a new Array with the elements that are in a but not in b
function diff( a, b ) {
var result = a.slice();
for ( var i = 0; i < result.length; i++ ) {
for ( var j = 0; j < b.length; j++ ) {
if ( result[i] === b[j] ) {
result.splice(i, 1);
i--;
break;
}
}
}
return result;
}
function fail(message, exception, callback) {
if ( typeof console !== "undefined" && console.error && console.warn ) {
console.error(message);
console.error(exception);
console.warn(callback.toString());
} else if ( window.opera && opera.postError ) {
opera.postError(message, exception, callback.toString);
}
}
function extend(a, b) {
for ( var prop in b ) {
a[prop] = b[prop];
}
return a;
}
function addEvent(elem, type, fn) {
if ( elem.addEventListener ) {
elem.addEventListener( type, fn, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, fn );
} else {
fn();
}
}
function id(name) {
return !!(typeof document !== "undefined" && document && document.getElementById) &&
document.getElementById( name );
}
// Test for equality any JavaScript type.
// Discussions and reference: http://philrathe.com/articles/equiv
// Test suites: http://philrathe.com/tests/equiv
// Author: Philippe Rathé <prathe@gmail.com>
QUnit.equiv = function () {
var innerEquiv; // the real equiv function
var callers = []; // stack to decide between skip/abort functions
// Determine what is o.
function hoozit(o) {
if (QUnit.is("String", o)) {
return "string";
} else if (QUnit.is("Boolean", o)) {
return "boolean";
} else if (QUnit.is("Number", o)) {
if (isNaN(o)) {
return "nan";
} else {
return "number";
}
} else if (typeof o === "undefined") {
return "undefined";
// consider: typeof null === object
} else if (o === null) {
return "null";
// consider: typeof [] === object
} else if (QUnit.is( "Array", o)) {
return "array";
// consider: typeof new Date() === object
} else if (QUnit.is( "Date", o)) {
return "date";
// consider: /./ instanceof Object;
// /./ instanceof RegExp;
// typeof /./ === "function"; // => false in IE and Opera,
// true in FF and Safari
} else if (QUnit.is( "RegExp", o)) {
return "regexp";
} else if (typeof o === "object") {
return "object";
} else if (QUnit.is( "Function", o)) {
return "function";
} else {
return undefined;
}
}
// Call the o related callback with the given arguments.
function bindCallbacks(o, callbacks, args) {
var prop = hoozit(o);
if (prop) {
if (hoozit(callbacks[prop]) === "function") {
return callbacks[prop].apply(callbacks, args);
} else {
return callbacks[prop]; // or undefined
}
}
}
var callbacks = function () {
// for string, boolean, number and null
function useStrictEquality(b, a) {
if (b instanceof a.constructor || a instanceof b.constructor) {
// to catch short annotaion VS 'new' annotation of a declaration
// e.g. var i = 1;
// var j = new Number(1);
return a == b;
} else {
return a === b;
}
}
return {
"string": useStrictEquality,
"boolean": useStrictEquality,
"number": useStrictEquality,
"null": useStrictEquality,
"undefined": useStrictEquality,
"nan": function (b) {
return isNaN(b);
},
"date": function (b, a) {
return hoozit(b) === "date" && a.valueOf() === b.valueOf();
},
"regexp": function (b, a) {
return hoozit(b) === "regexp" &&
a.source === b.source && // the regex itself
a.global === b.global && // and its modifers (gmi) ...
a.ignoreCase === b.ignoreCase &&
a.multiline === b.multiline;
},
// - skip when the property is a method of an instance (OOP)
// - abort otherwise,
// initial === would have catch identical references anyway
"function": function () {
var caller = callers[callers.length - 1];
return caller !== Object &&
typeof caller !== "undefined";
},
"array": function (b, a) {
var i;
var len;
// b could be an object literal here
if ( ! (hoozit(b) === "array")) {
return false;
}
len = a.length;
if (len !== b.length) { // safe and faster
return false;
}
for (i = 0; i < len; i++) {
if ( ! innerEquiv(a[i], b[i])) {
return false;
}
}
return true;
},
"object": function (b, a) {
var i;
var eq = true; // unless we can proove it
var aProperties = [], bProperties = []; // collection of strings
// comparing constructors is more strict than using instanceof
if ( a.constructor !== b.constructor) {
return false;
}
// stack constructor before traversing properties
callers.push(a.constructor);
for (i in a) { // be strict: don't ensures hasOwnProperty and go deep
aProperties.push(i); // collect a's properties
if ( ! innerEquiv(a[i], b[i])) {
eq = false;
}
}
callers.pop(); // unstack, we are done
for (i in b) {
bProperties.push(i); // collect b's properties
}
// Ensures identical properties name
return eq && innerEquiv(aProperties.sort(), bProperties.sort());
}
};
}();
innerEquiv = function () { // can take multiple arguments
var args = Array.prototype.slice.apply(arguments);
if (args.length < 2) {
return true; // end transition
}
return (function (a, b) {
if (a === b) {
return true; // catch the most you can
} else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || hoozit(a) !== hoozit(b)) {
return false; // don't lose time with error prone cases
} else {
return bindCallbacks(a, callbacks, [b, a]);
}
// apply transition with (1..n) arguments
})(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1));
};
return innerEquiv;
}();
/**
* jsDump
* Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
* Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php)
* Date: 5/15/2008
* @projectDescription Advanced and extensible data dumping for Javascript.
* @version 1.0.0
* @author Ariel Flesler
* @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
*/
QUnit.jsDump = (function() {
function quote( str ) {
return '"' + str.toString().replace(/"/g, '\\"') + '"';
};
function literal( o ) {
return o + '';
};
function join( pre, arr, post ) {
var s = jsDump.separator(),
base = jsDump.indent(),
inner = jsDump.indent(1);
if ( arr.join )
arr = arr.join( ',' + s + inner );
if ( !arr )
return pre + post;
return [ pre, inner + arr, base + post ].join(s);
};
function array( arr ) {
var i = arr.length, ret = Array(i);
this.up();
while ( i-- )
ret[i] = this.parse( arr[i] );
this.down();
return join( '[', ret, ']' );
};
var reName = /^function (\w+)/;
var jsDump = {
parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance
var parser = this.parsers[ type || this.typeOf(obj) ];
type = typeof parser;
return type == 'function' ? parser.call( this, obj ) :
type == 'string' ? parser :
this.parsers.error;
},
typeOf:function( obj ) {
var type;
if ( obj === null ) {
type = "null";
} else if (typeof obj === "undefined") {
type = "undefined";
} else if (QUnit.is("RegExp", obj)) {
type = "regexp";
} else if (QUnit.is("Date", obj)) {
type = "date";
} else if (QUnit.is("Function", obj)) {
type = "function";
} else if (QUnit.is("Array", obj)) {
type = "array";
} else if (QUnit.is("Window", obj) || QUnit.is("global", obj)) {
type = "window";
} else if (QUnit.is("HTMLDocument", obj)) {
type = "document";
} else if (QUnit.is("HTMLCollection", obj) || QUnit.is("NodeList", obj)) {
type = "nodelist";
} else if (/^\[object HTML/.test(Object.prototype.toString.call( obj ))) {
type = "node";
} else {
type = typeof obj;
}
return type;
},
separator:function() {
return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' ';
},
indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
if ( !this.multiline )
return '';
var chr = this.indentChar;
if ( this.HTML )
chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
return Array( this._depth_ + (extra||0) ).join(chr);
},
up:function( a ) {
this._depth_ += a || 1;
},
down:function( a ) {
this._depth_ -= a || 1;
},
setParser:function( name, parser ) {
this.parsers[name] = parser;
},
// The next 3 are exposed so you can use them
quote:quote,
literal:literal,
join:join,
//
_depth_: 1,
// This is the list of parsers, to modify them, use jsDump.setParser
parsers:{
window: '[Window]',
document: '[Document]',
error:'[ERROR]', //when no parser is found, shouldn't happen
unknown: '[Unknown]',
'null':'null',
undefined:'undefined',
'function':function( fn ) {
var ret = 'function',
name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
if ( name )
ret += ' ' + name;
ret += '(';
ret = [ ret, this.parse( fn, 'functionArgs' ), '){'].join('');
return join( ret, this.parse(fn,'functionCode'), '}' );
},
array: array,
nodelist: array,
arguments: array,
object:function( map ) {
var ret = [ ];
this.up();
for ( var key in map )
ret.push( this.parse(key,'key') + ': ' + this.parse(map[key]) );
this.down();
return join( '{', ret, '}' );
},
node:function( node ) {
var open = this.HTML ? '<' : '<',
close = this.HTML ? '>' : '>';
var tag = node.nodeName.toLowerCase(),
ret = open + tag;
for ( var a in this.DOMAttrs ) {
var val = node[this.DOMAttrs[a]];
if ( val )
ret += ' ' + a + '=' + this.parse( val, 'attribute' );
}
return ret + close + open + '/' + tag + close;
},
functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
var l = fn.length;
if ( !l ) return '';
var args = Array(l);
while ( l-- )
args[l] = String.fromCharCode(97+l);//97 is 'a'
return ' ' + args.join(', ') + ' ';
},
key:quote, //object calls it internally, the key part of an item in a map
functionCode:'[code]', //function calls it internally, it's the content of the function
attribute:quote, //node calls it internally, it's an html attribute value
string:quote,
date:quote,
regexp:literal, //regex
number:literal,
'boolean':literal
},
DOMAttrs:{//attributes to dump from nodes, name=>realName
id:'id',
name:'name',
'class':'className'
},
HTML:true,//if true, entities are escaped ( <, >, \t, space and \n )
indentChar:' ',//indentation unit
multiline:true //if true, items in a collection, are separated by a \n, else just a space.
};
return jsDump;
})();
})(this);
| JavaScript |
/* Rev. 508
Copyright (C) 2008-2011 agenceXML - Alain COUTHURES
Contact at : xsltforms@agencexml.com
Copyright (C) 2006 AJAXForms S.L.
Contact at: info@ajaxforms.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// JSLint declarations:
/*global Core, DebugConsole, Event, ExprContext, I8N */
/*global NodeType, XFElement, XFRepeat, XMLEvents, XNode, XPath, xforms */
/*global Calendar, Schema, Dialog, XDocument, XFProcessor */
/*global ActiveXObject, NumberList, XPathAxis, XPathCoreFunctions, */
/*global escape */
var Core = {
fileName : "xsltforms.js",
isOpera : navigator.userAgent.match(/\bOpera\b/) != null,
isIE : navigator.userAgent.match(/\bMSIE\b/) != null
&& navigator.userAgent.match(/\bOpera\b/) == null,
isIE6 : navigator.userAgent.match(/\bMSIE 6.0/) != null,
isMozilla : navigator.userAgent.match(/\bGecko\b/) != null,
isFF2 : navigator.userAgent.match(/\bFirefox[\/\s]2.\b/) != null,
isXhtml : false, // document.documentElement.namespaceURI == "http://www.w3.org/1999/xhtml",
setClass : function(element, className, value) {
assert(element && className);
if (value) {
if (!this.hasClass(element, className)) {
element.className += " " + className;
}
} else if (element.className) {
element.className = element.className.replace(className, "");
}
},
hasClass : function(element, className) {
var cn = element.className;
return inArray(className, (cn && cn.split(" ")) || []);
},
initHover : function(element) {
XSLTFormsEvent.attach(element, "mouseover", function(event) {
Core.setClass(XSLTFormsEvent.getTarget(event), "hover", true);
} );
XSLTFormsEvent.attach(element, "mouseout", function(event) {
Core.setClass(XSLTFormsEvent.getTarget(event), "hover", false);
} );
},
getEventPos : function(ev) {
ev = ev || window.event;
return { x : ev.pageX || ev.clientX + window.document.body.scrollLeft || 0,
y : ev.pageY || ev.clientY + window.document.body.scrollTop || 0 };
},
getAbsolutePos : function(e) {
var r = Core.getPos(e);
if (e.offsetParent) {
var tmp = Core.getAbsolutePos(e.offsetParent);
r.x += tmp.x;
r.y += tmp.y;
}
return r;
},
getPos : function(e) {
var is_div = /^div$/i.test(e.tagName);
var r = {
x: e.offsetLeft - (is_div && e.scrollLeft? e.scrollLeft : 0),
y: e.offsetTop - (is_div && e.scrollTop? e.scrollTop : 0)
};
return r;
},
setPos : function(element, left, top) {
if (element.offsetParent) {
var tmp = Core.getAbsolutePos(element.offsetParent);
left -= tmp.x;
top -= tmp.y;
}
element.style.top = top + "px";
element.style.left = left + "px";
},
loadProperties : function(name) {
var uri = this.ROOT + name;
var req = Core.openRequest("GET", uri, false);
if (req.overrideMimeType) {
req.overrideMimeType("application/xml");
}
try {
req.send(null);
} catch(e) {
alert("File not found: " + uri);
}
if (req.status == 200) {
Core.loadNode(Core.config, Core.selectSingleNode('//properties', req.responseXML));
var inst = document.getElementById("xf-instance-config").xfElement
Core.config = inst.doc.documentElement;
inst.srcXML = Core.saveXML(Core.config);
Core.setMeta(Core.config, "instance", "xf-instance-config");
Core.setMeta(Core.config, "model", "xf-model-config");
//XMLEvents.dispatch(properties.model, "xforms-rebuild");
//xforms.refresh();
}
},
constructURI : function(uri) {
if (uri.match(/^[a-zA-Z0-9+.-]+:\/\//)) {
return uri;
}
if (uri.charAt(0) == '/') {
return document.location.href.substr(0, document.location.href.replace(/:\/\//, ":\\\\").indexOf("/")) + uri;
}
var href = document.location.href;
var idx = href.indexOf("?");
href = idx == -1 ? href : href.substr(0, idx);
idx = href.replace(/:\/\//, ":\\\\").lastIndexOf("/");
if (href.length > idx + 1) {
return (idx == -1 ? href : href.substr(0, idx)) + "/" + uri;
}
return href + uri;
},
createElement : function(type, parent, content, className) {
var el = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", type) : document.createElement(type);
if (className) { el.className = className; }
if (parent) { parent.appendChild(el); }
if (content) { el.appendChild(document.createTextNode(content)); }
return el;
},
getWindowSize : function() {
var myWidth = 0, myHeight = 0, myOffsetX = 0, myOffsetY = 0, myScrollX = 0, myScrollY = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
myOffsetX = document.body ? Math.max(document.documentElement.clientWidth, document.body.clientWidth) : document.documentElement.clientWidth; // body margins ?
myOffsetY = document.body ? Math.max(document.documentElement.clientHeight, document.body.clientHeight) : document.documentElement.clientHeight; // body margins ?
myScrollX = window.scrollX;
myScrollY = window.scrollY;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
myOffsetX = Math.max(document.documentElement.clientWidth, document.body.clientWidth); // body margins ?
myOffsetY = Math.max(document.documentElement.clientHeight, document.body.clientHeight); // body margins ?
myScrollX = document.body.parentNode.scrollLeft;
myScrollY = document.body.parentNode.scrollTop;
}
return {
height : myHeight,
width : myWidth,
offsetX : myOffsetX,
offsetY : myOffsetY,
scrollX : myScrollX,
scrollY : myScrollY
};
}
};
if (window.XMLHttpRequest) {
Core.openRequest = function(method, uri, async) {
// netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
var req = new XMLHttpRequest();
try {
req.open(method, Core.constructURI(uri), async);
} catch (e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP.3.0");
} catch (e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
throw new Error("This browser does not support XHRs(Ajax)! \n Cause: " + (e.message || e.description || e) + " \n Enable Javascript or ActiveX controls (on IE) or lower security restrictions.");
}
}
req.open(method, Core.constructURI(uri), async);
}
// Added by conal.tuohy@versi.edu.au so xsltforms doesn't accept "text/html" (so that HTTP content negotiation can be used)
// req.setRequestHeader("Accept", "text/xml;q=0.5,application/xml;q=0.6,application/xhtml+xml;q=0.4");
if (Core.isMozilla) {
req.overrideMimeType("text/xml");
}
return req;
};
} else if (window.ActiveXObject) {
Core.openRequest = function(method, uri, async) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP.3.0");
} catch (e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
throw new Error("This browser does not support XHRs(Ajax)! \n Cause: " + (e.message || e.description || e) + " \n Enable Javascript or ActiveX controls (on IE) or lower security restrictions.");
}
}
req.open(method, Core.constructURI(uri), async);
// Added by conal.tuohy@versi.edu.au so xsltforms doesn't accept "text/html" (so that HTTP content negotiation can be used)
// req.setRequestHeader("Accept", "text/xml;q=0.5,application/xml;q=0.6,application/xhtml+xml;q=0.4");
return req;
};
} else {
throw new Error("This browser does not support XHRs(Ajax)! \n Enable Javascript or ActiveX controls (on IE) or lower security restrictions.");
}
if (Core.isIE) {
Core.transformText = function(xml, xslt, inline) {
var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.6.0");
xmlDoc.loadXML(xml);
var xslDoc = new ActiveXObject("MSXML2.FreeThreadedDOMDocument.6.0");
if (inline) {
xslDoc.loadXML(xml);
} else {
xslDoc.async = false;
xslDoc.load(xslt);
}
var xslTemplate = new ActiveXObject("MSXML2.XSLTemplate.6.0");
xslTemplate.stylesheet = xslDoc;
var xslProc = xslTemplate.createProcessor();
xslProc.input = xmlDoc;
for (var i = 3, len = arguments.length-1; i < len ; i += 2) {
xslProc.addParameter(arguments[i], arguments[i+1], "");
}
xslProc.transform();
return xslProc.output;
};
} else {
Core.transformText = function(xml, xslt, inline) {
var parser = new DOMParser();
var serializer = new XMLSerializer();
var xmlDoc = parser.parseFromString(xml, "text/xml");
var xsltDoc;
if (inline) {
xsltDoc = parser.parseFromString(xslt, "text/xml");
} else {
xsltDoc = document.implementation.createDocument("","",null);
if (xsltDoc.load) {
xsltDoc.async = false;
xsltDoc.load(xslt);
} else {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", xslt, false);
xhttp.send("");
xslt = xhttp.responseText;
xsltDoc = parser.parseFromString(xslt, "text/xml");
}
}
var xsltProcessor = new XSLTProcessor();
if (!Core.isMozilla) {
xsltProcessor.setParameter(null, "xsltforms_caller", "true");
}
xsltProcessor.setParameter(null, "xsltforms_config", document.getElementById("xf-instance-config").xfElement.srcXML);
xsltProcessor.setParameter(null, "xsltforms_debug", xforms.debugMode+"");
xsltProcessor.setParameter(null, "xsltforms_lang", Language);
xsltProcessor.importStylesheet(xsltDoc);
var resultDocument = xsltProcessor.transformToDocument(xmlDoc);
return serializer.serializeToString(resultDocument);
};
}
var __scripts = Core.isXhtml ? document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "script") : document.getElementsByTagName("script");
for (var __i = 0, __len = __scripts.length; __i < __len; __i++) {
var __src = __scripts[__i].src;
if (__src.indexOf(Core.fileName) != -1) {
Core.ROOT = __src.replace(Core.fileName, "");
break;
}
}
Core.loadapplet = function() {
appelt = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "applet") : document.createElement("applet");
appelt.setAttribute("style", "position:absolute;left:-1px");
appelt.setAttribute("name", "xsltforms");
appelt.setAttribute("code", "xsltforms.class");
appelt.setAttribute("archive", Core.ROOT + "xsltforms.jar");
appelt.setAttribute("width", "1");
appelt.setAttribute("height", "1");
body = Core.isXhtml ? document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "body")[0] : document.getElementsByTagName("body")[0];
body.insertBefore(appelt, body.firstChild);
};
Core.IEReadFile = function(fname, encoding, xsdtype, title) {
if (document.applets["xsltforms"] || (Core.loadapplet(),document.applets["xsltforms"])) {
return document.applets["xsltforms"].readFile(fname, encoding, xsdtype, title) || "";
}
return "";
};
Core.javaReadFile = function(fname, encoding, xsdtype, title) {
if (document.applets["xsltforms"] || (Core.loadapplet(),document.applets["xsltforms"])) {
return document.applets["xsltforms"].readFile(fname, encoding, xsdtype, title) || "";
}
return "";
};
Core.javaWriteFile = function(fname, encoding, xsdtype, title, content) {
if (document.applets["xsltforms"] || (Core.loadapplet(),document.applets["xsltforms"])) {
if (fname == "") {
fname = document.applets["xsltforms"].lastChosenFileName;
}
return document.applets["xsltforms"].writeFile(fname, encoding, xsdtype, title, content) == 1;
}
return false;
};
Core.readFile = function(fname, encoding, xsdtype, title) {
return Core.javaReadFile(fname, encoding, xsdtype, title);
};
Core.writeFile = function(fname, encoding, xsdtype, title, content) {
return Core.javaWriteFile(fname, encoding, xsdtype, title, content);
};
Core.xsltsrc =
'<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">'
+' <xsl:output method="xml" omit-xml-declaration="yes"/>'
+' <xsl:template match="@*[starts-with(translate(name(),\'ABCDEFGHIJKLMNOPQRSTUVWXYZ\',\'abcdefghijklmnopqrstuvwxyz\'),\'xsltforms_\')]" priority="1"/>'
+' <xsl:template match="@*|node()" priority="0">'
+' <xsl:copy>'
+' <xsl:apply-templates select="@*|node()"/>'
+' </xsl:copy>'
+' </xsl:template>'
+'</xsl:stylesheet>'
;
if (Core.isIE) {
Core.createXMLDocument = function(xml) {
var d = new ActiveXObject("MSXML2.DOMDocument.3.0");
d.setProperty("SelectionLanguage", "XPath");
d.loadXML(xml);
return d;
}
Core.setAttributeNS = function(node, ns, name, value) {
node.setAttributeNode(node.ownerDocument.createNode(NodeType.ATTRIBUTE, name, ns));
node.setAttribute(name, value);
}
Core.selectSingleNode = function(xpath, node) {
try {
return node.selectSingleNode(xpath);
} catch (e) {
return null;
}
}
Core.selectSingleNodeText = function(xpath, node) {
try {
return node.selectSingleNode(xpath).text;
} catch (e) {
return "";
}
}
Core.selectNodesLength = function(xpath, node) {
try {
return node.selectNodes(xpath).length;
} catch (e) {
return 0;
}
}
Core.xsltDoc = new ActiveXObject("MSXML2.DOMDocument.3.0");
Core.xsltDoc.loadXML(Core.xsltsrc);
Core.loadNode = function(dest, src) {
var r = src.cloneNode(true);
dest.parentNode.replaceChild(r, dest);
}
Core.loadTextNode = function(dest, txt) {
if (dest.nodeType == NodeType.ATTRIBUTE) {
dest.value = txt;
} else {
while (dest.firstChild) {
dest.removeChild(dest.firstChild);
}
dest.appendChild(dest.ownerDocument.createTextNode(txt));
}
}
Core.loadXML = function(dest, xml) {
var result = new ActiveXObject("MSXML2.DOMDocument.3.0");
result.setProperty("SelectionLanguage", "XPath");
result.loadXML(xml);
var r = result.documentElement.cloneNode(true);
dest.parentNode.replaceChild(r, dest);
}
Core.saveXML = function(node) {
var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.3.0");
xmlDoc.setProperty("SelectionLanguage", "XPath");
xmlDoc.appendChild(node.documentElement ? node.documentElement.cloneNode(true) : node.cloneNode(true));
return xmlDoc.transformNode(Core.xsltDoc);
}
} else {
Core.createXMLDocument = function(xml) {
return Core.parser.parseFromString(xml, "text/xml");
}
Core.setAttributeNS = function(node, ns, name, value) {
node.setAttributeNS(ns, name, value);
}
Core.selectSingleNode = function(xpath, node) {
try {
if (node.evaluate) {
return node.evaluate(xpath, node, null, XPathResult.ANY_TYPE, null).iterateNext();
} else {
return node.ownerDocument.evaluate(xpath, node, null, XPathResult.ANY_TYPE, null).iterateNext();
}
} catch (e) {
return null;
}
}
Core.selectSingleNodeText = function(xpath, node) {
try {
if (node.evaluate) {
return node.evaluate(xpath, node, null, XPathResult.ANY_TYPE, null).iterateNext().textContent;
} else {
return node.ownerDocument.evaluate(xpath, node, null, XPathResult.ANY_TYPE, null).iterateNext().textContent;
}
} catch (e) {
return "";
}
}
Core.selectNodesLength = function(xpath, node) {
try {
if (node.evaluate) {
return node.evaluate(xpath, node, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength;
} else {
return node.ownerDocument.evaluate(xpath, node, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength;
}
} catch (e) {
return 0;
}
}
Core.parser = new DOMParser();
Core.xsltDoc = Core.parser.parseFromString(Core.xsltsrc, "text/xml");
Core.xsltProcessor = new XSLTProcessor();
Core.xsltProcessor.importStylesheet(Core.xsltDoc);
Core.serializer = new XMLSerializer();
Core.loadNode = function(dest, src) {
var r = src.cloneNode(true);
dest.parentNode.replaceChild(r, dest);
}
Core.loadTextNode = function(dest, txt) {
if (dest.nodeType == NodeType.ATTRIBUTE) {
dest.value = txt;
} else {
while (dest.firstChild) {
dest.removeChild(dest.firstChild);
}
dest.appendChild(dest.ownerDocument.createTextNode(txt));
}
}
Core.loadXML = function(dest, xml) {
var result = Core.parser.parseFromString(xml, "text/xml");
var r = result.documentElement.cloneNode(true);
dest.parentNode.replaceChild(r, dest);
}
Core.saveXML = function(node) {
var resultDocument = Core.xsltProcessor.transformToDocument(node);
return Core.serializer.serializeToString(resultDocument);
}
}
Core.unescape = function(xml) {
if (xml == null) {
return "";
}
var regex_escapepb = /^\s*</;
if (!xml.match(regex_escapepb)) {
xml = xml.replace(/</g, "<");
xml = xml.replace(/>/g, ">");
xml = xml.replace(/&/g, "&");
}
return xml;
}
Core.escape = function(text) {
if (text == null) {
return "";
}
if (typeof(text) == "string") {
text = text.replace(/&/g, "&");
text = text.replace(/</g, "<");
text = text.replace(/>/g, ">");
}
return text;
}
Core.getMeta = function(node, meta) {
return node.nodeType == NodeType.ELEMENT ? node.getAttribute("xsltforms_"+meta) : node.ownerElement ? node.ownerElement.getAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_"+meta) : node.selectSingleNode("..").getAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_"+meta);
}
Core.getBoolMeta = function(node, meta) {
return Boolean(node.nodeType == NodeType.ELEMENT ? node.getAttribute("xsltforms_"+meta) : node.nodeType == NodeType.ATTRIBUTE ? node.ownerElement ? node.ownerElement.getAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_"+meta) : node.selectSingleNode("..").getAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_"+meta) : false);
}
Core.getType = function(node) {
if (node.nodeType == NodeType.ELEMENT) {
var t = node.getAttribute("xsltforms_type");
if (t && t != '') {
return t;
}
if (node.getAttributeNS) {
return node.getAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
} else {
var att = node.selectSingleNode("@*[local-name()='type' and namespace-uri()='http://www.w3.org/2001/XMLSchema-instance']");
if (att && att.value != '') {
return att.value;
} else {
return null;
}
}
} else if (node.nodeType == NodeType.DOCUMENT) {
return null;
} else {
if (node.ownerElement) {
return node.ownerElement.getAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_type");
} else {
return node.selectSingleNode("..").getAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_type");
}
}
}
Core.getNil = function(node) {
if (node.nodeType == NodeType.ELEMENT) {
if (node.getAttributeNS) {
return booleanValue(node.getAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"));
} else {
var att = node.selectSingleNode("@*[local-name()='nil' and namespace-uri()='http://www.w3.org/2001/XMLSchema-instance']");
if (att && att.value != '') {
return booleanValue(att.value);
} else {
return false;
}
}
} else {
return false;
}
}
Core.setMeta = function(node, meta, value) {
if (node) {
node.nodeType == NodeType.ELEMENT ? node.setAttribute("xsltforms_"+meta, value) : node.ownerElement ? node.ownerElement.setAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_"+meta, value) : node.selectSingleNode("..").setAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_"+meta, value);
}
}
Core.setBoolMeta = function(node, meta, value) {
if (node) {
if (value) {
node.nodeType == NodeType.ELEMENT ? node.setAttribute("xsltforms_"+meta, value) : node.ownerElement ? node.ownerElement.setAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_"+meta, value) : node.selectSingleNode("..").setAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_"+meta, value);
} else {
node.nodeType == NodeType.ELEMENT ? node.removeAttribute("xsltforms_"+meta) : node.ownerElement ? node.ownerElement.removeAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_"+meta) : node.selectSingleNode("..").removeAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_"+meta);
}
}
}
Core.setTrueBoolMeta = function(node, meta) {
if (node) {
node.nodeType == NodeType.ELEMENT ? node.setAttribute("xsltforms_"+meta, true) : node.ownerElement ? node.ownerElement.setAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_"+meta, true) : node.selectSingleNode("..").setAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_"+meta, true);
}
}
Core.setFalseBoolMeta = function(node, meta) {
if (node) {
node.nodeType == NodeType.ELEMENT ? node.removeAttribute("xsltforms_"+meta) : node.ownerElement ? node.ownerElement.removeAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_"+meta) : node.selectSingleNode("..").removeAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_"+meta);
}
}
Core.setType = function(node, value) {
if (node) {
if (node.nodeType == NodeType.ELEMENT) {
node.setAttribute("xsltforms_type", value);
} else {
if (node.ownerElement) {
node.ownerElement.setAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_type", value);
} else {
node.selectSingleNode("..").setAttribute("xsltforms_"+(node.localName ? node.localName : node.baseName)+"_type", value);
}
}
}
}
if (!Core.isIE) {
if (typeof XMLDocument == "undefined") {
XMLDocument = Document;
}
XMLDocument.prototype.selectNodes = function(path, single, node) {
var r = this.evaluate(path, (node ? node : this), this.createNSResolver(this.documentElement), (single ? XPathResult.FIRST_ORDERED_NODE_TYPE : XPathResult.ORDERED_NODE_SNAPSHOT_TYPE), null);
if (single) {
return r.singleNodeValue ? r.singleNodeValue : null;
}
for (var i = 0, len = r.snapshotLength, r2 = []; i < len; i++) {
r2.push(r.snapshotItem(i));
}
return r2;
}
XMLDocument.prototype.selectSingleNode = function(path) {
return this.selectNodes(path, true);
}
XMLDocument.prototype.createNode = function(t, name, ns) {
switch(t) {
case NodeType.ELEMENT:
return this.createElementNS(ns, name);
break;
case NodeType.ATTRIBUTE:
return this.createAttributeNS(ns, name);
break;
default:
return null;
}
}
Element.prototype.selectNodes = function(path) {
return this.ownerDocument.selectNodes(path, false, this);
}
Element.prototype.selectSingleNode = function(path) {
return this.ownerDocument.selectNodes(path, true, this);
}
}
var DebugConsole = {
element_ : null,
isInit_ : false,
time_ : 0,
init_ : function() {
this.element_ = document.getElementById("xsltforms_console");
this.isInit_ = true;
this.time_ = new Date().getTime();
},
write : function(text) {
try {
if (this.isOpen()) {
var time = new Date().getTime();
this.element_.appendChild(document.createTextNode(time - this.time_ + " -> " + text));
Core.createElement("br", this.element_);
this.time_ = time;
}
} catch(e) {
}
},
clear : function() {
if (this.isOpen()) {
while (this.element_.firstChild) {
this.element_.removeChild(this.element_.firstChild);
}
this.time_ = new Date().getTime();
}
},
isOpen : function() {
if (!this.isInit_) {
this.init_();
}
return this.element_ != null;
}
};
var Dialog = {
openPosition: {},
dialogs : [],
init : false,
initzindex : 50,
zindex: 0,
selectstack : [],
dialogDiv : function(id) {
var div = null;
if (typeof id != "string") {
var divid = id.getAttribute("id");
if (divid != null && divid != "") {
div = IdManager.find(divid);
} else {
div = id;
}
} else {
div = IdManager.find(id);
}
if (!div) {
DebugConsole.write("Unknown dialog("+id+")!");
}
return div;
},
show : function(div, parent, modal) {
if (!(div = this.dialogDiv(div))) {
return;
}
// Don't reopen the top-dialog.
if (this.dialogs[this.dialogs.length - 1] === div) {
return;
}
// Maintain dialogs-array ordered.
this.dialogs = removeArrayItem(this.dialogs, div);
this.dialogs.push(div);
if (modal) {
var surround = document.getElementById('xforms-dialog-surround');
surround.style.display = "block";
surround.style.zIndex = (this.zindex + this.initzindex)*2;
this.zindex++;
var size = Core.getWindowSize();
surround.style.height = size.height+"px";
surround.style.width = size.width+"px";
surround.style.top = size.scrollY+"px";
surround.style.left = size.scrollX+"px";
var surroundresize = function () {
var surround = document.getElementById('xforms-dialog-surround');
var size = Core.getWindowSize();
surround.style.height = size.height+"px";
surround.style.width = size.width+"px";
surround.style.top = size.scrollY+"px";
surround.style.left = size.scrollX+"px";
}
window.onscroll = surroundresize;
window.onresize = surroundresize;
}
div.style.display = "block";
div.style.zIndex = (this.zindex + this.initzindex)*2-1;
this.showSelects(div, false, modal);
if (parent) {
var absPos = Core.getAbsolutePos(parent);
Core.setPos(div, absPos.x, (absPos.y + parent.offsetHeight));
} else {
var size = Core.getWindowSize();
var h = size.scrollY + (size.height - div.offsetHeight) / 2;
Core.setPos(div, (size.width - div.offsetWidth) / 2, h > 0 ? h : 100);
}
},
hide : function(div, modal) {
if (!(div = this.dialogDiv(div))) {
return;
}
var oldlen = this.dialogs.length;
this.dialogs = removeArrayItem(this.dialogs, div);
if (this.dialogs.length == oldlen) {
return;
}
this.showSelects(div, true, modal);
div.style.display = "none";
if (modal) {
if (!this.dialogs.length) {
this.zindex = 0;
document.getElementById('xforms-dialog-surround').style.display = "none";
window.onscroll = null;
window.onresize = null;
} else {
this.zindex--;
document.getElementById('xforms-dialog-surround').style.zIndex = (this.zindex + this.initzindex)*2-2;
// Ensure new top-dialog over modal-surround.
if (this.dialogs.length) {
this.dialogs[this.dialogs.length - 1].style.zIndex = (this.zindex + this.initzindex)*2-1;
}
}
}
},
knownSelect : function(s) {
if (Core.isIE6) {
for (var i = 0, len = this.zindex; i < len; i++) {
for (var j = 0, len1 = this.selectstack[i].length; j < len1; j++) {
if (this.selectstack[i][j].select == s) {
return true;
}
}
}
}
return false;
},
showSelects : function(div, value, modal) {
if (Core.isIE6) {
var selects = Core.isXhtml ? document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "select") : document.getElementsByTagName("select");
var pos = Core.getAbsolutePos(div);
var w = div.offsetWidth;
var h = div.offsetHeight;
var dis = [];
for (var i = 0, len = selects.length; i < len; i++) {
var s = selects[i];
var p = s.parentNode;
while (p && p != div) {
p = p.parentNode;
}
if (p != div) {
var ps = Core.getAbsolutePos(s);
var ws = s.offsetWidth;
var hs = s.offsetHeight;
var under = ps.x + ws > pos.x && ps.x < pos.x + w && ps.y + hs > pos.y && ps.y < pos.y + h;
if (modal) {
if (value) {
dis = this.selectstack[this.zindex];
for (var j = 0, len1 = dis.length; j < len1; j++) {
if (dis[j].select == s) {
s.disabled = dis[j].disabled;
s.style.visibility = dis[j].visibility;
break;
}
}
} else {
var d = {"select": s, "disabled": s.disabled, "visibility": s.style.visibility};
dis[dis.length] = d;
if (under) {
s.style.visibility = "hidden";
} else {
s.disabled = true;
}
}
} else {
if (under) {
s.style.visibility = value? "" : "hidden";
}
}
}
}
if (modal && !value) {
this.selectstack[this.zindex - 1] = dis;
}
}
}
};
var XSLTFormsEvent = {
cache :null,
add_ : function() {
if (!XSLTFormsEvent.cache) {
XSLTFormsEvent.cache = [];
XSLTFormsEvent.attach(window, "unload", XSLTFormsEvent.flush_);
}
XSLTFormsEvent.cache.push(arguments);
},
flush_ : function() {
if (!XSLTFormsEvent.cache) return;
for (var i = XSLTFormsEvent.cache.length - 1; i >= 0; i--) {
var item = XSLTFormsEvent.cache[i];
XSLTFormsEvent.detach(item[0], item[1], item[2], item[3]);
}
if (XSLTFormsEvent.onunload) {
XSLTFormsEvent.onunload();
}
XSLTFormsEvent.onunload = null;
},
onunload : null
};
if (Core.isIE) {
XSLTFormsEvent.attach = function(target, name, handler, phase) {
var func = function(evt) { handler.call(window.event.srcElement, evt); };
target.attachEvent("on" + name, func);
this.add_(target, name, func, phase);
};
XSLTFormsEvent.detach = function(target, name, handler, phase) {
target.detachEvent("on" + name, handler);
};
XSLTFormsEvent.getTarget = function() {
return window.event.srcElement;
};
XSLTFormsEvent.dispatch = function(target, name) {
target.fireEvent("on" + name, document.createEventObject());
};
} else {
XSLTFormsEvent.attach = function(target, name, handler, phase) {
if (target == window && !window.addEventListener) {
target = document;
}
target.addEventListener(name, handler, phase);
this.add_(target, name, handler, phase);
};
XSLTFormsEvent.detach = function(target, name, handler, phase) {
if (target == window && !window.addEventListener) {
target = document;
}
target.removeEventListener(name, handler, phase);
};
XSLTFormsEvent.getTarget = function(ev) {
return ev.target;
};
XSLTFormsEvent.dispatch = function(target, name) {
var event = document.createEvent("Event");
event.initEvent(name, true, true);
target.dispatchEvent(event);
};
}
var I8N = {
messages : null,
lang : null,
langs : ["cz", "de", "el", "en", "en_us", "es", "fr" , "gl", "ko", "it", "ja", "nb_no", "nl", "nn_no", "pt", "ro", "ru", "si", "sk", "zh", "zh_cn", "zh_tw"],
get : function(key) {
if (!Core.config) {
return "Initializing";
}
if (Language == "navigator" || Language != Core.selectSingleNodeText('language', Core.config)) {
var lan = Language == "navigator" ? (navigator.language || navigator.userLanguage) : Core.selectSingleNodeText('language', Core.config);
lan = lan.replace("-", "_").toLowerCase();
var finded = inArray(lan, I8N.langs);
if (!finded) {
ind = lan.indexOf("_");
if (ind != -1) {
lan = lan.substring(0, ind);
}
finded = inArray(lan, I8N.langs);
}
if (finded) {
Core.loadProperties("config_" + lan + ".xsl");
Language = Core.selectSingleNodeText('language', Core.config);
} else {
Language = "default";
}
}
return Core.selectSingleNodeText(key, Core.config);
},
parse : function(str, pattern) {
if (str == null || str.match("^\\s*$")) {
return null;
}
if (!pattern) { pattern = I8N.get("format.datetime"); }
var d = new Date();
I8N._parse(d, "Year", str, pattern, "yyyy");
I8N._parse(d, "Month", str, pattern, "MM");
I8N._parse(d, "Date", str, pattern, "dd");
I8N._parse(d, "Hours", str, pattern, "hh");
I8N._parse(d, "Minutes", str, pattern, "mm");
I8N._parse(d, "Seconds", str, pattern, "ss");
return d;
},
format : function(date, pattern, loc) {
if (!date) {
return "";
}
if (!pattern) { pattern = I8N.get("format.datetime"); }
var str = I8N._format(pattern, (loc ? date.getDate() : date.getUTCDate()), "dd");
str = I8N._format(str, (loc ? date.getMonth() : date.getUTCMonth()) + 1, "MM");
y = (loc ? date.getFullYear() : date.getUTCFullYear());
str = I8N._format(str, y < 1000? 1900 + y : y, "yyyy");
str = I8N._format(str, (loc ? date.getSeconds() : date.getUTCSeconds()), "ss");
str = I8N._format(str, (loc ? date.getMinutes() : date.getUTCMinutes()), "mm");
str = I8N._format(str, (loc ? date.getHours() : date.getUTCHours()), "hh");
o = date.getTimezoneOffset();
str = I8N._format(str, (loc ? (o < 0 ? "+" : "-")+zeros(Math.floor(Math.abs(o)/60),2)+":"+zeros(Math.abs(o) % 60,2) : "Z"), "z");
return str;
},
parseDate : function(str) {
return I8N.parse(str, I8N.get("format.date"));
},
formatDate : function(str) {
return I8N.format(str, I8N.get("format.date"), true);
},
formatNumber : function(number, decimals) {
if (isNaN(number)) { return number; }
var value = "" + number;
var index = value.indexOf(".");
var integer = parseInt(index != -1? value.substring(0, index) : value, 10);
var decimal = index != -1? value.substring(index + 1) : "";
var decsep = I8N.get("format.decimal");
return integer
+ (decimals > 0? decsep + zeros(decimal, decimals, true)
: (decimal? decsep + decimal : ""));
},
parseNumber : function(value) {
var decsep = I8N.get("format.decimal");
if(!value.match("^[\\-+]?([0-9]+(\\" + decsep + "[0-9]*)?|\\" + decsep + "[0-9]+)$")) {
throw "Invalid number " + value;
}
var index = value.indexOf(decsep);
var integer = parseInt(index != -1? value.substring(0, index) : value, 10);
var decimal = index != -1? value.substring(index + 1) : null;
return integer + (decimal? "." + decimal : "");
},
_format : function(returnValue, value, el) {
return returnValue.replace(el, zeros(value, el.length));
},
_parse : function(date, prop, str, format, el) {
var index = format.indexOf(el);
if (index != -1) {
format = format.replace(new RegExp("\\.", "g"), "\\.");
format = format.replace(new RegExp("\\(", "g"), "\\(");
format = format.replace(new RegExp("\\)", "g"), "\\)");
format = format.replace(new RegExp(el), "(.*)");
format = format.replace(new RegExp("yyyy"), ".*");
format = format.replace(new RegExp("MM"), ".*");
format = format.replace(new RegExp("dd"), ".*");
format = format.replace(new RegExp("hh"), ".*");
format = format.replace(new RegExp("mm"), ".*");
format = format.replace(new RegExp("ss"), ".*");
var val = str.replace(new RegExp(format), "$1");
if (val.charAt(0) === '0') val = val.substring(1);
val = parseInt(val, 10);
if (isNaN(val)) {
throw "Error parsing date " + str + " with pattern " + format;
}
var n = new Date();
n = n.getFullYear() - 2000;
date["set" + prop](prop == "Month"? val - 1 : (prop == "Year" && val <= n+10 ? val+2000 : val));
}
}
};
var NumberList = function(parent, className, input, min, max, minlengh) {
this.element = Core.createElement("ul", parent, null, className);
this.move = 0;
this.input = input;
this.min = min;
this.max = max;
this.minlength = minlengh || 1;
var list = this;
this.createChild("+", function() { list.start(1); }, function() { list.stop(); } );
for (var i = 0; i < 7; i++) {
this.createChild(" ", function(event) {
list.input.value = XSLTFormsEvent.getTarget(event).childNodes[0].nodeValue;
list.close();
XSLTFormsEvent.dispatch(list.input, "change");
} );
}
this.createChild("-", function() { list.start(-1); }, function() { list.stop(); } );
};
NumberList.prototype.show = function() {
var input = this.input;
this.current = parseInt(input.value, 10);
this.refresh();
Dialog.show(this.element, input, false);
};
NumberList.prototype.close = function() {
Dialog.hide(this.element, false);
};
NumberList.prototype.createChild = function(content, handler, handler2) {
var child = Core.createElement("li", this.element, content);
Core.initHover(child);
if (handler2) {
XSLTFormsEvent.attach(child, "mousedown", handler);
XSLTFormsEvent.attach(child, "mouseup", handler2);
} else {
XSLTFormsEvent.attach(child, "click", handler);
}
};
NumberList.prototype.refresh = function() {
var childs = this.element.childNodes;
var cur = this.current;
if (cur >= this.max - 3) {
cur = this.max - 3;
} else if (cur <= this.min + 3) {
cur = this.min + 3;
}
var top = cur + 4;
for (var i = 1; i < 8; i++) {
Core.setClass(childs[i], "hover", false);
var str = (top - i) + "";
for (; str.length < this.minlength; str = '0' + str) {}
childs[i].firstChild.nodeValue = str;
}
};
NumberList.prototype.start = function(value) {
this.move = value;
NumberList.current = this;
this.run();
};
NumberList.prototype.stop = function() {
this.move = 0;
};
NumberList.prototype.run = function() {
if ( (this.move > 0 && this.current + 3 < this.max)
|| (this.move < 0 && this.current - 3> this.min)) {
this.current += this.move;
this.refresh();
var list = this;
setTimeout("NumberList.current.run()", 60);
}
};
NumberList.current = null;
function forEach(object, block) {
var args = [];
for (var i = 0, len = arguments.length - 2; i < len; i++) {
args[i] = arguments[i + 2];
}
if (object) {
if (typeof object.length == "number") {
for (var j = 0, len1 = object.length; j < len1; j++) {
var obj = object[j];
var func = typeof block == "string"? obj[block] : block;
func.apply(obj, args);
}
} else {
for (var key in object) {
var obj2 = object[key];
var func2 = typeof block == "string"? obj2[block] : block;
func2.apply(obj2, args);
}
}
}
}
function assert(condition, message) {
if (!condition && DebugConsole.isOpen()) {
if (!xforms.debugMode) {
xforms.debugMode = true;
xforms.debugging();
}
DebugConsole.write("Assertion failed: " + message);
var callstack = null;
if (arguments.caller) { // Internet Explorer
this.callstack = [];
for (var caller = arguments.caller; caller != null; caller = caller.caller) {
this.callstack.push(caller.name ? caller.name : "<anonymous>");
}
} else {
try {
var x; x.y;
} catch (exception) {
this.callstack = exception.stack.split("\n");
}
}
if (this.callstack) {
for (var i = 0, len = this.callstack.length; i < len; i++) {
DebugConsole.write("> " + this.callstack[i]);
}
}
throw message;
}
}
function inArray(value, array) {
for (var i = 0, len = array.length; i < len; i++) {
if (value == array[i]) {
return true;
}
}
return false;
}
function zeros(value, length, right) {
var res = "" + value;
for (; res.length < length; res = right? res + '0' : '0' + res) {}
return res;
}
function getValue(node, format, serialize) {
assert(node);
if (serialize) {
return node.nodeType == NodeType.ATTRIBUTE ? node.nodeValue : Core.saveXML(node);
}
/*****************
var value = node.nodeType == NodeType.ATTRIBUTE ? node.nodeValue :
(node.firstChild != null? node.firstChild.nodeValue : "");
var value = "";
if (node.nodeType == NodeType.ATTRIBUTE) {
value = node.nodeValue;
} else if (node.firstChild == null) {
} else if (node.firstChild.nodeType == NodeType.TEXT) {
var childNodes = node.childNodes;
var len = childNodes.length;
for (var i = 0; i < len; i++) {
value = value + childNodes[i].nodeValue;
}
} else {
value = node.firstChild.nodeValue;
}
******************/
var value = node.text != undefined ? node.text : node.textContent;
if (value && format) {
var schtyp = Schema.getType(Core.getType(node) || "xsd_:string");
if (schtyp.format) {
try { value = schtyp.format(value); } catch(e) { }
}
}
return value;
}
function setValue(node, value) {
assert(node);
if (node.nodeType == NodeType.ATTRIBUTE) {
node.nodeValue = value;
} else if (Core.isIE && node.innerHTML) {
node.innerHTML = value;
} else {
while (node.firstChild) {
node.removeChild(node.firstChild);
}
if (value != null) {
for (var i = 0, l = value.length; i < l; i += 4096) {
node.appendChild(node.ownerDocument.createTextNode(value.substr(i, 4096)));
}
}
}
}
function run(action, element, evt, synch, propagate) {
if (synch) {
Dialog.show("statusPanel", null, false);
setTimeout(function() {
xforms.openAction();
action.execute(IdManager.find(element), null, evt);
Dialog.hide("statusPanel", false);
if (!propagate) {
evt.stopPropagation();
}
xforms.closeAction();
}, 1 );
} else {
xforms.openAction();
action.execute(IdManager.find(element), null, evt);
if (!propagate) {
evt.stopPropagation();
}
xforms.closeAction();
}
}
function getId(element) {
if(element.id) {
return element.id;
} else {
return element.parentNode.parentNode.parentNode.parentNode.id;
}
}
function show(el, type, value) {
el.parentNode.lastChild.style.display = value? 'inline' : 'none';
}
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/, '');
};
String.prototype.addslashes = function() {
return this.replace(/\\/g,"\\\\").replace(/\'/g,"\\'").replace(/\"/g,"\\\"");
}
function copyArray(source, dest) {
if( dest ) {
for (var i = 0, len = source.length; i < len; i++) {
dest[i] = source[i];
}
}
}
function removeArrayItem(array, item) {
var narr = [];
for (var i = 0, len = array.length; i < len; i++) {
if (array[i] != item ) {
narr.push(array[i]);
}
}
return narr;
}
var xforms = {
cont : 0,
ready : false,
body : null,
models : [],
defaultModel : null,
changes : [],
newChanges : [],
building : false,
posibleBlur : false,
bindErrMsgs : [], // binding-error messages gathered during refreshing
htmltime: 0,
creatingtime: 0,
inittime: 0,
refreshtime: 0,
refreshcount: 0,
counters: {
group: 0,
input: 0,
item: 0,
itemset: 0,
label: 0,
output: 0,
repeat: 0,
select: 0,
trigger: 0
},
fileVersion : "508",
fileVersionNumber: 508,
debugMode: false,
debugButtons: [
{label: "Profiler", action: "xforms.profiling();"}
/*
,{label: "Instance Viewer"}
,{label: "Validator"},
,{label: "XPath Evaluator"}
*/
],
debugging : function() {
var body = Core.isXhtml ? document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "body")[0] : document.getElementsByTagName("body")[0];
if (this.debugMode) {
var dbg = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "div") : document.createElement("div");
dbg.setAttribute("style", "border-bottom: thin solid #888888;");
dbg.setAttribute("id", "xsltforms_debug");
var img = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "img") : document.createElement("img");
img.setAttribute("src", Core.ROOT+"magnify.png");
img.setAttribute("style", "vertical-align:middle;border:0;");
dbg.appendChild(img);
var spn = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "span") : document.createElement("span");
spn.setAttribute("style", "font-size:16pt");
var txt = document.createTextNode(" Debug Mode");
spn.appendChild(txt);
dbg.appendChild(spn);
var spn2 = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "span") : document.createElement("span");
spn2.setAttribute("style", "font-size:11pt");
var txt2 = document.createTextNode(" ("+this.fileVersion+") \xA0\xA0\xA0");
spn2.appendChild(txt2);
dbg.appendChild(spn2);
var a = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "a") : document.createElement("a");
a.setAttribute("href", "http://www.w3.org/TR/xforms11/");
a.setAttribute("style", "text-decoration:none;");
var img2 = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "img") : document.createElement("img");
img2.setAttribute("src", Core.ROOT+"valid-xforms11.png");
img2.setAttribute("style", "vertical-align:middle;border:0;");
a.appendChild(img2);
dbg.appendChild(a);
var a2 = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "a") : document.createElement("a");
a2.setAttribute("href", "http://www.agencexml.com/xsltforms");
a2.setAttribute("style", "text-decoration:none;");
var img3 = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "img") : document.createElement("img");
img3.setAttribute("src", Core.ROOT+"poweredbyXSLTForms.png");
img3.setAttribute("style", "vertical-align:middle;border:0;");
a2.appendChild(img3);
dbg.appendChild(a2);
var spn3 = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "span") : document.createElement("span");
spn3.setAttribute("style", "font-size:11pt");
var txt3 = document.createTextNode(" Press ");
spn3.appendChild(txt3);
dbg.appendChild(spn3);
var a3 = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "a") : document.createElement("a");
a3.setAttribute("onClick", "xforms.debugMode=false;xforms.debugging();return false;");
a3.setAttribute("style", "text-decoration:none;");
a3.setAttribute("href", "#");
var img4 = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "img") : document.createElement("img");
img4.setAttribute("src", Core.ROOT+"F1.png");
img4.setAttribute("style", "vertical-align:middle;border:0;");
a3.appendChild(img4);
dbg.appendChild(a3);
var spn4 = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "span") : document.createElement("span");
spn4.setAttribute("style", "font-size:11pt");
var txt4 = document.createTextNode(" to toggle mode ");
spn4.appendChild(txt4);
dbg.appendChild(spn4);
var br = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "br") : document.createElement("br");
dbg.appendChild(br);
var txt5 = document.createTextNode(" \xA0\xA0\xA0\xA0\xA0\xA0");
dbg.appendChild(txt5);
for (var i = 0, len = xforms.debugButtons.length; i < len; i++) {
if (xforms.debugButtons[i].action) {
var btn = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "button") : document.createElement("button");
btn.setAttribute("onClick", xforms.debugButtons[i].action);
var txt6 = document.createTextNode(" "+xforms.debugButtons[i].label+" ");
btn.appendChild(txt6);
dbg.appendChild(btn);
} else {
var a4 = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "a") : document.createElement("a");
a4.setAttribute("href", "http://www.agencexml.com/xsltforms");
var txt7 = document.createTextNode(" Debugging extensions can be downloaded! ");
a4.appendChild(txt7);
dbg.appendChild(a4);
break;
}
}
var br2 = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "br") : document.createElement("br");
dbg.appendChild(br2);
var ifr = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "iframe") : document.createElement("iframe");
ifr.setAttribute("src", "http://www.agencexml.com/direct/banner.htm");
ifr.setAttribute("style", "width:100%;height:90px;border:none;margin:0;");
ifr.setAttribute("frameborder", "0");
dbg.appendChild(ifr);
body.insertBefore(dbg, body.firstChild);
document.getElementById('xsltforms_console').style.display = "block";
} else {
body.removeChild(document.getElementById("xsltforms_debug"));
document.getElementById('xsltforms_console').style.display = "none";
}
},
profiling : function() {
var s = "XSLTForms Profiler:\n";
s += "\nXForms Instances:";
var pos = 0;
for (var m = 0, mlen = xforms.models.length; m < mlen; m++) {
if (xforms.models[m].element.id != "xf-model-config") {
for (var i in xforms.models[m].instances) {
var count = Core.selectNodesLength("descendant::node() | descendant::*/@*[not(starts-with(local-name(),'xsltforms_'))]", xforms.models[m].instances[i].doc);
s += (pos % 3 == 0 ? "\n " : ", ") + "\"" + i + "\": " + count + " node" + (count > 1? "s" : "");
pos++;
}
}
}
s += "\nXForms Controls:";
s += "\n " + xforms.counters.group + " group" + (xforms.counters.group > 1? "s" : "");
s += ", " + xforms.counters.input + " input" + (xforms.counters.input > 1? "s" : "");
s += ", " + xforms.counters.item + " item" + (xforms.counters.item > 1? "s" : "");
s += ", " + xforms.counters.itemset + " itemset" + (xforms.counters.itemset > 1? "s" : "");
s += "\n " + xforms.counters.output + " output" + (xforms.counters.output > 1? "s" : "");
s += ", " + xforms.counters.repeat + " repeat" + (xforms.counters.repeat > 1? "s" : "");
s += ", " + xforms.counters.select + " select" + (xforms.counters.select > 1? "s" : "");
s += ", " + xforms.counters.trigger + " trigger" + (xforms.counters.trigger > 1? "s" : "");
s += "\nHTML Time: " + this.htmltime + "ms";
s += "\nCreating Time: " + this.creatingtime + "ms";
s += "\nInit Time: " + this.inittime + "ms";
s += "\nRefresh Counter: " + this.refreshcount;
s += "\nCumulative Refresh Time: " + this.refreshtime + "ms";
var exprtab = [];
for (var expr in XPath.expressions) {
exprtab[exprtab.length] = {expr: expr, evaltime: XPath.expressions[expr].evaltime};
}
exprtab.sort(function(a,b) { return b.evaltime - a.evaltime; });
var top = 0;
if (exprtab.length > 0) {
s += "\nXPath Evaluation:";
for (var i = 0; i < exprtab.length && i < 20; i++) {
s += "\n \"" + (exprtab[i].expr.length > 60 ? exprtab[i].expr.substring(0,60)+"..." : exprtab[i].expr) + "\": " + exprtab[i].evaltime + "ms";
top += exprtab[i].evaltime;
}
if (exprtab.length > 20) {
var others = 0;
for (var i = 20; i < exprtab.length; i++) {
others += exprtab[i].evaltime;
}
s += "\n Others (" + (exprtab.length - 20) + " expr.): " + others + "ms";
top += others;
s += "\n Total: " + top + "ms";
}
}
alert(s);
},
init : function() {
setValue(document.getElementById("statusPanel"), I8N.get("status"));
var b = Core.isXhtml ? document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "body")[0] : document.getElementsByTagName("body")[0];
this.body = b;
document.onhelp = new Function("return false;");
window.onhelp = new Function("return false;");
XSLTFormsEvent.attach(document, "keydown", function(evt) {
if (evt.keyCode == 112) {
xforms.debugMode = !xforms.debugMode;
xforms.debugging();
if (evt.stopPropagation) {
evt.stopPropagation();
evt.preventDefault();
} else {
evt.cancelBubble = true;
}
return false;
}
});
XSLTFormsEvent.attach(b, "click", function(evt) {
var target = XSLTFormsEvent.getTarget(evt);
var parent = target;
while (parent && parent.nodeType == NodeType.ELEMENT) {
if (Core.hasClass(parent, "xforms-repeat-item")) {
XFRepeat.selectItem(parent);
}
parent = parent.parentNode;
}
parent = target;
while (parent && parent.nodeType == NodeType.ELEMENT) {
var xf = parent.xfElement;
if (xf) {
if(typeof parent.node != "undefined" && parent.node != null && xf.focus && !Core.getBoolMeta(parent.node, "readonly")) {
var name = target.nodeName.toLowerCase();
xf.focus(name == "input" || name == "textarea");
}
if(xf.click) {
xf.click(target);
break;
}
}
parent = parent.parentNode;
}
} );
XSLTFormsEvent.onunload = function() {
xforms.close();
};
this.openAction();
XMLEvents.dispatchList(this.models, "xforms-model-construct");
this.refresh();
this.closeAction();
this.ready = true;
Dialog.hide("statusPanel", false);
},
close : function() {
if (xforms.body) {
xforms.openAction();
//XMLEvents.dispatchList(xforms.models, "xforms-model-destruct");
for (var i = 0, len = Listener.destructs.length; i < len; i++) {
Listener.destructs[i].callback({target: Listener.destructs[i].observer});
}
xforms.closeAction();
IdManager.clear();
xforms.defaultModel = null;
xforms.changes = [];
xforms.models = [];
xforms.body = null;
xforms.cont = 0;
xforms.dispose(document.documentElement);
//XSLTFormsEvent.flush_();
if (XSLTFormsEvent.cache) {
for (var i = XSLTFormsEvent.cache.length - 1; i >= 0; i--) {
var item = XSLTFormsEvent.cache[i];
XSLTFormsEvent.detach(item[0], item[1], item[2], item[3]);
}
}
Listener.destructs = [];
Schema.all = {};
TypeDefs.initAll();
Calendar.INSTANCE = null;
xforms.ready = false;
xforms.building = false;
xforms.posibleBlur = false;
}
},
openAction : function() {
if (this.cont++ == 0) {
DebugConsole.clear();
}
},
closeAction : function() {
if (this.cont == 1) {
this.closeChanges();
}
this.cont--;
},
closeChanges : function() {
var changes = this.changes;
for (var i = 0, len = changes.length; i < len; i++) {
var change = changes[i];
if (change.instances) {//Model
if (change.rebuilded) {
XMLEvents.dispatch(change, "xforms-rebuild");
} else {
XMLEvents.dispatch(change, "xforms-recalculate");
}
} else { // Repeat or tree
}
}
if (changes.length > 0) {
this.refresh();
if (this.changes.length > 0) {
this.closeChanges();
}
}
},
error : function(element, event, message, causeMessage) {
Dialog.hide("statusPanel", false);
setValue(document.getElementById("statusPanel"), message);
Dialog.show("statusPanel", null, false);
if (element != null) {
XMLEvents.dispatch(element, event);
}
if (causeMessage) {
message += " : " + causeMessage;
}
DebugConsole.write("Error: " + message);
throw event;
},
refresh : function() {
var d1 = new Date();
this.building = true;
this.build(this.body, (this.defaultModel.getInstanceDocument() ? this.defaultModel.getInstanceDocument().documentElement : null), true);
if (this.newChanges.length > 0) {
this.changes = this.newChanges;
this.newChanges = [];
} else {
this.changes.length = 0;
}
for (var i = 0, len = this.models.length; i < len; i++) {
var model = this.models[i];
if (model.newNodesChanged.length > 0 || model.newRebuilded) {
model.nodesChanged = model.newNodesChanged;
model.newNodesChanged = [];
model.rebuilded = model.newRebuilded;
model.newRebuilded = false;
} else {
model.nodesChanged.length = 0;
model.rebuilded = false;
}
}
this.building = false;
// Throw any gathered binding-errors.
//
if (this.bindErrMsgs.length) {
this.error(this.defaultModel, "xforms-binding-exception", "Binding Errors: \n" + this.bindErrMsgs.join("\n "));
this.bindErrMsgs = [];
}
var d2 = new Date();
this.refreshtime += d2 - d1;
this.refreshcount++;
},
build : function(element, ctx, selected) {
if ( element.nodeType != NodeType.ELEMENT
|| element.id == "xsltforms_console" || element.hasXFElement == false) { return; }
var xf = element.xfElement;
var hasXFElement = !!xf;
if (element.getAttribute("mixedrepeat") == "true") {
ctx = element.node || ctx;
selected = element.selected;
}
//if (!ctx) { alert("xforms.build " + element.id + " no ctx"); }
if (xf) {
xf.build(ctx);
if (xf.isRepeat) {
xf.refresh(selected);
}
}
ctx = element.node || ctx;
var childs = element.childNodes;
var sel = element.selected;
if (typeof sel != "undefined") {
selected = sel;
}
if (!xf || !xf.isRepeat || xf.nodes.length > 0) {
for (var i = 0; i < childs.length && this.building; i++) {
hasXFElement = (childs[i].nodeType == NodeType.ELEMENT && !childs[i].getAttribute("cloned") ? this.build(childs[i], ctx, selected) : false) || hasXFElement;
}
}
if(this.building) {
if (xf && xf.changed) {
xf.refresh(selected);
xf.changed = false;
}
if (element.hasXFElement == null) {
element.hasXFElement = hasXFElement;
}
}
return hasXFElement;
},
addChange : function(element) {
var list = this.building? this.newChanges : this.changes;
if (!inArray(element, list)) {
list.push(element);
}
},
dispose : function(element) {
if (element.nodeType != NodeType.ELEMENT || element.id == "xsltforms_console") { return; }
element.listeners = null;
element.node = null;
element.hasXFElement = null;
var xf = element.xfElement;
if (xf) {
xf.dispose();
}
var childs = element.childNodes;
for (var i = 0; i < childs.length; i++) {
this.dispose(childs[i]);
}
},
blur : function(direct) {
if ((direct || this.posibleBlur) && this.focus) {
if(this.focus.element) {
this.openAction();
XMLEvents.dispatch(this.focus, "DOMFocusOut");
Core.setClass(this.focus.element, "xforms-focus", false);
this.focus.blur();
this.closeAction();
}
this.posibleBlur = false;
this.focus = null;
}
}
};
function Binding(isvalue, xpath, model, bind) {
this.isvalue = isvalue;
this.bind = bind? bind : null;
this.xpath = xpath? XPath.get(xpath) : null;
var modelelt = model;
if( typeof model == "string" ) {
modelelt = document.getElementById(model);
}
this.model = model? (modelelt != null ? modelelt.xfElement : model) : null;
}
Binding.prototype.evaluate = function(ctx, depsNodes, depsId, depsElements) {
//alert("Binding: "+depsId);
var result = null;
if (this.bind) {
if (typeof this.bind == "string") {
var idel = document.getElementById(this.bind);
if (!idel) {
DebugConsole.write("Binding evaluation returned null for bind: " + this.bind);
return null; // A 'null' signifies bind-ID not found.
}
this.bind = idel.xfElement;
}
result = this.bind.nodes;
copyArray(this.bind.depsNodes, depsNodes);
copyArray(this.bind.depsElements, depsElements);
/*
if(this.bind.depsNodes) {
var s = this.bind.depsNodes.length > 0 ? "Binding: "+depsId+" depsNodes=" : "";
for(var i = 0; i < this.bind.depsNodes.length; i++) s += this.bind.depsNodes[i].nodeName + " ";
if(s!="")alert(s);
}
*/
} else {
var exprCtx = new ExprContext(!ctx || (this.model && this.model != document.getElementById(Core.getMeta(ctx.ownerDocument.documentElement, "model")).xfElement) ? this.model ? this.model.getInstanceDocument().documentElement : xforms.defaultModel.getInstanceDocument().documentElement : ctx,
null, null, null, null, ctx, depsNodes, depsId, depsElements);
result = this.xpath.evaluate(exprCtx);
/*
if(exprCtx.depsNodes) {
var s = exprCtx.depsNodes.length > 0 ? "Binding: "+depsId+" depsNodes=" : "";
for(var i = 0; i < exprCtx.depsNodes.length; i++) s += exprCtx.depsNodes[i].nodeName + " ";
if(s!="")alert(s);
}
*/
}
assert(this.isvalue || result == null || typeof result == "object", "Binding evaluation didn't returned a nodeset but '"+(typeof result == "object" ? "" : result)+"' for " + (this.bind ? "bind: " + this.bind : "XPath expression: " + this.xpath.expression));
return this.isvalue ? stringValue(result) : result;
};
var IdManager = {
cloneId : function(element) {
assert(element && element.id);
var id = element.getAttribute("oldid") || element.id;
var list = this.data[id];
if (!list) {
list = [];
this.data[id] = list;
}
var newId = "clonedId" + this.index++;
list.push(newId);
element.setAttribute("oldid", id);
element.id = newId;
},
find : function(id) {
var ids = this.data[id];
if (ids) {
for (var i = 0, len = ids.length; i < len; i++) {
var element = document.getElementById(ids[i]);
if (element) {
var parent = element.parentNode;
while (parent.nodeType == NodeType.ELEMENT) {
if (Core.hasClass(parent, "xforms-repeat-item")) {
if (Core.hasClass(parent, "xforms-repeat-item-selected")) {
return element;
} else {
break;
}
}
parent = parent.parentNode;
}
}
}
}
var res = document.getElementById(id);
//if (!res) {
//alert("element " + id + " not found");
//}
return res;
},
clear : function() {
for (var i = 0, len = this.data.length; i < len; i++) {
this.data[i] = null;
}
this.data = [];
index = 0;
},
data : [],
index : 0
};
function XFCoreElement() {
}
XFCoreElement.prototype.init = function(id, parent, className) {
parent = parent? parent.element : Core.isXhtml ? document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "head")[0]: document.getElementsByTagName("head")[0];
this.element = Core.createElement("span", parent, null, className);
this.element.id = id;
this.element.xfElement = this;
};
XFCoreElement.prototype.dispose = function() {
this.element.xfElement = null;
this.element.parentNode.removeChild(this.element);
this.element = null;
this.model = null;
};
function XFModel(id, schemas) {
this.init(id, null, "xforms-model");
this.instances = {};
this.binds = [];
this.nodesChanged = [];
this.newNodesChanged = [];
this.schemas = [];
this.defaultInstance = null;
this.defaultSubmission = null;
xforms.models.push(this);
xforms.defaultModel = xforms.defaultModel || this;
if (document.getElementById(id)) {
document.getElementById(id).getInstanceDocument = function(modid) {
return this.xfElement.getInstanceDocument(modid);
};
document.getElementById(id).rebuild = function() {
return this.xfElement.rebuild();
};
document.getElementById(id).recalculate = function() {
return this.xfElement.recalculate();
};
document.getElementById(id).revalidate = function() {
return this.xfElement.revalidate();
};
document.getElementById(id).refresh = function() {
return this.xfElement.refresh();
};
document.getElementById(id).reset = function() {
return this.xfElement.reset();
};
}
if (schemas) {
schemas = schemas.split(" ");
for (var i = 0, len = schemas.length; i < len; i++) {
var founded = false;
for (var sid in Schema.all) {
var schema = Schema.all[sid];
if (schema.name == schemas[i]) {
this.schemas.push(schema);
founded = true;
break;
}
}
if (!founded) {
xforms.error(this, "xforms-link-exception", "Schema " + schemas[i] + " not found");
}
}
}
}
XFModel.prototype = new XFCoreElement();
XFModel.prototype.addInstance = function(instance) {
this.instances[instance.element.id] = instance;
this.defaultInstance = this.defaultInstance || instance;
};
XFModel.prototype.addBind = function(bind) {
this.binds.push(bind);
};
XFModel.prototype.dispose = function() {
this.instances = null;
this.binds = null;
this.defaultInstance = null;
XFCoreElement.prototype.dispose.call(this);
};
XFModel.prototype.getInstance = function(id) {
return id? this.instances[id] : this.defaultInstance;
};
XFModel.prototype.getInstanceDocument = function(id) {
var instance = this.getInstance(id);
return instance? instance.doc : null;
};
XFModel.prototype.findInstance = function(node) {
var doc = node.nodeType == NodeType.DOCUMENT ? node : node.ownerDocument;
for (var id in this.instances) {
var inst = this.instances[id];
if (doc == inst.doc) {
return inst;
}
}
return null;
};
XFModel.prototype.construct = function() {
if (!xforms.ready) {
forEach(this.instances, "construct");
}
XMLEvents.dispatch(this, "xforms-rebuild");
XMLEvents.dispatch(this, "xforms-model-construct-done");
if (this == xforms.models[xforms.models.length - 1]) {
window.setTimeout("XMLEvents.dispatchList(xforms.models, \"xforms-ready\")", 1);
}
};
XFModel.prototype.reset = function() {
forEach(this.instances, "reset");
this.setRebuilded(true);
xforms.addChange(this);
};
XFModel.prototype.rebuild = function() {
if (xforms.ready) {
this.setRebuilded(true);
}
forEach(this.binds, "refresh");
XMLEvents.dispatch(this, "xforms-recalculate");
};
XFModel.prototype.recalculate = function() {
forEach(this.binds, "recalculate");
XMLEvents.dispatch(this, "xforms-revalidate");
};
XFModel.prototype.revalidate = function() {
forEach(this.instances, "revalidate");
if (xforms.ready) {
XMLEvents.dispatch(this, "xforms-refresh");
}
};
XFModel.prototype.refresh = function() {
// Nada?
};
XFModel.prototype.addChange = function(node) {
var list = xforms.building? this.newNodesChanged : this.nodesChanged;
if (!inArray(node, list)) {
xforms.addChange(this);
}
if (node.nodeType == NodeType.ATTRIBUTE && !inArray(node, list)) {
list.push(node);
node = node.ownerElement ? node.ownerElement : node.selectSingleNode("..");
}
while (node.nodeType == NodeType.ELEMENT && !inArray(node, list)) {
list.push(node);
node = node.parentNode;
}
};
XFModel.prototype.setRebuilded = function(value) {
if (xforms.building) {
this.newRebuilded = value;
} else {
this.rebuilded = value;
}
};
function XFInstance(id, model, readonly, mediatype, src, srcXML) {
this.init(id, model, "xforms-instance");
this.readonly = readonly;
this.mediatype = mediatype;
this.src = Core.unescape(src);
switch(mediatype) {
case "application/xml":
this.srcXML = Core.unescape(srcXML);
break;
case "application/json":
var json;
eval("json = " + Core.unescape(srcXML));
this.srcXML = json2xml("", json, true, false);
break;
default:
alert("Unsupported mediatype '" + mediatype + "' for instance #" + id);
return;
}
this.model = model;
this.doc = Core.createXMLDocument("<dummy/>");
Core.setMeta(this.doc.documentElement, "instance", id);
Core.setMeta(this.doc.documentElement, "model", model.element.id);
model.addInstance(this);
}
XFInstance.prototype = new XFCoreElement();
XFInstance.prototype.dispose = function() {
XFCoreElement.prototype.dispose.call(this);
};
XFInstance.prototype.construct = function() {
if (!xforms.ready) {
if (this.src) {
var cross = false;
if (this.src.match(/^[a-zA-Z0-9+.-]+:\/\//)) {
var domain = /^([a-zA-Z0-9+.-]+:\/\/[^\/]*)/;
var sdom = domain.exec(this.src);
var ldom = domain.exec(document.location.href);
cross = sdom[0] != ldom[0];
}
if (cross) {
this.setDoc('<dummy xmlns=""/>');
jsoninstobj = this;
var scriptelt = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "script") : document.createElement("script");
scriptelt.setAttribute("src", this.src+((this.src.indexOf("?") == -1) ? "?" : "&")+"callback=jsoninst");
scriptelt.setAttribute("id", "jsoninst");
scriptelt.setAttribute("type", "text/javascript");
var body = Core.isXhtml ? document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "body")[0] : document.getElementsByTagName("body")[0];
body.insertBefore(scriptelt, body.firstChild);
} else {
try {
var req = Core.openRequest("GET", this.src, false);
DebugConsole.write("Loading " + this.src);
req.send(null);
if (req.status != 0 && (req.status < 200 || req.status >= 300)) {
throw "Request error: " + req.status;
}
this.setDoc(req.responseText);
} catch(e) {
xforms.error(this.element, "xforms-link-exception", "Fatal error loading " + this.src, e.toString());
}
}
} else {
this.setDoc(this.srcXML);
}
}
};
XFInstance.prototype.reset = function() {
this.setDoc(this.oldXML, true);
};
XFInstance.prototype.store = function(isReset) {
if (this.oldXML && !isReset) {
this.oldXML = null;
}
this.oldXML = Core.saveXML(this.doc.documentElement);
};
XFInstance.prototype.setDoc = function(xml, isReset, preserveOld) {
var instid = Core.getMeta(this.doc.documentElement, "instance");
var modid = Core.getMeta(this.doc.documentElement, "model");
Core.loadXML(this.doc.documentElement, xml);
Core.setMeta(this.doc.documentElement, "instance", instid);
Core.setMeta(this.doc.documentElement, "model", modid);
if (!preserveOld) {
this.store(isReset);
}
if (instid == "xf-instance-config") {
Core.config = this.doc.documentElement;
}
};
XFInstance.prototype.revalidate = function() {
if (!this.readonly) {
this.validation_(this.doc.documentElement);
}
};
XFInstance.prototype.validation_ = function(node, readonly, notrelevant) {
if (readonly == null) { readonly = false; }
if (notrelevant == null) { notrelevant = false; }
this.validate_(node, readonly, notrelevant);
readonly = Core.getBoolMeta(node, "readonly");
notrelevant = Core.getBoolMeta(node, "notrelevant");
var atts = node.attributes || [];
if (atts) {
var atts2 = [];
for (var i = 0, len = atts.length; i < len; i++) {
if (atts[i].nodeName.substr(0,10) != "xsltforms_") {
atts2[atts2.length] = atts[i];
}
}
for (var i = 0, len = atts2.length; i < len; i++) {
this.validation_(atts2[i], readonly, notrelevant);
}
}
for (var j = 0, len1 = node.childNodes.length; j < len1; j++) {
var child = node.childNodes[j];
if (child.nodeType == NodeType.ELEMENT) {
this.validation_(child, readonly, notrelevant);
}
}
};
XFInstance.prototype.validate_ = function(node, readonly, notrelevant) {
var bindids = Core.getMeta(node, "bind");
var value = xmlValue(node);
var schtyp = Schema.getType(Core.getType(node) || "xsd_:string");
if (bindids) {
var binds = bindids.split(" ");
var relevantfound = false;
var readonlyfound = false;
for (var i = 0, len = binds.length; i < len; i++) {
var bind = document.getElementById(binds[i]).xfElement;
var nodes = bind.nodes;
var i2 = 0;
for (var len2 = nodes.length; i2 < len2; i2++) {
if (nodes[i2] == node) {
break;
}
}
for (var j = 0, len2 = bind.depsNodes.length; j < len2; j++) {
Core.setFalseBoolMeta(bind.depsNodes[j], "depfor_"+bind.depsId);
}
bind.depsNodes.length = 0;
var ctx = new ExprContext(node, i2, nodes, null, null, null, [], bind.depsId);
if (bind.required) {
this.setProperty_(node, "required", booleanValue(bind.required.evaluate(ctx)));
}
if (notrelevant || !relevantfound || bind.relevant != undefined) {
this.setProperty_(node, "notrelevant", notrelevant || !(bind.relevant? booleanValue(bind.relevant.evaluate(ctx)) : true));
relevantfound = relevantfound || bind.relevant != undefined;
}
if (readonly || !readonlyfound || bind.readonly != undefined) {
this.setProperty_(node, "readonly", readonly || (bind.readonly? booleanValue(bind.readonly.evaluate(ctx)) : bind.calculate ? true : false));
readonlyfound = readonlyfound || bind.readonly != undefined;
}
this.setProperty_(node, "notvalid",
!Core.getBoolMeta(node, "notrelevant") && !(!(Core.getBoolMeta(node, "required") && (!value || value == ""))
&& (!schtyp || schtyp.validate(value))
&& (value == "" | !Core.getNil(node))
&& (!bind.constraint || booleanValue(bind.constraint.evaluate(ctx)))));
copyArray(ctx.depsNodes, bind.depsNodes);
}
} else {
this.setProperty_(node, "notrelevant", notrelevant);
this.setProperty_(node, "readonly", readonly);
this.setProperty_(node, "notvalid", schtyp && !schtyp.validate(value));
}
};
XFInstance.prototype.setProperty_ = function (node, property, value) {
if (Core.getBoolMeta(node, property) != value) {
Core.setBoolMeta(node, property, value);
this.model.addChange(node);
}
};
function json2xml(name, json, root, inarray) {
var fullname = "";
if (name == "________") {
fullname = " exml:fullname=\"" + Core.escape(name) + "\"";
name = "________";
}
var ret = root ? "<exml:anonymous xmlns:exml=\"http://www.agencexml.com/exml\" xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" xmlns:exsi=\"http://www.agencexml.com/exi\" xmlns=\"\">" : "";
if (json instanceof Array) {
if (inarray) {
ret += "<exml:anonymous exsi:maxOccurs=\"unbounded\">";
}
if (json.length == 0) {
ret += "<" + (name == "" ? "exml:anonymous" : name) + fullname + " exsi:maxOccurs=\"unbounded\" xsi:nil=\"true\"/>";
} else {
for (var i = 0, len = json.length; i < len; i++) {
ret += json2xml(name == "" ? "exml:anonymous" : name, json[i], false, true);
}
}
if (inarray) {
ret += "</exml:anonymous>";
}
} else {
var xsdtype = "";
switch(typeof(json)) {
case "number":
xsdtype = " xsi:type=\"xsd:double\"";
break;
case "boolean":
xsdtype = " xsi:type=\"xsd:boolean\"";
break;
case "object":
if (json instanceof Date) {
xsdtype = " xsi:type=\"xsd:dateTime\"";
}
break;
}
ret += name == "" ? "" : "<"+name+fullname+(inarray?" exsi:maxOccurs=\"unbounded\"":"")+xsdtype+">";
if (typeof(json) == "object" && !(json instanceof Date)) {
for (var m in json) {
ret += json2xml(m, json[m], false, false);
}
} else {
if (json instanceof Date) {
ret += json.getFullYear() + "-";
ret += (json.getMonth() < 9 ? "0" : "") + (json.getMonth()+1) + "-";
ret += (json.getDate() < 10 ? "0" : "") + json.getDate() + "T";
ret += (json.getHours() < 10 ? "0" : "") + json.getHours() + ":";
ret += (json.getMinutes() < 10 ? "0" : "") + json.getMinutes() + ":";
ret += (json.getSeconds() < 10 ? "0" : "") + json.getSeconds() + "Z";
} else {
ret += Core.escape(json);
}
}
ret += name == "" ? "" : "</"+name+">";
}
ret += root ? "</exml:anonymous>" : "";
return ret;
}
var jsoninstobj;
function jsoninst(json) {
//alert(json2xml("", json, true, false));
jsoninstobj.setDoc(json2xml("", json, true, false));
xforms.addChange(jsoninstobj.model);
XMLEvents.dispatch(jsoninstobj.model, "xforms-rebuild");
xforms.refresh();
document.body.removeChild(document.getElementById("jsoninst"));
}
function XFBind(id, parent, nodeset, type, readonly, required, relevant, calculate, constraint) {
this.init(id, parent, "xforms-bind");
this.model = parent.model || parent;
this.type = type? Schema.getType(type) : null;
this.nodeset = nodeset;
this.readonly = XPath.get(readonly);
this.required = XPath.get(required);
this.relevant = XPath.get(relevant);
this.calculate = XPath.get(calculate);
this.constraint = XPath.get(constraint);
this.depsNodes = [];
this.depsElements = [];
this.nodes = [];
this.binding = new Binding(false, this.nodeset);
parent.addBind(this);
this.depsId = XFElement.depsId++;
}
XFBind.prototype = new XFCoreElement();
XFBind.prototype.addBind = function() {};
XFBind.prototype.refresh = function(ctx, index) {
if (!index) {
for (var i = 0, len = this.depsNodes.length; i < len; i++) {
Core.setFalseBoolMeta(this.depsNodes[i], "depfor_"+this.depsId);
}
this.depsNodes.length = 0;
this.depsElements.length = 0;
this.nodes.length = 0;
}
ctx = ctx || (this.model ? this.model.getInstanceDocument() ? this.model.getInstanceDocument().documentElement : null : null);
copyArray(this.binding.evaluate(ctx, this.depsNodes, this.depsId, this.depsElements), this.nodes);
var el = this.element;
for (var i = 0, len = this.nodes.length; i < len; i++) {
var node = this.nodes[i];
var bindids = Core.getMeta(node, "bind");
if (!bindids) {
Core.setMeta(node, "bind", this.element.id);
} else {
var bindids2 = " "+bindids+" ";
if (bindids.indexOf(" "+this.element.id+" ") == -1) {
Core.setMeta(node, "bind", bindids+" "+this.element.id);
}
}
if (this.type) {
if (Core.getMeta(node, "schemaType")) {
XFProcessor.error(el, "xforms-binding-exception", "Type especified in xsi:type attribute");
} else {
var name = this.type.name;
var ns = this.type.nsuri;
for (var key in Schema.prefixes) {
if (Schema.prefixes[key] == ns) {
name = key + ":" + name;
break;
}
}
Core.setType(node, name);
}
}
for (var j = 0, len1 = el.childNodes.length; j < len1; j++) {
el.childNodes[j].xfElement.refresh(node, i);
}
}
};
XFBind.prototype.recalculate = function() {
var el = this.element;
if (this.calculate) {
for (var i = 0, len = this.nodes.length; i < len; i++) {
var node = this.nodes[i];
var ctx = new ExprContext(node, i + 1, this.nodes);
var value = stringValue(this.calculate.evaluate(ctx));
value = Schema.getType(Core.getType(node) || "xsd_:string").normalize(value);
setValue(node, value);
this.model.addChange(node);
DebugConsole.write("Calculate " + node.nodeName + " " + value);
}
}
for (var j = 0, len1 = el.childNodes.length; j < len1; j++) {
el.childNodes[j].xfElement.recalculate();
}
};
function XFSubmission(id, model, ref, bind, action, method, version, indent,
mediatype, encoding, omitXmlDeclaration, cdataSectionElements,
replace, targetref, instance, separator, includenamespaceprefixes, validate,
synchr, show, serialization) {
this.init(id, model, "xforms-submission");
this.model = model;
if (model.defaultSubmission == null) {
model.defaultSubmission = this;
}
this.action = action;
if (action.substr && action.substr(0,7) == "file://" && !document.applets["xsltforms"]) {
Core.loadapplet();
}
this.method = method;
this.replace = replace;
this.targetref = targetref;
this.version = version;
this.indent = indent;
this.validate = validate;
this.synchr = synchr;
this.show = show;
this.serialization = serialization;
if (mediatype != null) {
var lines = mediatype.split(";");
this.mediatype = lines[0];
for (var i = 1, len = lines.length; i < len; i++) {
var vals = lines[i].split("=");
switch (vals[0]) {
case "action" : this.soapAction = vals[1]; break;
case "charset" : this.charset = vals[1]; break;
}
}
}
this.encoding = encoding || "UTF-8";
this.omitXmlDeclaration = omitXmlDeclaration;
this.cdataSectionElements = cdataSectionElements;
this.instance = instance;
this.separator = separator == "&"? "&" : separator;
this.includenamespaceprefixes = includenamespaceprefixes;
this.headers = [];
if (ref || bind) {
this.binding = new Binding(false, ref, model.element, bind);
this.eval_ = function() {
return this.binding.evaluate()[0];
};
} else {
this.eval_ = function() {
return this.model.getInstanceDocument();
};
}
};
XFSubmission.prototype = new XFCoreElement();
XFSubmission.prototype.header = function(nodeset, combine, name, values) {
this.headers.push({nodeset: nodeset, combine: combine, name: name, values: values});
return this;
};
XFSubmission.prototype.submit = function() {
xforms.openAction();
var node = this.eval_();
var action = "error";
if(this.action.evaluate) {
action = stringValue(this.action.evaluate());
} else {
action = this.action;
}
var method = "post";
if(this.method.evaluate) {
var method = stringValue(this.method.evaluate());
} else {
method = this.method;
}
var evcontext = {"method": method, "resource-uri": action};
if (node) {
if (this.validate && !validate_(node)) {
evcontext["error-type"] = "validation-error";
this.issueSubmitException_(evcontext, null, null);
xforms.closeAction();
return;
}
if ((method == "get" || method == "delete") && this.serialization != "none") {
var tourl = XFSubmission.toUrl_(node, this.separator);
action += (action.indexOf('?') == -1? '?' : this.separator)
+ tourl.substr(0, tourl.length - this.separator.length);
}
}
XMLEvents.dispatch(this, "xforms-submit-serialize");
var ser = node ? Core.saveXML(node) : "";
var instance = this.instance;
if (action.substr(0,7) == "file://") {
var subm = this;
if (method == "put") {
if (!Core.writeFile(action.substr(7), subm.encoding, "string", "XSLTForms Java Saver", ser)) {
XMLEvents.dispatch(subm, "xforms-submit-error");
}
XMLEvents.dispatch(subm, "xforms-submit-done");
} else if (method == "get") {
ser = Core.readFile(action.substr(7), subm.encoding, "string", "XSLTForms Java Loader");
if (ser != "" && (subm.replace == "instance" || (subm.targetref && subm.replace == "text"))) {
var ctxnode = instance == null ? (node ? (node.documentElement ? node.documentElement : node.ownerDocument.documentElement) : subm.model.getInstance().documentElement) : document.getElementById(instance).xfElement.doc.documentElement;
if (subm.targetref) {
var targetnode = subm.targetref.evaluate(ctxnode);
if (targetnode && targetnode[0]) {
if (subm.replace == "instance") {
Core.loadXML(targetnode[0], ser);
} else {
Core.loadTextNode(targetnode[0], ser);
}
}
} else {
var inst = instance == null ? (node ? document.getElementById(Core.getMeta(node.documentElement ? node.documentElement : node.ownerDocument.documentElement, "instance")).xfElement : subm.model.getInstance()) : document.getElementById(instance).xfElement;
inst.setDoc(ser, false, true);
}
xforms.addChange(subm.model);
XMLEvents.dispatch(subm.model, "xforms-rebuild");
xforms.refresh();
XMLEvents.dispatch(subm, "xforms-submit-done");
} else {
XMLEvents.dispatch(subm, "xforms-submit-error");
}
}
xforms.closeAction();
return;
}
var synchr = this.synchr;
if(method == "xml-urlencoded-post") {
var outForm = document.getElementById("xsltforms_form");
if(outForm) {
outForm.firstChild.value = ser;
} else {
outForm = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "form") : document.createElement("form");
outForm.setAttribute("method", "post");
outForm.setAttribute("action", action);
outForm.setAttribute("id", "xsltforms_form");
var txt = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "input") : document.createElement("input");
txt.setAttribute("type", "hidden");
txt.setAttribute("name", "postdata");
txt.setAttribute("value", ser);
outForm.appendChild(txt);
body = Core.isXhtml ? document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "body")[0] : document.getElementsByTagName("body")[0];
body.insertBefore(outForm, body.firstChild);
}
outForm.submit();
xforms.closeAction();
} else {
var cross = false;
if (action.match(/^[a-zA-Z0-9+.-]+:\/\//)) {
var domain = /^([a-zA-Z0-9+.-]+:\/\/[^\/]*)/;
var sdom = domain.exec(action);
var ldom = domain.exec(document.location.href);
cross = sdom[0] != ldom[0];
}
if (cross) {
jsoninstobj = instance == null? (node ? document.getElementById(Core.getMeta(node.documentElement ? node.documentElement : node.ownerDocument.documentElement, "instance")).xfElement : this.model.getInstance()) : document.getElementById(instance).xfElement;
var scriptelt = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "script") : document.createElement("script");
scriptelt.setAttribute("src", action.replace(/&/g, "&")+((action.indexOf("?") == -1) ? "?" : "&")+"callback=jsoninst");
scriptelt.setAttribute("id", "jsoninst");
scriptelt.setAttribute("type", "text/javascript");
var body = Core.isXhtml ? document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "body")[0] : document.getElementsByTagName("body")[0];
body.insertBefore(scriptelt, body.firstChild);
XMLEvents.dispatch(this, "xforms-submit-done");
xforms.closeAction();
} else {
// TODO: Validate binding target is not empty
if (!node && (method != "get" || method != "delete")) {
evcontext["error-type"] = "no-data";
this.issueSubmitException_(evcontext, null, null);
return;
}
var req = null;
var subm = this;
try {
req = Core.openRequest(method, action, !synchr);
var func = function() {
if (!synchr && req.readyState != 4) { return; }
try {
if (req.status != 0 && (req.status < 200 || req.status >= 300)) {
evcontext["error-type"] = "resource-error";
subm.issueSubmitException_(evcontext, req, null);
xforms.closeAction();
return;
}
if (subm.replace == "instance" || (subm.targetref && subm.replace == "text")) {
if (subm.targetref) {
var ctxnode = instance == null ? (node ? (node.documentElement ? node.documentElement : node.ownerDocument.documentElement) : subm.model.getInstance().documentElement) : document.getElementById(instance).xfElement.doc.documentElement;
var targetnode = subm.targetref.evaluate(ctxnode);
if (targetnode && targetnode[0]) {
if (subm.replace == "instance") {
Core.loadXML(targetnode[0], req.responseText);
} else {
Core.loadTextNode(targetnode[0], req.responseText);
}
}
} else {
var inst = instance == null? (node ? document.getElementById(Core.getMeta(node.documentElement ? node.documentElement : node.ownerDocument.documentElement, "instance")).xfElement : subm.model.getInstance()) : document.getElementById(instance).xfElement;
inst.setDoc(req.responseText, false, true);
}
xforms.addChange(subm.model);
XMLEvents.dispatch(subm.model, "xforms-rebuild");
xforms.refresh();
}
subm.requesteventlog(evcontext, req);
XMLEvents.dispatch(subm, "xforms-submit-done", null, null, null, null, evcontext);
xforms.closeAction();
if (subm.replace == "all") {
var resp = req.responseText;
var piindex = resp.indexOf("<?xml-stylesheet", 0);
while ( piindex != -1) {
var xslhref = resp.substr(piindex, resp.substr(piindex).indexOf("?>")).replace(/^.*href=\"([^\"]*)\".*$/, "$1");
resp = Core.transformText(resp, xslhref, false);
piindex = resp.indexOf("<?xml-stylesheet", 0);
}
if( subm.show == "new" ) {
w = window.open("about:blank","_blank");
w.document.write(resp);
w.document.close();
} else {
Dialog.hide("statusPanel", false);
xforms.close();
if(document.write) {
document.write(resp);
document.close();
} else {
//document.documentElement.parentNode.replaceChild(req.responseXML.documentElement,document.documentElement);
if (resp.indexOf("<?", 0) === 0) {
resp = resp.substr(resp.indexOf("?>")+2);
}
//alert(resp);
document.documentElement.innerHTML = resp;
}
}
}
} catch(e) {
DebugConsole.write(e || e.message);
evcontext["error-type"] = "parse-error";
subm.issueSubmitException_(evcontext, req, e);
xforms.closeAction();
}
};
if (!synchr) {
req.onreadystatechange = func;
}
var media = this.mediatype;
var mt = (media || "application/xml")
+ (this.charset? ";charset=" + this.charset : "");
DebugConsole.write("Submit " + this.method + " - " + mt + " - "
+ action + " - " + synchr);
var len = this.headers.length;
if (len != 0) {
var headers = [];
for (var i = 0, len = this.headers.length; i < len; i++) {
var nodes = [];
if (this.headers[i].nodeset) {
nodes = this.headers[i].nodeset.evaluate();
} else {
nodes = [subm.model.getInstanceDocument().documentElement];
}
var hname;
for (var n = 0, lenn = nodes.length; n < lenn; n++) {
if (this.headers[i].name.evaluate) {
hname = stringValue(this.headers[i].name.evaluate(nodes[n]));
} else {
hname = this.headers[i].name;
}
if (hname != "") {
var hvalue = "";
var j;
for (j = 0, len2 = this.headers[i].values.length; j < len2; j++) {
var hv = this.headers[i].values[j];
var hv2;
if (hv.evaluate) {
hv2 = stringValue(hv.evaluate(nodes[n]));
} else {
hv2 = hv;
}
hvalue += hv2;
if (j < len2 - 1) {
hvalue += ",";
}
}
var len3 = headers.length;
for (j = 0; j < len3; j++) {
if (headers[j].name == hname) {
switch (this.headers[i].combine) {
case "prepend":
headers[j].value = hvalue + "," + headers[j].value;
break;
case "replace":
headers[j].value = hvalue;
break;
default:
headers[j].value += "," + hvalue;
break;
}
break;
}
}
if (j == len3) {
headers.push({name: hname, value: hvalue});
}
}
}
}
for (var i = 0, len = headers.length; i < len; i++) {
req.setRequestHeader(headers[i].name, headers[i].value);
}
}
if (method == "get" || method == "delete") {
if (media == XFSubmission.SOAP_) {
req.setRequestHeader("Accept", mt);
} else {
if (subm.replace == "instance") {
req.setRequestHeader("Accept", "application/xml,text/xml");
}
}
req.send(null);
} else {
req.setRequestHeader("Content-Type", mt);
if (media == XFSubmission.SOAP_) {
req.setRequestHeader("SOAPAction", this.soapAction);
} else {
if (subm.replace == "instance") {
req.setRequestHeader("Accept", "application/xml,text/xml");
}
}
req.send(ser);
}
if (synchr) {
func();
}
} catch(e) {
DebugConsole.write(e.message || e);
evcontext["error-type"] = "resource-error";
subm.issueSubmitException_(evcontext, req, e);
xforms.closeAction();
}
}
}
};
XFSubmission.SOAP_ = "application/soap+xml";
XFSubmission.prototype.requesteventlog = function(evcontext, req) {
evcontext["response-status-code"] = req.status;
evcontext["response-reason-phrase"] = req.statusText;
var rheads = req.getAllResponseHeaders();
var rheaderselts = "";
if (rheads) {
rheads = rheads.replace(/\r/, "").split("\n");
for (var i = 0, len = rheads.length; i < len; i++) {
var colon = rheads[i].indexOf(":");
if (colon != -1) {
var name = rheads[i].substring(0, colon).replace(/^\s+|\s+$/, "");
var value = rheads[i].substring(colon+1).replace(/^\s+|\s+$/, "");
rheaderselts += "<header><name>"+Core.escape(name)+"</name><value>"+Core.escape(value)+"</value></header>";
}
}
}
evcontext.rheadsdoc = Core.createXMLDocument("<data>"+rheaderselts+"</data>");
if (evcontext.rheadsdoc.documentElement.firstChild) {
var rh = evcontext.rheadsdoc.documentElement.firstChild;
evcontext["response-headers"] = [rh];
while (rh.nextSibling) {
rh = rh.nextSibling;
evcontext["response-headers"].push(rh);
}
}
if (req.responseXML) {
evcontext["response-body"] = [Core.createXMLDocument(req.responseText)];
} else {
evcontext["response-body"] = req.responseText || "";
}
};
XFSubmission.prototype.issueSubmitException_ = function(evcontext, req, ex) {
if (ex) {
evcontext["message"] = ex.message || ex;
evcontext["stack-trace"] = ex.stack;
}
if (req) {
this.requesteventlog(evcontext, req);
}
XMLEvents.dispatch(this, "xforms-submit-error", null, null, null, null, evcontext);
};
XFSubmission.toUrl_ = function(node, separator) {
var url = "";
var val = "";
var hasChilds = false;
for(var i = 0, len = node.childNodes.length; i < len; i++) {
var child = node.childNodes[i];
switch (child.nodeType) {
case NodeType.ELEMENT :
hasChilds = true;
url += this.toUrl_(child, separator);
break;
case NodeType.TEXT :
val += child.nodeValue;
break;
}
}
if (!hasChilds && val.length > 0) {
url += node.nodeName + '=' + encodeURIComponent(val) + separator;
}
return url;
};
var XFProcessor = {
error : function(element, type, value) {
alert(type+": "+value);
}
};
function AJXTimer(id, time) {
this.init(id, null, "xforms-timer");
this.running = false;
this.time = time;
}
AJXTimer.prototype = new XFCoreElement();
AJXTimer.prototype.start = function() {
this.running = true;
var timer = this;
setTimeout(function() { timer.run(); }, this.time);
};
AJXTimer.prototype.stop = function() {
this.running = false;
};
AJXTimer.prototype.run = function() {
if (this.running) {
var timer = this;
xforms.openAction();
XMLEvents.dispatch(timer.element, "ajx-time");
xforms.closeAction();
setTimeout(function() { timer.run(); }, this.time);
}
};
function AJXConfirm(id, binding, ifexpr, whileexpr) {
this.id = id;
this.binding = binding;
this.init(ifexpr, whileexpr);
}
AJXConfirm.prototype = new XFAbstractAction();
AJXConfirm.prototype.run = function(element, ctx, evt) {
var text;
if (this.binding) {
var node = this.binding.evaluate(ctx)[0];
if (node) {
text = getValue(node);
}
} else {
var e = IdManager.find(this.id);
xforms.build(e, ctx);
text = e.textContent || e.innerText;
}
if (text) {
var res = confirm(text.trim());
if (!res) {
evt.stopPropagation();
evt.stopped = true;
}
}
};
function AJXSetproperty(name, value, literal, ifexpr, whileexpr) {
this.name = name;
this.value = value;
this.literal = literal;
this.init(ifexpr, whileexpr);
}
AJXSetproperty.prototype = new XFAbstractAction();
AJXSetproperty.prototype.run = function(element, ctx) {
var value = this.literal;
if (this.value) {
value = this.value.evaluate(node); // ??? What is node?
if (typeof(value) != "string" && typeof(value.length) != "undefined") {
value = value.length > 0? getValue(value[0]) : "";
}
}
if (value) {
I8N.lang = value;
DebugConsole.write("setproperty " + name + " = " + value);
}
};
function XFAbstractAction() {
}
XFAbstractAction.prototype.init = function(ifexpr, whileexpr) {
this.ifexpr = XPath.get(ifexpr);
this.whileexpr = XPath.get(whileexpr);
};
XFAbstractAction.prototype.execute = function(element, ctx, evt) {
if (evt.stopped) { return; }
if (!ctx) {
ctx = element.node || (xforms.defaultModel.getInstanceDocument() ? xforms.defaultModel.getInstanceDocument().documentElement : null);
}
if (this.whileexpr) {
while(booleanValue(this.whileexpr.evaluate(ctx))) {
if(!this.exec_(element, ctx, evt)) {
break;
}
}
} else {
this.exec_(element, ctx, evt);
}
};
XFAbstractAction.prototype.exec_ = function(element, ctx, evt) {
if (this.ifexpr) {
if (booleanValue(this.ifexpr.evaluate(ctx))) {
this.run(element, ctx, evt);
} else {
return false;
}
} else {
this.run(element, ctx, evt);
}
return true;
};
XFAbstractAction.prototype.run = function(element, ctx, evt) { };
function XFAction(ifexpr, whileexpr) {
this.init(ifexpr, whileexpr);
this.childs = [];
}
XFAction.prototype = new XFAbstractAction();
XFAction.prototype.add = function(action) {
this.childs.push(action);
return this;
};
XFAction.prototype.run = function(element, ctx, evt) {
forEach(this.childs, "execute", element, ctx, evt);
};
function XFDelete(nodeset, model, bind, at, context, ifexpr, whileexpr) {
this.binding = new Binding(false, nodeset, model, bind);
//this.at = at?XPath.get(at):null;
this.at = XPath.get(at);
this.context = XPath.get(context);
this.init(ifexpr, whileexpr);
}
XFDelete.prototype = new XFAbstractAction();
XFDelete.prototype.run = function(element, ctx) {
if (this.context) {
ctx = this.context.evaluate(ctx)[0];
}
if (!ctx) { return; }
var nodes = this.binding.evaluate(ctx);
if(this.at) {
var index = numberValue(this.at.evaluate(new ExprContext(ctx, 1, nodes)));
if(!nodes[index - 1]) { return; }
nodes = [nodes[index - 1]];
}
var model;
var instance;
if( nodes.length > 0 ) {
model = document.getElementById(Core.getMeta(nodes[0].documentElement ? nodes[0].documentElement : nodes[0].ownerDocument.documentElement, "model")).xfElement;
instance = model.findInstance(nodes[0]);
}
for(var i = 0, len = nodes.length; i < len; i++) {
var node = nodes[i];
var repeat = Core.getMeta(node, "repeat");
if (node.nodeType == NodeType.ATTRIBUTE) {
node.ownerElement ? node.ownerElement.removeAttributeNS(node.namespaceURI, node.nodeName) : node.selectSingleNode("..").removeAttributeNS(node.namespaceURI, node.nodeName);
} else {
node.parentNode.removeChild(node);
}
if (repeat) {
document.getElementById(repeat).xfElement.deleteNode(node);
}
}
if( nodes.length > 0 ) {
xforms.addChange(model);
model.setRebuilded(true);
XMLEvents.dispatch(instance, "xforms-delete");
}
};
function XFDispatch(name, target, ifexpr, whileexpr, delay) {
this.name = name;
this.target = target;
this.init(ifexpr, whileexpr);
this.delay = delay;
}
XFDispatch.prototype = new XFAbstractAction();
XFDispatch.prototype.run = function(element, ctx, evt) {
var target;
if (this.target == null) {
switch (this.name) {
case "xforms-submit":
target = document.getElementById(Core.getMeta(ctx.ownerDocument.documentElement, "model")).xfElement.defaultSubmission;
break;
case "xforms-reset":
target = document.getElementById(Core.getMeta(ctx.ownerDocument.documentElement, "model")).xfElement;
break;
}
} else {
target = typeof this.target == "string"? document.getElementById(this.target) : this.target;
}
var delay = 0;
if (this.delay) {
if (this.delay.evaluate) {
delay = numberValue(this.delay.evaluate());
} else {
delay = numberValue(this.delay);
}
}
if (delay > 0 ) {
window.setTimeout("XMLEvents.dispatch(document.getElementById('"+target.id+"'),'"+this.name+"')", delay);
} else {
XMLEvents.dispatch(target, this.name);
}
};
function XFInsert(nodeset, model, bind, at, position, origin, context, ifexpr, whileexpr) {
this.binding = new Binding(false, nodeset, model, bind);
this.origin = XPath.get(origin);
this.context = XPath.get(context);
this.at = XPath.get(at);
this.position = position;
this.init(ifexpr, whileexpr);
}
XFInsert.prototype = new XFAbstractAction();
XFInsert.prototype.run = function(element, ctx) {
if (this.context) {
ctx = this.context.evaluate(ctx)[0];
}
if (!ctx) { return; }
var nodes = [];
if( this.binding.bind || this.binding.xpath ) {
nodes = this.binding.evaluate(ctx);
}
var index = 0;
var node = null;
var originNodes = [];
var parent = null;
var pos = this.position == "after"? 1 : 0;
var res = 0;
if (this.origin) {
originNodes = this.origin.evaluate(ctx);
}
if (originNodes.length === 0) {
if (nodes.length === 0) {
return;
}
originNodes.push(nodes[nodes.length - 1]);
}
for(var i = 0, len = originNodes.length; i < len; i += 1) {
node = originNodes[i];
if (nodes.length === 0) {
parent = ctx;
} else {
parent = nodes[0].nodeType == NodeType.DOCUMENT? nodes[0] : nodes[0].nodeType == NodeType.ATTRIBUTE? nodes[0].ownerDocument ? nodes[0].ownerDocument : nodes[0].selectSingleNode("..") : nodes[0].parentNode;
if (parent.nodeType != NodeType.DOCUMENT && node.nodeType != NodeType.ATTRIBUTE) {
res = this.at? Math.round(numberValue(this.at.evaluate(new ExprContext(ctx, 1, nodes)))) + i - 1: nodes.length - 1;
index = isNaN(res)? nodes.length : res + pos;
}
}
DebugConsole.write("insert " + node.nodeName + " in " + parent.nodeName
+ " at " + index + " - " + ctx.nodeName);
if (node.nodeType == NodeType.ATTRIBUTE) {
Core.setAttributeNS(parent, node.namespaceURI, (node.prefix ? node.prefix+":" : "")+node.nodeName, node.nodeValue);
} else {
var clone = node.cloneNode(true);
if (parent.nodeType == NodeType.DOCUMENT) {
var first = parent.documentElement;
var prevmodel = Core.getMeta(first, "model");
var previnst = Core.getMeta(first, "instance");
parent.removeChild(first);
first = null;
Core.setMeta(clone, "instance", previnst);
Core.setMeta(clone, "model", prevmodel);
parent.appendChild(clone);
} else {
var nodeAfter;
if (index >= nodes.length && nodes.length != 0) {
nodeAfter = nodes[nodes.length - 1].nextSibling;
} else {
nodeAfter = nodes[index];
}
if (nodeAfter) {
nodeAfter.parentNode.insertBefore(clone, nodeAfter);
} else {
parent.appendChild(clone);
}
var repeat = nodes.length > 0? Core.getMeta(nodes[0], "repeat") : null;
nodes.push(clone);
if (repeat) {
document.getElementById(repeat).xfElement.insertNode(clone, nodeAfter);
}
}
}
}
var model = document.getElementById(Core.getMeta(parent.documentElement ? parent.documentElement : parent.ownerDocument.documentElement, "model")).xfElement;
xforms.addChange(model);
model.setRebuilded(true);
XMLEvents.dispatch(model.findInstance(parent), "xforms-insert");
};
function XFLoad(binding, resource, show, ifexpr, whileexpr) {
this.binding = binding;
this.resource = resource;
this.show = show;
this.init(ifexpr, whileexpr);
}
XFLoad.prototype = new XFAbstractAction();
XFLoad.prototype.run = function(element, ctx) {
var href = this.resource;
if (this.binding) {
var node = this.binding.evaluate(ctx)[0];
if (node) {
href = getValue(node);
}
} else {
if (typeof href == 'object') {
href = stringValue(this.resource.xpath.evaluate(ctx));
} else {
if (typeof href == 'string') {
href = Core.unescape(href);
}
}
}
if (href) {
if(href.substr(0, 11) == "javascript:") {
try {
eval("{XSLTFormsContext={elementId:\""+element.getAttribute("id")+"\"};"+href.substr(11)+"}");
} catch (e) {
alert("XSLTForms Exception\n--------------------------\n\nError evaluating the following Javascript expression :\n\n"+href.substr(11)+"\n\n"+e);
}
} else if (this.show == "new") {
window.open(href);
} else {
location.href = href;
}
}
};
function XFMessage(id, binding, level, ifexpr, whileexpr) {
this.binding = binding;
this.id = id;
this.level = level;
this.init(ifexpr, whileexpr);
}
XFMessage.prototype = new XFAbstractAction();
XFMessage.prototype.run = function(element, ctx) {
var text;
if (this.binding) {
var node = this.binding.evaluate(ctx)[0];
if (node) {
text = getValue(node);
}
} else {
var e = IdManager.find(this.id);
var building = xforms.building;
xforms.building = true;
xforms.build(e, ctx);
xforms.building = building;
text = e.textContent || e.innerText;
}
if (text) {
alert(text.trim());
}
};
function XFScript(binding, stype, script, ifexpr, whileexpr) {
this.binding = binding;
this.stype = stype;
this.script = script;
this.init(ifexpr, whileexpr);
}
XFScript.prototype = new XFAbstractAction();
XFScript.prototype.run = function(element, ctx) {
var script = this.script;
switch (this.stype) {
case "text/javascript":
if (this.binding) {
var node = this.binding.evaluate(ctx)[0];
if (node) {
script = getValue(node);
}
} else {
if (typeof script == 'object') {
script = stringValue(this.script.xpath.evaluate(ctx));
} else {
if (typeof script == 'string') {
script = Core.unescape(script);
}
}
}
if (script) {
try {
eval("{XSLTFormsContext={elementId:\""+element.getAttribute("id")+"\"};"+script+"}");
} catch (e) {
alert("XSLTForms Exception\n--------------------------\n\nError evaluating the following Javascript expression :\n\n"+script+"\n\n"+e);
}
}
break;
case "application/xquery":
this.script.xpath.evaluate(ctx);
break;
}
};
function XFSetindex(repeat, index, ifexpr, whileexpr) {
this.repeat = repeat;
this.index = XPath.get(index);
this.init(ifexpr, whileexpr);
}
XFSetindex.prototype = new XFAbstractAction();
XFSetindex.prototype.run = function(element, ctx) {
var repeat = IdManager.find(this.repeat);
var index = numberValue(this.index.evaluate(ctx));
DebugConsole.write("setIndex " + index);
if (!isNaN(index)) {
repeat.xfElement.setIndex(index);
}
};
function XFSetvalue(binding, value, literal, ifexpr, whileexpr) {
this.binding = binding;
this.value = value? XPath.get(value) : null;
this.literal = literal;
this.init(ifexpr, whileexpr);
}
XFSetvalue.prototype = new XFAbstractAction();
XFSetvalue.prototype.run = function(element, ctx) {
var node = this.binding.evaluate(ctx)[0];
if (node) {
var value = this.value? stringValue(this.value.evaluate(node, ctx))
: this.literal;
xforms.openAction();
setValue(node, value || "");
document.getElementById(Core.getMeta(node.ownerDocument.documentElement, "model")).xfElement.addChange(node);
DebugConsole.write("Setvalue " + node.nodeName + " = " + value);
xforms.closeAction();
}
};
function XFToggle(caseId, ifexpr, whileexpr) {
this.caseId = caseId;
this.init(ifexpr, whileexpr);
}
XFToggle.prototype = new XFAbstractAction();
XFToggle.prototype.run = function(element, ctx) {
XFToggle.toggle(this.caseId, ctx);
};
XFToggle.toggle = function(caseId, ctx) {
xforms.openAction();
if (typeof caseId == 'object') {
if (!ctx) {
ctx = xforms.defaultModel.getInstanceDocument() ? xforms.defaultModel.getInstanceDocument().documentElement : null;
}
caseId = stringValue(caseId.xpath.evaluate(ctx));
}
var element = IdManager.find(caseId);
var childs = element.parentNode.childNodes;
var ul;
var index = -1;
if (childs.length > 0 && childs[0].nodeName.toLowerCase() == "ul") {
ul = childs[0];
}
for (var i = ul != null? 1 : 0, len = childs.length; i < len; i++) {
var child = childs[i];
if (child == element) {
index = i - 1;
} else {
if (child.style && child.style.display != "none") {
child.style.display = "none";
if (ul != null) {
Core.setClass(ul.childNodes[i - 1], "ajx-tab-selected", false);
}
}
XMLEvents.dispatch(child, "xforms-deselect");
}
}
if (element.style.display == "none") {
element.style.display = "block";
if (ul != null) {
Core.setClass(ul.childNodes[index], "ajx-tab-selected", true);
}
}
XMLEvents.dispatch(element, "xforms-select");
xforms.closeAction();
};
function AJXTree(id, binding) {
this.init(id);
this.binding = binding;
this.hasBinding = true;
this.root = Core.isXhtml ? this.element.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "ul")[0] : this.element.getElementsByTagName("ul")[0];
this.label = this.root.firstChild.cloneNode(true);
}
AJXTree.prototype = new XFElement();
AJXTree.prototype.dispose = function() {
this.root = null;
this.selected = null;
XFElement.prototype.dispose.call(this);
};
AJXTree.prototype.build_ = function(ctx) {
var node = this.evaluateBinding(this.binding, ctx)[0];
if (node) {
var nodes = [];
this.buildTree(this.root, 0, node, nodes);
if (!this.selected || !inArray(this.selected, nodes)) {
this.select(this.root.firstChild);
}
}
};
AJXTree.prototype.select = function(item) {
var changed = true;
var init = !!this.selected;
if (init) {
if (this.selected == item) {
changed = false;
} else {
Core.setClass(this.selected, "xforms-tree-item-selected", false);
Core.setClass(this.selected.childNodes[1], "xforms-tree-item-label-selected", false);
}
}
if (changed) {
this.element.node = item.node;
this.selected = item;
Core.setClass(item, "xforms-tree-item-selected", true);
Core.setClass(item.childNodes[1], "xforms-tree-item-label-selected", true);
xforms.openAction();
xforms.addChange(this);
xforms.addChange(document.getElementById(Core.getMeta(item.node.ownerDocument.documentElement, "model")).xfElement);
xforms.closeAction();
}
};
AJXTree.prototype.click = function(target) {
if (target.className == "xforms-tree-item-button") {
var ul = target.nextSibling.nextSibling;
if (ul != null) {
ul.style.display = ul.style.display != "none"? "none" : "block";
}
} else if (Core.hasClass(target, "xforms-tree-item-label")) {
this.select(target.parentNode);
}
};
AJXTree.prototype.buildTree = function(parent, index, node, nodes) {
var li = null;
var ul = null;
var label = null;
var childs = node.childNodes;
var nochild = childs.length === 0;
nodes.push(node);
if (parent.childNodes.length < index + 1) {
li = this.label.cloneNode(true);
parent.appendChild(li);
XFRepeat.initClone(li);
} else {
li = parent.childNodes[index];
var last = li.lastChild;
if (last.nodeName.toLowerCase() == "ul") {
ul = last;
if (nochild) {
xforms.dispose(ul);
li.removeChild(ul);
}
}
}
li.node = node;
Core.setClass(li, "xforms-tree-item-fork", !nochild);
Core.setClass(li, "xforms-tree-item-leaf", nochild);
for (var i = 0, len = childs.length; i < len; i++) {
var child = childs[i];
if (child.nodeType == NodeType.ELEMENT) {
if (!ul) {
ul = Core.createElement("ul", li);
}
this.buildTree(ul, i, child, nodes);
}
}
if (ul) {
for (var j = ul.childNodes.length, len1 = childs.length; j > len1; j--) {
xforms.dispose(ul.lastChild);
ul.removeChild(ul.lastChild);
}
}
};
AJXTree.prototype.refresh = function() {
};
function XFAVT(id, attrs) {
this.init(id);
this.attrs = attrs;
this.bindings = [];
for (var i = 0, len = attrs.length; i < len; i++) {
}
this.hasBinding = true;
this.isOutput = true;
}
XFAVT.prototype = new XFControl();
XFAVT.prototype.clone = function(id) {
return new XFAVT(id, this.attrs);
};
XFAVT.prototype.dispose = function() {
this.attrs = null;
XFControl.prototype.dispose.call(this);
};
XFAVT.prototype.setValue = function(value) {
var node = this.element.node;
var element = this.valueElement;
if (element.nodeName.toLowerCase() == "span") {
if (this.mediatype == "application/xhtml+xml") {
while (element.firstChild) {
element.removeChild(element.firstChild);
}
XDocument.parse(value, element);
} else {
setValue(element, value);
}
} else {
element.src = value;
}
};
function XFElement() {
}
XFElement.depsId = 0;
XFElement.prototype.init = function(id) {
this.element = document.getElementById(id);
this.element.xfElement = this;
this.depsElements = [];
this.depsNodesBuild = [];
this.depsNodesRefresh = [];
this.depsIdB = XFElement.depsId++;
this.depsIdR = XFElement.depsId++;
};
XFElement.prototype.dispose = function() {
if(this.element) {
this.element.xfElement = null;
this.element.hasXFElement = null;
this.element = null;
}
this.depsElements = null;
if (this.depsNodesBuild) {
for (var i = 0, len = this.depsNodesBuild.length; i < len; i++) {
Core.setFalseBoolMeta(this.depsNodesBuild[i], "depfor_"+this.depsIdB);
}
}
this.depsNodesBuild = null;
if (this.depsNodesRefresh) {
for (var i = 0, len = this.depsNodesRefresh.length; i < len; i++) {
Core.setFalseBoolMeta(this.depsNodesRefresh[i], "depfor_"+this.depsIdR);
}
}
this.depsNodesRefresh = null;
};
XFElement.prototype.build = function(ctx) {
if (this.hasBinding) {
var deps = this.depsElements;
var depsN = this.depsNodesBuild;
var depsR = this.depsNodesRefresh;
var build = !xforms.ready || (deps.length === 0) || ctx != this.ctx;
var refresh = false;
var changes = xforms.changes;
for (var i0 = 0, len0 = depsN.length; !build && i0 < len0; i0++) {
build = depsN[i0].nodeName == "";
}
for (var i = 0, len = deps.length; !build && i < len; i++) {
var el = deps[i];
for (var j = 0, len1 = changes.length; !build && j < len1; j++) {
if (el == changes[j]) {
if (el.instances) { //model
if (el.rebuilded || el.newRebuilded) {
build = true;
} else {
/*
var t = el.nodesChanged.concat(depsN);
t.sort();
for (var k = 0, len2 = t.length-1; !build && k < len2; k++) {
build = t[k] == t[k+1];
}
*/
for (var k = 0, len2 = depsN.length; !build && k < len2; k++) {
build = inArray(depsN[k], el.nodesChanged);
}
if (!build) {
/*
t = el.nodesChanged.concat(depsR);
t.sort();
for (var k = 0, len2 = t.length-1; !refresh && k < len2; k++) {
refresh = t[k] == t[k+1];
}
*/
for (var n = 0, len3 = depsR.length; n < len3; n++) {
refresh = inArray(depsR[n], el.nodesChanged);
}
}
}
} else {
build = true;
}
}
}
}
this.changed = build || refresh;
if (build) {
for (var i = 0, len = depsN.length; i < len; i++) {
Core.setFalseBoolMeta(depsN[i], "depfor_"+this.depsIdB);
}
depsN.length = 0;
for (var i = 0, len = depsR.length; i < len; i++) {
Core.setFalseBoolMeta(depsR[i], "depfor_"+this.depsIdR);
}
depsR.length = 0;
deps.length = 0;
this.ctx = ctx;
this.build_(ctx);
}
} else {
this.element.node = ctx;
}
};
XFElement.prototype.evaluateBinding = function(binding, ctx) {
var nodes = null;
var errmsg = null;
if (binding) {
nodes = binding.evaluate(ctx, this.depsNodesBuild, this.depsIdB, this.depsElements);
if (nodes != null) {
return nodes;
}
// A 'null' binding means bind-ID was not found.
errmsg = "non-existent bind-ID("+ binding.bind + ") on element(" + this.element.id + ")!";
} else {
errmsg = "no binding defined for element("+ this.element.id + ")!";
}
assert(errmsg);
if (xforms.building && xforms.debugMode) {
//
// Do not fail here, to keep on searching for more errors.
xforms.bindErrMsgs.push(errmsg);
XMLEvents.dispatch(this.element, "xforms-binding-exception");
nodes = [];
} else {
xforms.error(this.element, "xforms-binding-exception", errmsg);
}
return nodes;
};
function XFControl() {
this.isControl = true;
}
XFControl.prototype = new XFElement();
XFControl.prototype.initFocus = function(element, principal) {
if (principal) {
this.focusControl = element;
}
XSLTFormsEvent.attach(element, "focus", XFControl.focusHandler);
XSLTFormsEvent.attach(element, "blur", XFControl.blurHandler);
};
XFControl.prototype.dispose = function() {
this.focusControl = null;
XFElement.prototype.dispose.call(this);
};
XFControl.prototype.focus = function(focusEvent) {
if (this.isOutput) {
return;
}
if (xforms.focus != this) {
xforms.openAction();
xforms.blur(true);
xforms.focus = this;
Core.setClass(this.element, "xforms-focus", true);
Core.setClass(this.element, "xforms-disabled", false);
var parent = this.element.parentNode;
while (parent.nodeType == NodeType.ELEMENT) {
if (typeof parent.node != "undefined"
&& Core.hasClass(parent, "xforms-repeat-item")) {
XFRepeat.selectItem(parent);
}
parent = parent.parentNode;
}
XMLEvents.dispatch(xforms.focus, "DOMFocusIn");
xforms.closeAction();
if (this.full && !focusEvent) { // select full
this.focusFirst();
}
}
var fcontrol = this.focusControl;
xforms.posibleBlur = false;
if (fcontrol && !focusEvent) {
var control = this.focusControl;
var name = control.nodeName.toLowerCase();
control.focus();
control.focus();
if (name == "input" || name == "textarea") {
control.select();
}
}
};
XFControl.prototype.build_ = function(ctx) {
var result = this.evaluateBinding(this.binding, ctx);
if (typeof result == "object") {
var node = result[0];
var element = this.element;
var old = element.node;
if (old != node || !xforms.ready) {
element.node = node;
this.nodeChanged = true;
}
if (node) {
this.depsNodesRefresh.push(node);
}
} else {
this.outputValue = result;
}
};
XFControl.prototype.refresh = function() {
var element = this.element;
var node = element.node;
if (node) {
var value = getValue(node, true, this.complex);
xforms.openAction();
var changed = value != this.currentValue || this.nodeChanged;
if (this.relevant) {
Core.setClass(element, "xforms-disabled", false);
}
this.changeProp(node, "required", "xforms-required", "xforms-optional", changed, value);
this.changeProp(node, "notrelevant", "xforms-disabled", "xforms-enabled", changed, value);
this.changeProp(node, "readonly", "xforms-readonly", "xforms-readwrite", changed, value);
this.changeProp(node, "notvalid", "xforms-invalid", "xforms-valid", changed, value);
if (changed) {
this.currentValue = value;
this.setValue(value);
if (!this.nodeChanged && !this.isTrigger) {
XMLEvents.dispatch(element, "xforms-value-changed");
}
}
xforms.closeAction();
} else if (this.outputValue != null) {
this.setValue(this.outputValue);
Core.setClass(element, "xforms-disabled", false);
} else {
Core.setClass(element, "xforms-disabled", !this.hasValue);
}
this.nodeChanged = false;
};
XFControl.prototype.changeProp = function(node, prop, onTrue, onFalse, changed, nvalue) {
var value = Core.getMeta(node, prop);
if (changed || value != this[prop]) {
if (!this.nodeChanged && !this.isTrigger) {
XMLEvents.dispatch(this.element, (value? onTrue : onFalse));
}
this[prop] = value;
if (prop == "notvalid" && nvalue == "") {
value = false;
}
Core.setClass(this.element, onTrue, value);
Core.setClass(this.element, onFalse, !value);
if(prop == "readonly" && this.changeReadonly) {
this.changeReadonly();
}
}
};
XFControl.prototype.valueChanged = function(value) {
var node = this.element.node;
var model = document.getElementById(Core.getMeta(node.ownerDocument.documentElement, "model")).xfElement;
var schtyp = Schema.getType(Core.getType(node) || "xsd_:string");
if (value != null && value.length > 0 && schtyp.parse) {
try { value = schtyp.parse(value); } catch(e) { }
}
if (value != getValue(node)) {
xforms.openAction();
setValue(node, value);
model.addChange(node);
//XMLEvents.dispatch(model, "xforms-recalculate");
//xforms.refresh();
xforms.closeAction();
}
};
XFControl.getXFElement = function(element) {
var xf = null;
while (!xf && element) {
xf = element.xfElement;
if (xf && !xf.isControl) {
xf = null;
}
element = element.parentNode;
}
return xf;
};
XFControl.focusHandler = function() {
var xf = XFControl.getXFElement(this);
if (xforms.focus != xf) {
xf.focus(true);
} else {
xforms.posibleBlur = false;
}
};
XFControl.blurHandler = function() {
if (XFControl.getXFElement(this) == xforms.focus) {
xforms.posibleBlur = true;
setTimeout("xforms.blur()", 200);
}
};
function XFGroup(id, binding) {
xforms.counters.group++;
this.init(id);
if (binding) {
this.hasBinding = true;
this.binding = binding;
} else {
Core.setClass(this.element, "xforms-disabled", false);
}
}
XFGroup.prototype = new XFElement();
XFGroup.prototype.dispose = function() {
xforms.counters.group--;
XFElement.prototype.dispose.call(this);
};
XFGroup.prototype.clone = function(id) {
return new XFGroup(id, this.binding);
};
XFGroup.prototype.build_ = function(ctx) {
var nodes = this.evaluateBinding(this.binding, ctx);
this.element.node = nodes[0];
this.depsNodesRefresh.push(nodes[0]);
};
XFGroup.prototype.refresh = function() {
var element = this.element;
var disabled = !element.node || Core.getBoolMeta(element.node, "notrelevant");
Core.setClass(element, "xforms-disabled", disabled);
/** Tabs */
var ul = element.parentNode.firstChild;
if (ul.nodeName.toLowerCase() == "ul") {
var childs = element.parentNode.childNodes;
var tab;
for (var i = 1, len = childs.length; i < len; i++) {
if (childs[i] == element) {
tab = ul.childNodes[i - 1];
}
}
Core.setClass(tab, "xforms-disabled", disabled);
}
};
function XFInput(id, itype, binding, inputmode, incremental, delay, aidButton, clone) {
xforms.counters.input++;
this.init(id);
this.binding = binding;
this.inputmode = typeof inputmode == "string"? XFInput.InputMode[inputmode] : inputmode;
this.incremental = incremental;
this.delay = delay;
this.timer = null;
var cells = this.element.firstChild.firstChild.childNodes;
this.cell = cells[cells.length - 2];
this.isClone = clone;
this.hasBinding = true;
this.type; // ???
this.itype = itype;
this.bolAidButton = aidButton;
for (; this.cell.firstChild.nodeType == NodeType.TEXT; this.cell.removeChild(this.cell.firstChild)) {}
this.initFocus(this.cell.firstChild, true);
if (aidButton) {
this.aidButton = cells[cells.length - 1].firstChild;
this.initFocus(this.aidButton);
}
}
XFInput.prototype = new XFControl();
XFInput.prototype.clone = function(id) {
return new XFInput(id, this.itype, this.binding, this.inputmode, this.incremental, this.delay, this.bolAidButton, true);
};
XFInput.prototype.dispose = function() {
this.cell = null;
this.calendarButton = null;
xforms.counters.input--;
XFControl.prototype.dispose.call(this);
};
XFInput.prototype.initInput = function(type) {
var cell = this.cell;
var input = cell.firstChild;
var clase = type["class"];
if (input.type == "password") {
this.type = Schema.getType("xsd_:string");
this.initEvents(input, true);
} else if (input.nodeName.toLowerCase() == "textarea") {
this.type = Schema.getType("xsd_:string");
this.initEvents(input, false);
} else if (type != this.type) {
this.type = type;
if (clase == "boolean" || this.itype != input.type) {
for (; cell.firstChild; cell.removeChild(cell.firstChild)) {}
} else {
for (var i = cell.childNodes.length - 1; i >= 1; i--) {
cell.removeChild(cell.childNodes[i]);
}
}
if (clase == "boolean") {
input = Core.createElement("input");
input.type = "checkbox";
cell.appendChild(input);
} else {
if(this.itype != input.type) {
input = Core.createElement("input", cell, null, "xforms-value");
}
this.initEvents(input, (this.itype=="text"));
if (clase == "date" || clase == "datetime") {
this.calendarButton = Core.createElement("button", cell, "...", "aid-button");
this.initFocus(this.calendarButton);
} else if (clase == "number") {
input.style.textAlign = "right";
}
var max = type.getMaxLength();
if (max) {
input.maxLength = max;
} else {
input.removeAttribute("maxLength");
}
var length = type.getDisplayLength();
if (length) {
input.size = length;
} else {
input.removeAttribute("size");
}
}
}
this.initFocus(input, true);
this.input = input;
};
XFInput.prototype.setValue = function(value) {
var node = this.element.node;
var type = node ? Schema.getType(Core.getType(node) || "xsd_:string") : Schema.getType("xsd_:string");
if (!this.input || type != this.type) {
this.initInput(type);
this.changeReadonly();
}
if (type["class"] == "boolean") {
this.input.checked = value == "true";
} else if (this.input.value != value) { // && this != xforms.focus) {
this.input.value = value || "";
}
};
XFInput.prototype.changeReadonly = function() {
if (this.input) {
this.input.readOnly = this.readonly;
if (this.calendarButton) {
this.calendarButton.style.display = this.readonly? "none" : "";
}
}
};
XFInput.prototype.initEvents = function(input, canActivate) {
if (this.inputmode) {
XSLTFormsEvent.attach(input, "keyup", XFInput.keyUpInputMode);
}
if (canActivate) {
XSLTFormsEvent.attach(input, "keydown", XFInput.keyDownActivate);
XSLTFormsEvent.attach(input, "keypress", XFInput.keyPressActivate);
if (this.incremental) {
XSLTFormsEvent.attach(input, "keyup", XFInput.keyUpIncrementalActivate);
} else {
XSLTFormsEvent.attach(input, "keyup", XFInput.keyUpActivate);
}
} else {
if (this.incremental) {
XSLTFormsEvent.attach(input, "keyup", XFInput.keyUpIncremental);
}
}
};
XFInput.prototype.blur = function(target) {
xforms.focus = null;
var input = this.input;
if (!this.incremental) {
assert(input, this.element.id);
var value = input.type == "checkbox"? (input.checked? "true" : "false") : input.value;
this.valueChanged(value);
} else {
var node = this.element.node;
var value = input.value;
if (value != null && value.length > 0 && Schema.getType(Core.getType(node) || "xsd_:string").format) {
try { input.value = getValue(node, true); } catch(e) { }
}
if (this.timer) {
window.clearTimeout(this.timer);
this.timer = null;
}
}
};
XFInput.prototype.click = function(target) {
if (target == this.aidButton) {
xforms.openAction();
XMLEvents.dispatch(this, "ajx-aid");
xforms.closeAction();
} else if (target == this.input && this.type["class"] == "boolean") {
xforms.openAction();
this.valueChanged(target.checked? "true" : "false");
XMLEvents.dispatch(this, "DOMActivate");
xforms.closeAction();
} else if (target == this.calendarButton) {
Calendar.show(target.previousSibling, this.type["class"] == "datetime"? Calendar.SECONDS : Calendar.ONLY_DATE);
}
};
XFInput.keyUpInputMode = function() {
var xf = XFControl.getXFElement(this);
this.value = xf.inputmode(this.value);
};
XFInput.keyDownActivate = function(a) {
this.keyDownCode = a.keyCode;
};
XFInput.keyPressActivate = function(a) {
this.keyPressCode = a.keyCode;
};
XFInput.keyUpActivate = function(a) {
var xf = XFControl.getXFElement(this);
if (a.keyCode == 13 && (this.keyDownCode == 13 || this.keyPressCode == 13)) {
xforms.openAction();
xf.valueChanged(this.value || "");
XMLEvents.dispatch(xf, "DOMActivate");
xforms.closeAction();
}
this.keyDownCode = this.keyPressCode = null;
};
XFInput.keyUpIncrementalActivate = function(a) {
var xf = XFControl.getXFElement(this);
if (a.keyCode == 13 && (this.keyDownCode == 13 || this.keyPressCode == 13)) {
xforms.openAction();
xf.valueChanged(this.value || "");
XMLEvents.dispatch(xf, "DOMActivate");
xforms.closeAction();
} else {
if (xf.delay && xf.delay > 0) {
if (xf.timer) {
window.clearTimeout(xf.timer);
}
xf.timer = window.setTimeout("xforms.openAction();document.getElementById('" + xf.element.id + "').xfElement.valueChanged('" + (this.value.addslashes() || "") + "');xforms.closeAction();", xf.delay);
} else {
xforms.openAction();
xf.valueChanged(this.value || "");
xforms.closeAction();
}
}
this.keyDownCode = this.keyPressCode = null;
};
XFInput.keyUpIncremental = function() {
var xf = XFControl.getXFElement(this);
if (xf.delay && xf.delay > 0) {
if (xf.timer) {
window.clearTimeout(xf.timer);
}
xf.timer = window.setTimeout("xforms.openAction();document.getElementById('" + xf.element.id + "').xfElement.valueChanged('" + (this.value.addslashes() || "") + "');xforms.closeAction();", xf.delay);
} else {
xforms.openAction();
xf.valueChanged(this.value || "");
xforms.closeAction();
}
};
XFInput.InputMode = {
lowerCase : function(value) { return value.toLowerCase(); },
upperCase : function(value) { return value.toUpperCase(); },
titleCase : function(value) {
return value.charAt(0).toUpperCase() + value.substring(1).toLowerCase();
},
digits : function(value) {
if (/^[0-9]*$/.exec(value) != null) {
return value;
} else {
alert("Character not valid");
var digits = "1234567890";
var newValue = "";
for (var i = 0, len = value.length; i < len; i++) {
if (digits.indexOf(value.charAt(i)) != -1) {
newValue += value.charAt(i);
}
}
return newValue;
}
}
};
function XFItem(id, bindingL, bindingV) {
xforms.counters.item++;
this.init(id);
if (bindingL || bindingV) {
this.hasBinding = true;
this.bindingL = bindingL;
this.bindingV = bindingV;
} else {
Core.setClass(this.element, "xforms-disabled", false);
}
var element = this.element;
if (element.nodeName.toLowerCase() != "option") {
this.input = Core.isXhtml ? element.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "input")[0] : element.getElementsByTagName("input")[0];
this.input.name = XFControl.getXFElement(this.element).element.id;
XSLTFormsEvent.attach(this.input, "focus", XFControl.focusHandler);
XSLTFormsEvent.attach(this.input, "blur", XFControl.blurHandler);
this.label = Core.isXhtml ? element.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "span")[0] : element.getElementsByTagName("span")[0];
}
}
XFItem.prototype = new XFElement();
XFItem.prototype.clone = function(id) {
return new XFItem(id, this.bindingL, this.bindingV);
};
XFItem.prototype.dispose = function() {
this.input = null;
this.label = null;
xforms.counters.item--;
XFElement.prototype.dispose.call(this);
};
XFItem.prototype.build_ = function(ctx) {
var element = this.element;
var xf = element.parentNode.xfElement;
if (xf && xf.isRepeat) {
ctx = element.node;
} else {
element.node = ctx;
}
if (this.bindingL) {
element.nodeL = this.evaluateBinding(this.bindingL, ctx)[0];
this.depsNodesRefresh.push(element.nodeL);
}
if (this.bindingV) {
element.nodeV = this.evaluateBinding(this.bindingV, ctx)[0];
this.depsNodesRefresh.push(element.nodeV);
}
};
XFItem.prototype.refresh = function() {
var element = this.element;
if (element.nodeName.toLowerCase() == "option") {
if (element.nodeL) {
try { element.text = getValue(element.nodeL, true); } catch(e) { }
}
if (element.nodeV) {
try { element.value = getValue(element.nodeV); } catch(e2) { }
}
} else {
if (element.nodeL) {
setValue(this.label, getValue(element.nodeL, true));
}
if (element.nodeV) {
this.input.value = getValue(element.nodeV);
}
}
};
XFItem.prototype.click = function (target) {
var input = this.input;
if (input) {
var xf = XFControl.getXFElement(this.element);
if (!xf.element.node.readonly && target == input) {
/*
if (target != input) {
if (input.type != "radio" || !input.checked) {
input.checked = !input.checked;
input.focus();
}
}
*/
xf.itemClick(input.value);
}
}
};
function XFItemset(id, nodesetBinding, labelBinding, valueBinding) {
xforms.counters.itemset++;
this.init(id);
this.nodesetBinding = nodesetBinding;
this.labelBinding = labelBinding;
this.valueBinding = valueBinding;
this.hasBinding = true;
}
XFItemset.prototype = new XFElement();
XFItemset.prototype.build_ = function(ctx) {
if (this.element.getAttribute("cloned")) { return; }
this.nodes = this.evaluateBinding(this.nodesetBinding, ctx);
var next = this.element;
var parentNode = next.parentNode;
var length = this.nodes.length;
var oldNode = next;
var listeners = next.listeners;
for (var cont = 1; true;) {
next = next.nextSibling;
if (next && next.getAttribute("cloned")) {
if (cont >= length) {
next.listeners = null;
parentNode.removeChild(next);
next = oldNode;
} else {
next.node = this.nodes[cont];
this.refresh_(next, cont++);
oldNode = next;
}
} else {
for (var i = cont; i < length; i++) {
var node = this.element.cloneNode(true);
node.setAttribute("cloned", "true");
IdManager.cloneId(node);
node.node = this.nodes[i];
parentNode.appendChild(node);
this.refresh_(node, i);
if (listeners && !Core.isIE) {
for (var j = 0, len = listeners.length; j < len; j++) {
listeners[j].clone(node);
}
}
}
break;
}
}
if (length > 0) {
this.element.node = this.nodes[0];
this.refresh_(this.element, 0);
} else {
this.element.value = "\xA0";
this.element.text = "\xA0";
}
};
XFItemset.prototype.refresh = function() {
var parent = this.element.parentNode;
var i;
for (i = 0; parent.childNodes[i] != this.element; i++);
for (var j = 0, len = this.nodes.length; j < len || j == 0; j++) {
Core.setClass(parent.childNodes[i+j], "xforms-disabled", this.nodes.length === 0);
}
};
XFItemset.prototype.clone = function(id) {
return new XFItemset(id, this.nodesetBinding, this.labelBinding, this.valueBinding);
};
XFItemset.prototype.dispose = function() {
xforms.counters.itemset--;
XFElement.prototype.dispose.call(this);
};
XFItemset.prototype.refresh_ = function(element, cont) {
var ctx = this.nodes[cont];
var nodeLabel = this.evaluateBinding(this.labelBinding, ctx)[0];
var nodeValue = this.evaluateBinding(this.valueBinding, ctx)[0];
if (nodeLabel) {
this.depsNodesRefresh.push(nodeLabel);
try { element.text = getValue(nodeLabel, true); } catch(e) { }
}
if (nodeValue) {
this.depsNodesRefresh.push(nodeValue);
try { element.value = getValue(nodeValue); } catch(e2) { }
}
};
function XFLabel(id, binding) {
xforms.counters.label++;
this.init(id);
if (binding) {
this.hasBinding = true;
this.binding = binding;
}
}
XFLabel.prototype = new XFElement();
XFLabel.prototype.clone = function(id) {
return new XFLabel(id, this.binding);
};
XFLabel.prototype.dispose = function() {
xforms.counters.label--;
XFElement.prototype.dispose.call(this);
};
XFLabel.prototype.build_ = function(ctx) {
var nodes = this.evaluateBinding(this.binding, ctx);
this.element.node = nodes[0];
this.depsNodesRefresh.push(nodes[0]);
};
XFLabel.prototype.refresh = function() {
var node = this.element.node;
var value = node? getValue(node, true) : "";
setValue(this.element, value);
};
function XFOutput(id, binding, mediatype) {
xforms.counters.output++;
this.init(id);
if (this.element.firstChild.firstChild) {
var cells = this.element.firstChild.firstChild.childNodes;
this.valueElement = cells[cells.length - 2];
} else {
this.valueElement = this.element;
}
for (var i=0, len = this.valueElement.childNodes.length; i<len; i++) {
if( this.valueElement.childNodes[i].nodeType != NodeType.TEXT ) {
this.valueElement = this.valueElement.childNodes[i];
break;
}
}
this.hasBinding = true;
this.binding = binding;
this.mediatype = mediatype;
this.complex = mediatype == "application/xhtml+xml";
this.isOutput = true;
if (this.binding && this.binding.isvalue) {
Core.setClass(this.element, "xforms-disabled", false);
}
}
XFOutput.prototype = new XFControl();
XFOutput.prototype.clone = function(id) {
return new XFOutput(id, this.binding, this.mediatype);
};
XFOutput.prototype.dispose = function() {
this.valueElement = null;
xforms.counters.output--;
XFControl.prototype.dispose.call(this);
};
XFOutput.prototype.setValue = function(value) {
var node = this.element.node;
var element = this.valueElement;
if (element.nodeName.toLowerCase() == "span") {
if (this.mediatype == "application/xhtml+xml") {
while (element.firstChild) {
element.removeChild(element.firstChild);
}
if (value != null) {
element.innerHTML = value;
}
} else if (this.mediatype == "image/svg+xml") {
while (element.firstChild) {
element.removeChild(element.firstChild);
}
if (Core.isIE) {
var xamlScript = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "script") : document.createElement("script");
xamlScript.setAttribute("type", "text/xaml");
xamlScript.setAttribute("id", this.element.id+"-xaml");
xamlScript.text = Core.transformText(value, Core.ROOT + "svg2xaml.xsl", false, "width", element.currentStyle.width, "height", element.currentStyle.height);
element.appendChild(xamlScript);
var xamlObject = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "object") : document.createElement("object");
xamlObject.setAttribute("width", element.currentStyle.width+"px");
xamlObject.setAttribute("height", element.currentStyle.height+"px");
xamlObject.setAttribute("type", "application/x-silverlight");
xamlObject.setAttribute("style", "min-width: " + element.currentStyle.width+"px");
//xamlObject.setAttribute("style", "min-width: " + xamlScript.text.substring(xamlScript.text.indexOf('<Canvas Width="')+15,xamlScript.text.indexOf('" Height="')) + "px");
var xamlParamSource = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "param") : document.createElement("param");
xamlParamSource.setAttribute("name", "source");
xamlParamSource.setAttribute("value", "#"+this.element.id+"-xaml");
xamlObject.appendChild(xamlParamSource);
var xamlParamOnload = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "param") : document.createElement("param");
xamlParamOnload.setAttribute("name", "onload");
xamlParamOnload.setAttribute("value", "onLoaded");
xamlObject.appendChild(xamlParamOnload);
var xamlParamIswindowless = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "param") : document.createElement("param");
xamlParamIswindowless.setAttribute("name", "iswindowless");
xamlParamIswindowless.setAttribute("value", "true");
xamlObject.appendChild(xamlParamIswindowless);
element.appendChild(xamlObject);
} else if (Core.isXhtml) {
var cs = window.getComputedStyle(element, null);
XDocument.parse(value, element);
element.firstChild.setAttribute("width", cs.getPropertyValue("min-width"));
element.firstChild.setAttribute("height", cs.getPropertyValue("min-height"));
} else {
var svgObject = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "object") : document.createElement("object");
svgObject.setAttribute("type", "image/svg+xml");
svgObject.setAttribute("data", "data:image/svg+xml,"+ value);
//svgObject.setAttribute("height", "400px");
element.appendChild(svgObject);
}
} else {
setValue(element, value);
}
} else {
element.src = value;
}
};
XFOutput.prototype.getValue = function(format) {
var node = this.element.node;
var element = this.valueElement;
if (element.nodeName.toLowerCase() == "span") {
return getValue(element, format);
} else {
value = element.src;
if (value && format && element.type.format) {
try { value = element.type.format(value); } catch(e) { }
}
return value;
}
};
function XFRepeat(id, binding, clone) {
xforms.counters.repeat++;
this.init(id);
this.binding = binding;
this.index = 1;
var el = this.element;
this.isRepeat = true;
this.hasBinding = true;
this.root = Core.hasClass(el, "xforms-control")? el.lastChild : el;
this.isItemset = Core.hasClass(el, "xforms-itemset");
}
XFRepeat.prototype = new XFElement();
XFRepeat.prototype.dispose = function() {
this.root = null;
xforms.counters.repeat--;
XFElement.prototype.dispose.call(this);
};
XFRepeat.prototype.setIndex = function(index) {
if (this.index != index) {
var node = this.nodes[index - 1];
if (node) {
xforms.openAction();
this.index = index;
this.element.node = node;
xforms.addChange(this);
xforms.addChange(document.getElementById(Core.getMeta(node.ownerDocument.documentElement, "model")).xfElement);
xforms.closeAction();
}
}
};
XFRepeat.prototype.deleteNode = function(node) {
var newNodes = [];
var nodes = this.nodes;
for (var i = 0, len = nodes.length; i < len; i++) {
if (node != nodes[i]) {
newNodes.push(nodes[i]);
}
}
this.nodes = newNodes;
this.setIndex(this.index == nodes.length? this.index - 1 : this.index);
};
XFRepeat.prototype.insertNode = function(node, nodeAfter) {
var nodes = this.nodes;
if (nodeAfter) {
var newNodes = [];
var index = 1;
for (var i = 0, len = nodes.length; i < len; i++) {
if (nodeAfter == nodes[i]) {
newNodes.push(node);
index = i + 1;
}
newNodes.push(nodes[i]);
}
this.nodes = newNodes;
this.setIndex(index);
} else {
nodes.push(node);
this.setIndex(nodes.length);
}
};
XFRepeat.prototype.build_ = function(ctx) {
var nodes = this.evaluateBinding(this.binding, ctx);
var r = this.root;
var l = r.childNodes.length;
this.nodes = nodes;
var n = nodes.length;
XFRepeat.forceOldId(r.firstChild);
for (var i = l; i < n; i++) {
var child = r.firstChild.cloneNode(true);
r.appendChild(child);
XFRepeat.initClone(child);
}
for (var j = n; j < l && r.childNodes.length > 1; j++) {
xforms.dispose(r.lastChild);
r.removeChild(r.lastChild);
}
for (var k = 0; k < n; k++) {
Core.setMeta(nodes[k], "repeat", this.element.id);
r.childNodes[k].node = nodes[k];
}
if (this.index > n) {
this.index = 1;
}
this.element.node = nodes[this.index - 1];
};
XFRepeat.prototype.refresh = function(selected) {
var empty = this.nodes.length === 0;
Core.setClass(this.element, "xforms-disabled", empty);
if (!empty && !this.isItemset) {
var childs = this.root.childNodes;
for (var i = 0, len = childs.length; i < len; i++) {
var sel = selected && (this.index == i + 1);
childs[i].selected = sel;
Core.setClass(childs[i], "xforms-repeat-item-selected", sel);
}
}
};
XFRepeat.prototype.clone = function(id) {
return new XFRepeat(id, this.binding, true);
};
XFRepeat.initClone = function(element) {
var id = element.id;
if (id) {
IdManager.cloneId(element);
var oldid = element.getAttribute("oldid");
var original = document.getElementById(oldid);
var xf = original.xfElement;
if (xf) {
xf.clone(element.id);
}
var listeners = original.listeners;
if (listeners && !Core.isIE) {
for (var i = 0, len = listeners.length; i < len; i++) {
listeners[i].clone(element);
}
}
}
var next = element.firstChild;
while (next) {
var child = next;
next = next.nextSibling;
if (child.id && child.getAttribute("cloned")) {
element.removeChild(child);
} else {
XFRepeat.initClone(child);
}
}
};
XFRepeat.forceOldId = function(element) {
var id = element.id;
if (id) {
if (id.substr(0, 8) == "clonedId") {
return;
}
element.setAttribute("oldid", id);
}
var next = element.firstChild;
while (next) {
var child = next;
next = next.nextSibling;
XFRepeat.forceOldId(child);
}
};
XFRepeat.selectItem = function(element) {
var par = element.parentNode;
if (par) {
var repeat = par.xfElement? par : par.parentNode;
var childs = par.childNodes;
assert(repeat.xfElement, element.nodeName + " - " + repeat.nodeName);
for (var i = 0, len = childs.length; i < len; i++) {
if (childs[i] == element) {
repeat.xfElement.setIndex(i + 1);
break;
}
}
}
};
function XFSelect(id, multiple, full, binding, incremental, clone) {
xforms.counters.select++;
this.init(id);
this.binding = binding;
this.multiple = multiple;
this.full = full;
this.incremental = incremental;
this.isClone = clone;
this.hasBinding = true;
if (!this.full) {
this.select = Core.isXhtml ? this.element.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "select")[0] : this.element.getElementsByTagName("select")[0];
this.initFocus(this.select);
XSLTFormsEvent.attach(this.select, "change",
incremental? XFSelect.incrementalChange : XFSelect.normalChange);
}
}
XFSelect.prototype = new XFControl();
XFSelect.prototype.clone = function(id) {
return new XFSelect(id, this.multiple, this.full, this.binding, this.incremental, true);
};
XFSelect.prototype.dispose = function() {
this.select = null;
this.selectedOptions = null;
xforms.counters.select--;
XFControl.prototype.dispose.call(this);
};
XFSelect.prototype.focusFirst = function() {
var input = Core.isXhtml ? this.element.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "input")[0] : this.element.getElementsByTagName("input")[0];
input.focus();
if (Core.isOpera) {
input.focus();
}
};
XFSelect.prototype.setValue = function(value) {
if (!this.full && (!value || value == "")) {
this.selectedOptions = [];
if (this.select.firstChild.value != "\xA0") {
var empty = this.select.options[0].cloneNode(true);
empty.value = "\xA0";
empty.text = "\xA0";
empty.id = "";
this.select.insertBefore(empty, this.select.options[0]);
this.select.selectedIndex = 0;
}
} else {
if (!this.full && this.select.firstChild.value == "\xA0") {
this.select.removeChild(this.select.firstChild);
}
var vals = value? (this.multiple? value.split(" ") : [value]) : [""];
var list = this.full? (Core.isXhtml ? this.element.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "input") : this.element.getElementsByTagName("input")) : this.select.options;
var well = true;
for (var i = 0, len = vals.length; well && i < len; i++) {
var val = vals[i];
var finded = false;
for (var j = 0, len1 = list.length; !finded && j < len1; j++) {
if (list[j].value == val) {
finded = true;
}
}
well = finded;
}
if (well || (this.multiple && !value)) {
if (this.outRange) {
this.outRange = false;
XMLEvents.dispatch(this, "xforms-in-range");
}
} else if ((!this.multiple || value) && !this.outRange) {
this.outRange = true;
XMLEvents.dispatch(this, "xforms-out-of-range");
}
vals = this.multiple? vals : [vals[0]];
var readonly = this.element.node.readonly;
if (this.full) {
for (var n = 0, len2 = list.length; n < len2; n++) {
var item = list[n];
item.checked = inArray(item.value, vals);
}
} else {
this.selectedOptions = [];
for (var k = 0, len3 = list.length; k < len3; k++) {
var item = list[k];
var b = inArray(item.value, vals);
if (b) {
this.selectedOptions.push(item);
}
try {
item.selected = b;
} catch(e) {
}
}
}
}
};
XFSelect.prototype.changeReadonly = function() {
if (this.full) {
var list = Core.isXhtml ? this.element.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "input") : this.element.getElementsByTagName("input");
for (var i = 0, len = list.length; i < len; i++) {
list[i].disabled = this.readonly;
}
} else {
if (!Dialog.knownSelect(this.select)) {
this.select.disabled = this.readonly;
}
}
};
XFSelect.prototype.itemClick = function(value) {
var inputs = Core.isXhtml ? this.element.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "input") : this.element.getElementsByTagName("input");
xforms.openAction();
if (this.multiple) {
var newValue = null;
for (var i = 0, len = inputs.length; i < len; i++) {
var input = inputs[i];
if (input.value == value) {
XMLEvents.dispatch(input.parentNode, input.checked? "xforms-select" : "xforms-deselect");
}
if (input.checked) {
newValue = (newValue? newValue + " " : "") + input.value;
}
}
value = newValue;
} else {
var old = this.value || getValue(this.element.node);
var inputSelected = null;
if (old == value) {
xforms.closeAction();
return;
}
for (var j = 0, len1 = inputs.length; j < len1; j++) {
var input = inputs[j];
input.checked = input.value == value;
if (input.value == old) {
XMLEvents.dispatch(input.parentNode, "xforms-deselect");
} else if (input.value == value) {
var inputSelected = input;
}
}
XMLEvents.dispatch(inputSelected.parentNode, "xforms-select");
}
if (this.incremental) {
this.valueChanged(value || "");
} else {
this.value = value || "";
}
xforms.closeAction();
};
XFSelect.prototype.blur = function(evt) {
if (this.value != null) {
xforms.openAction();
this.valueChanged(this.value);
xforms.closeAction();
this.value = null;
}
};
XFSelect.normalChange = function(evt) {
var xf = XFControl.getXFElement(this);
var news = [];
var value = "";
var old = xf.getSelected();
var opts = this.options;
xforms.openAction();
for (var i = 0, len = old.length; i < len; i++) {
if (old[i].selected) {
news.push(old[i]);
} else {
XMLEvents.dispatch(old[i], "xforms-deselect");
}
}
for (var j = 0, len1 = opts.length; j < len1; j++) {
var opt = opts[j];
if (opt.selected) {
value = value? value + " " + opt.value : opt.value;
}
}
for (var j = 0, len1 = opts.length; j < len1; j++) {
var opt = opts[j];
if (opt.selected) {
if (!inArray(opt, news)) {
news.push(opt);
XMLEvents.dispatch(opt, "xforms-select");
}
}
}
xf.value = value;
xf.selectedOptions = news;
xforms.closeAction();
};
XFSelect.incrementalChange = function(evt) {
var xf = XFControl.getXFElement(this);
xforms.openAction();
XFSelect.normalChange.call(this, evt);
xf.valueChanged(xf.value);
xforms.closeAction();
};
XFSelect.prototype.getSelected = function() {
var s = this.selectedOptions;
if (!s) {
s = [];
var opts = this.select.options;
for (var i = 0, len = opts.length; i < len; i++) {
if (opts[i].selected) {
s.push(opts[i]);
}
}
}
return s;
};
function XFTrigger(id, binding, clone) {
xforms.counters.trigger++;
this.init(id);
this.binding = binding;
this.hasBinding = !!binding;
if(!this.hasBinding) {
Core.setClass(this.element, "xforms-disabled", false);
}
this.isTrigger = true;
var button = Core.isXhtml ? (this.element.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "a")[0] || this.element.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "button")[0]) : (this.element.getElementsByTagName("a")[0] || this.element.getElementsByTagName("button")[0]);
this.initFocus(button);
}
XFTrigger.prototype = new XFControl();
XFTrigger.prototype.setValue = function () { };
XFTrigger.prototype.clone = function (id) {
return new XFTrigger(id, this.binding, true);
};
XFTrigger.prototype.dispose = function() {
xforms.counters.trigger--;
XFElement.prototype.dispose.call(this);
};
XFTrigger.prototype.click = function () {
xforms.openAction();
XMLEvents.dispatch(this, "DOMActivate");
xforms.closeAction();
};
XFTrigger.prototype.blur = function () { };
function Calendar() {
var calendar = this;
var body = Core.isXhtml ? document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "body")[0] : document.getElementsByTagName("body")[0];
this.element = Core.createElement("table", body, null, "calendar");
var tHead = Core.createElement("thead", this.element);
var trTitle = Core.createElement("tr", tHead);
var title = Core.createElement("td", trTitle, null, "title");
title.colSpan = 7;
this.selectMonth = Core.createElement("select", title);
XSLTFormsEvent.attach(this.selectMonth, "change", function() {
Calendar.INSTANCE.refresh();
} );
for (var i = 0; i < 12; i++) {
var o = Core.createElement("option", this.selectMonth, I8N.get("calendar.month" + i));
o.setAttribute("value", i);
}
this.inputYear = Core.createElement("input", title);
this.inputYear.readOnly = true;
XSLTFormsEvent.attach(this.inputYear, "mouseup", function() {
var cal = Calendar.INSTANCE;
cal.yearList.show();
} );
XSLTFormsEvent.attach(this.inputYear, "change", function() {
Calendar.INSTANCE.refresh();
} );
var close = Core.createElement("button", title, "X");
close.setAttribute("title", "Close");
XSLTFormsEvent.attach(close, "click", function() {
Calendar.close();
} );
var trDays = Core.createElement("tr", tHead, null, "names");
var ini = parseInt(I8N.get("calendar.initDay"), 10);
for (var j = 0; j < 7; j++) {
var ind = (j + ini) % 7;
this.createElement(trDays, "name", I8N.get("calendar.day" + ind));
}
this.tBody = Core.createElement("tbody", this.element);
var handler = function(event) {
var value = XSLTFormsEvent.getTarget(event).childNodes[0].nodeValue;
var cal = Calendar.INSTANCE;
if (value != "") {
cal.day = value;
var date = new Date(cal.inputYear.value,cal.selectMonth.value,cal.day);
if (cal.isTimestamp) {
date.setSeconds(cal.inputSec.value);
date.setMinutes(cal.inputMin.value);
date.setHours(cal.inputHour.value);
cal.input.value = I8N.format(date, null, true);
} else {
cal.input.value = I8N.formatDate(date);
}
Calendar.close();
XSLTFormsEvent.dispatch(cal.input, "keyup");
cal.input.focus();
}
};
for (var dtr = 0; dtr < 6; dtr++) {
var trLine = Core.createElement("tr", this.tBody);
for (var day = 0; day < 7; day++) {
this.createElement(trLine, "day", " ", 1, handler);
}
}
var tFoot = Core.createElement("tfoot", this.element);
var trFoot = Core.createElement("tr", tFoot);
var tdFoot = Core.createElement("td", trFoot);
tdFoot.colSpan = 7;
this.inputHour = Core.createElement("input", tdFoot);
this.inputHour.readOnly = true;
XSLTFormsEvent.attach(this.inputHour, "mouseup", function() {
Calendar.INSTANCE.hourList.show();
} );
tdFoot.appendChild(document.createTextNode(":"));
this.inputMin = Core.createElement("input", tdFoot);
this.inputMin.readOnly = true;
XSLTFormsEvent.attach(this.inputMin, "mouseup", function() {
Calendar.INSTANCE.minList.show();
} );
tdFoot.appendChild(document.createTextNode(":"));
this.inputSec = Core.createElement("input", tdFoot);
this.inputSec.readOnly = true;
XSLTFormsEvent.attach(this.inputSec, "mouseup", function() {
if (Calendar.INSTANCE.type >= Calendar.SECONDS) {
Calendar.INSTANCE.secList.show();
}
} );
this.yearList = new NumberList(title, "calendarList", this.inputYear, 1900, 2050);
this.hourList = new NumberList(tdFoot, "calendarList", this.inputHour, 0, 23, 2);
this.minList = new NumberList(tdFoot, "calendarList", this.inputMin, 0, 59, 2);
this.secList = new NumberList(tdFoot, "calendarList", this.inputSec, 0, 59, 2);
}
Calendar.prototype.today = function() {
this.refreshControls(new Date());
};
Calendar.prototype.refreshControls = function(date) {
this.day = date.getDate();
this.selectMonth.value = date.getMonth();
this.inputYear.value = date.getYear() < 1000? 1900 + date.getYear() : date.getYear();
if (this.isTimestamp) {
this.inputHour.value = zeros(date.getHours(), 2);
this.inputMin.value = this.type >= Calendar.MINUTES? zeros(date.getMinutes(), 2) : "00";
this.inputSec.value = this.type >= Calendar.SECONDS? zeros(date.getSeconds(), 2) : "00";
}
this.refresh();
};
Calendar.prototype.refresh = function() {
var firstDay = this.getFirstDay();
var daysOfMonth = this.getDaysOfMonth();
var ini = parseInt(I8N.get("calendar.initDay"), 10);
var cont = 0;
var day = 1;
var currentMonthYear = this.selectMonth.value == this.currentMonth
&& this.inputYear.value == this.currentYear;
for (var i = 0; i < 6; i++) {
var trLine = this.tBody.childNodes[i];
for (var j = 0; j < 7; j++, cont++) {
var cell = trLine.childNodes[j];
var dayInMonth = (cont >= firstDay && cont < firstDay + daysOfMonth);
Core.setClass(cell, "hover", false);
Core.setClass(cell, "today", currentMonthYear && day == this.currentDay);
Core.setClass(cell, "selected", dayInMonth && day == this.day);
Core.setClass(cell, "weekend", (j+ini)%7 > 4);
cell.firstChild.nodeValue = dayInMonth ? day++ : "";
}
}
};
Calendar.prototype.getFirstDay = function() {
var date = new Date();
date.setDate(1);
date.setMonth(this.selectMonth.value);
date.setYear(this.inputYear.value);
var ini = parseInt(I8N.get("calendar.initDay"), 10);
var d = date.getDay();
return (d + (6 - ini)) % 7;
};
Calendar.prototype.getDaysOfMonth = function() {
var year = this.inputYear.value;
var month = this.selectMonth.value;
if (month == 1 && ((0 === (year % 4)) && ( (0 !== (year % 100))
|| (0 === (year % 400))))) {
return 29;
}
return Calendar.daysOfMonth[this.selectMonth.value];
};
Calendar.prototype.createElement = function(parent, className, text, colspan, handler) {
var element = Core.createElement("td", parent, text, className);
if (colspan > 1) {
element.colSpan = colspan;
}
if (handler) {
XSLTFormsEvent.attach(element, "click", handler);
Core.initHover(element);
}
return element;
};
Calendar.daysOfMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
Calendar.ONLY_DATE = 0;
Calendar.HOURS = 1;
Calendar.MINUTES = 2;
Calendar.SECONDS = 3;
Calendar.show = function(input, type) {
var cal = Calendar.INSTANCE;
if (!cal) {
cal = new Calendar();
Calendar.INSTANCE = cal;
}
if (!type) {
type = Calendar.ONLY_DATE;
}
cal.input = input;
cal.type = type;
cal.isTimestamp = type != Calendar.ONLY_DATE;
Core.setClass(cal.element, "date", !cal.isTimestamp);
var date;
try {
date = cal.isTimestamp? I8N.parse(input.value) : I8N.parseDate(input.value);
} catch (e) { date = new Date(); }
if (date != null) {
cal.refreshControls(date);
} else {
cal.today();
}
Dialog.show(cal.element, input, false);
};
Calendar.close = function() {
var cal = Calendar.INSTANCE;
cal.yearList.close();
Dialog.hide(cal.element, false);
};
function Type() {
}
Type.prototype.setSchema = function(schema) {
this.schema = schema;
return this;
};
Type.prototype.setName = function(name) {
this.name = name;
this.nsuri = this.schema.ns;
this.schema.types[name] = this;
return this;
};
Type.prototype.canonicalValue = function(value) {
value = value.toString();
switch (this.whiteSpace) {
case "replace": value = value.replace(/[\t\r\n]/g, " "); break;
case "collapse": value = value.replace(/[\t\r\n ]+/g, " ").replace(/^\s+|\s+$/g, ""); break;
}
return value;
};
Type.prototype.getMaxLength = function() {
return this.maxLength != null? this.maxLength
: (this.length != null? this.length
: (this.totalDigits != null? this.totalDigits + 1 : null));
};
Type.prototype.getDisplayLength = function() {
return this.displayLength;
};
function Schema(ns, name, prefixes) {
assert(ns && !Schema.all[ns], "Needed schema name or exists one schema with that namespace");
if(Schema.all[ns]) {
xforms.error(this, "xforms-link-exception", "More than one schema with the same namespace declaration");
return;
}
this.name = name;
this.ns = ns;
this.types = {};
this.prefixes = prefixes || {};
Schema.all[ns] = this;
}
Schema.all = {};
Schema.prototype.getType = function(name) {
if (name.indexOf(":") != -1) {
var res = name.split(":");
var prefix = res[0];
var ns = this.prefixes[prefix];
if (ns) {
return Schema.getTypeNS(ns, res[1]);
}
return Schema.getType(name);
}
var type = this.types[name];
if (!type) {
alert("Type " + name + " not defined");
throw "Error";
}
return type;
};
Schema.getType = function(name) {
var res = name.split(":");
if (typeof(res[1]) == "undefined") {
return Schema.getTypeNS(Schema.prefixes["xforms"], res[0]);
} else {
return Schema.getTypeNS(Schema.prefixes[res[0]], res[1]);
}
};
Schema.getTypeNS = function(ns, name) {
var schema = Schema.all[ns];
if (!schema) {
alert("Schema for namespace " + ns + " not defined for type " + name);
throw "Error";
}
var type = schema.types[name];
if (!type) {
alert("Type " + name + " not defined in namespace " + ns);
throw "Error";
}
return type;
};
Schema.get = function(ns) {
var schema = Schema.all[ns];
if (!schema) {
schema = new Schema(ns);
}
return schema;
};
Schema.prefixes = {
"xsd_" : "http://www.w3.org/2001/XMLSchema",
"xsd" : "http://www.w3.org/2001/XMLSchema",
"xforms" : "http://www.w3.org/2002/xforms",
"xsltforms" : "http://www.agencexml.com/xsltforms"
};
Schema.registerPrefix = function(prefix, namespace) {
this.prefixes[prefix] = namespace;
};
function AtomicType() {
this.patterns = [];
}
AtomicType.prototype = new Type();
AtomicType.prototype.setBase = function(base) {
var baseType = typeof base == "string"? this.schema.getType(base) : base;
for (var id in baseType) {
var value = baseType[id];
if (id == "patterns") {
copyArray(value, this.patterns);
} else if (id != "name" && id != "nsuri") {
this[id] = value;
}
}
return this;
};
AtomicType.prototype.put = function(name, value) {
if (name == "base") {
this.setBase(value);
} else if (name == "pattern") {
copyArray([value], this.patterns);
} else {
this[name] = value;
}
return this;
};
/** If valid return canonicalValue else null*/
AtomicType.prototype.validate = function (value) {
value = this.canonicalValue(value);
for (var i = 0, len = this.patterns.length; i < len; i++) {
if (!value.match(this.patterns[i])) {
return false;
}
}
if (this.enumeration != null) {
var matched = false;
for (var j = 0, len1 = this.enumeration.length; j < len1; j++) {
if (value == this.canonicalValue(this.enumeration[j])) {
matched = true;
break;
}
}
if (!matched) {
return false;
}
}
var l = value.length;
var value_i = parseInt(value, 10);
if ( (this.length != null && this.length != l)
|| (this.minLength != null && l < this.minLength)
|| (this.maxLength != null && l > this.maxLength)
|| (this.maxInclusive != null && value_i > this.maxInclusive)
|| (this.maxExclusive != null && value_i >= this.maxExclusive)
|| (this.minInclusive != null && value_i < this.minInclusive)
|| (this.minExclusive != null && value_i <= this.minExclusive) ) {
return false;
}
if (this.totalDigits != null || this.fractionDigits != null) {
var index = value.indexOf(".");
var integer = parseInt(index != -1? value.substring(0, index) : value, 10);
var decimal = index != -1? value.substring(index + 1) : "";
if (index != -1) {
if (this.fractionDigits == 0) {
return false;
}
var dl = decimal.length - 1;
for (; dl >= 0 && decimal.charAt(dl) == 0; dl--) {}
decimal = decimal.substring(0, dl + 1);
}
if ( (this.totalDigits != null && integer.length + decimal.length > this.totalDigits)
|| (this.fractionDigits != null && decimal.length > this.fractionDigits)) {
return false;
}
}
return true;
};
AtomicType.prototype.normalize = function (value) {
if (this.fractionDigits != null) {
var number = parseFloat(value);
var num;
if (isNaN(number)) {
return "NaN";
}
if (number == 0) {
num = zeros(0, this.fractionDigits + 1, true);
} else {
var mult = zeros(1, this.fractionDigits + 1, true);
num = "" + Math.round(number * mult);
}
if (this.fractionDigits != 0) {
var index = num.length - this.fractionDigits;
return (index == 0? "0" : num.substring(0, index)) + "." + num.substring(index);
}
return num;
}
return value;
};
function ListType() {
this.whiteSpace = "collapse";
}
ListType.prototype = new Type();
ListType.prototype.setItemType = function(itemType) {
this.itemType = typeof itemType == "string"? this.schema.getType(itemType) : itemType;
return this;
};
ListType.prototype.validate = function (value) {
var items = this.baseType.canonicalValue.call(this, value).split(" ");
value = "";
if (items.length == 1 && items[0] == "") {
items = [];
}
for (var i = 0, len = items.length; i < len; i++) {
var item = itemType.validate(items[i]);
if (!item) {
return null;
}
value += value.length === 0? item : " " + item;
}
if ( (this.length != null > 0 && this.length != 1) // !!! was l (lowercase L)
|| (this.minLength != null && 1 < this.minLength)
|| (this.maxLength != null && 1 > this.maxLength)) {
return null;
}
return null;
};
ListType.prototype.canonicalValue = function(value) {
var items = this.baseType.canonicalValue(value).split(" ");
var cvalue = "";
for (var i = 0, len = items.length; i < len; i++) {
var item = this.itemType.canonicalValue(items[i]);
cvalue += (cvalue.length === 0? "" : " ") + item;
}
return cvalue;
};
function UnionType() {
this.baseTypes = [];
}
UnionType.prototype = new Type();
UnionType.prototype.addType = function(type) {
this.baseTypes.push(typeof type == "string"? this.schema.getType(type) : type);
return this;
};
UnionType.prototype.validate = function (value) {
for (var i = 0, len = this.baseTypes.length; i < len; ++i) {
if (this.baseTypes[i].validate(value)) {
return true;
}
}
return false;
};
var TypeDefs = {
initAll : function() {
this.init("http://www.w3.org/2001/XMLSchema", this.Default);
this.init("http://www.w3.org/2002/xforms", this.XForms);
this.init("http://www.agencexml.com/xsltforms", this.XSLTForms);
},
init : function(ns, list) {
var schema = Schema.get(ns);
for (var id in list) {
var type = new AtomicType();
type.setSchema(schema);
type.setName(id);
var props = list[id];
var base = props.base;
if (base) {
type.setBase(base);
}
for (var prop in props) {
if (prop != "base") {
type[prop] = props[prop];
}
}
}
},
ctes : {
i : "A-Za-z_\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\xFF",
c : "A-Za-z_\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\xFF\\-\\.0-9\\xB7"
}
};
TypeDefs.Default = {
"string" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"whiteSpace" : "preserve"
},
"boolean" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^(true|false|0|1)$" ],
"class" : "boolean"
},
"decimal" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^[\\-+]?([0-9]+(\\.[0-9]*)?|\\.[0-9]+)$" ],
"class" : "number",
"format" : function(value) {
return I8N.formatNumber(value, this.fractionDigits);
},
"parse" : function(value) {
return I8N.parseNumber(value);
}
},
"float" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^(([-+]?([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))([eE][-+]?[0-9]+)?|-?INF|NaN)$" ],
"class" : "number"
},
"double" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^(([-+]?([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))([eE][-+]?[0-9]+)?|-?INF|NaN)$" ],
"class" : "number"
},
"dateTime" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^([12][0-9]{3})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\\.[0-9]+)?(Z|[+-]([01][0-9]|2[0-3]):[0-5][0-9])?$" ],
"class" : "datetime",
"displayLength" : 20,
"format" : function(value) {
return I8N.format(I8N.parse(value, "yyyy-MM-ddThh:mm:ss"),null, true);
},
"parse" : function(value) {
return I8N.format(I8N.parse(value), "yyyy-MM-ddThh:mm:ss", true);
}
},
"date" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^([12][0-9]{3})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])(Z|[+-]([01][0-9]|2[0-3]):[0-5][0-9])?$" ],
"class" : "date",
"displayLength" : 10,
"format" : function(value) {
return I8N.formatDate(I8N.parse(value, "yyyy-MM-dd"), null, true);
},
"parse" : function(value) {
return I8N.format(I8N.parseDate(value), "yyyy-MM-dd", true);
}
},
"time" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\\.[0-9]+)?(Z|[+-]([01][0-9]|2[0-3]):[0-5][0-9])?$" ],
"displayLength" : 8
},
"duration" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^-?P(?!$)([0-9]+Y)?([0-9]+M)?([0-9]+D)?(T(?!$)([0-9]+H)?([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?)?$" ]
},
"gDay" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^---(0[1-9]|[12][0-9]|3[01])$" ]
},
"gMonth" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^--(0[1-9]|1[012])$" ]
},
"gMonthDay" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^--(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$" ]
},
"gYear" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^([-+]?([0-9]{4}|[1-9][0-9]{4,}))?$" ]
},
"gYearMonth" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^([12][0-9]{3})-(0[1-9]|1[012])$" ]
},
"integer" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:decimal",
"fractionDigits" : "0"
},
"nonPositiveInteger" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:integer",
"patterns" : [ "^([\\-][0-9]+|0)$" ]
},
"nonNegativeInteger" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:integer",
"patterns" : [ "^[+]?[0-9]+$" ]
},
"negativeInteger" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:integer",
"patterns" : [ "^[\\-]0*[1-9][0-9]*$" ]
},
"positiveInteger" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:integer",
"patterns" : [ "^[+]?0*[1-9][0-9]*$" ]
},
"byte" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:integer",
"minInclusive" : -128,
"maxInclusive" : 127
},
"short" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:integer",
"minInclusive" : -32768,
"maxInclusive" : 32767
},
"int" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:integer",
"minInclusive" : -2147483648,
"maxInclusive" : 2147483647
},
"long" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:integer",
"minInclusive" : -9223372036854775808,
"maxInclusive" : 9223372036854775807
},
"unsignedByte" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:nonNegativeInteger",
"maxInclusive" : 255
},
"unsignedShort" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:nonNegativeInteger",
"maxInclusive" : 65535
},
"unsignedInt" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:nonNegativeInteger",
"maxInclusive" : 4294967295
},
"unsignedLong" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:nonNegativeInteger",
"maxInclusive" : 18446744073709551615
},
"normalizedString" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"whiteSpace" : "replace"
},
"token" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"whiteSpace" : "collapse"
},
"language" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:token",
"patterns" : [ "^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$" ]
},
"anyURI" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:token",
"patterns" : [ "^(([^:\\/?#]+):)?(\\/\\/([^\\/\\?#]*))?([^\\?#]*)(\\?([^#]*))?(#([^\\:#\\[\\]\\@\\!\\$\\&\\\\'\(\\)\\*\\+\\,\\;\\=]*))?$" ]
},
"Name" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:token",
"patterns" : [ "^[" + TypeDefs.ctes.i + ":][" + TypeDefs.ctes.c + ":]*$" ]
},
"NCName" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:token",
"patterns" : [ "^[" + TypeDefs.ctes.i + "][" + TypeDefs.ctes.c + "]*$" ]
},
"QName" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:token",
"patterns" : [ "^(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\>> -_!~*'()%]+)?(>> #[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?:[" + TypeDefs.ctes.i + "][" + TypeDefs.ctes.c + "]*$" ]
},
"ID" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:NCName"
},
"IDREF" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"base" : "xsd_:NCName"
},
"IDREFS" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^[" + TypeDefs.ctes.i + "][" + TypeDefs.ctes.c + "]*( +[" + TypeDefs.ctes.i + "][" + TypeDefs.ctes.c + "]*)*$" ]
},
"NMTOKEN" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^[" + TypeDefs.ctes.c + "]+$" ]
},
"NMTOKENS" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^[" + TypeDefs.ctes.c + "]+( +[" + TypeDefs.ctes.c + "]+)*$" ]
},
"base64Binary" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^[a-zA-Z0-9+/]+$" ]
},
"hexBinary" : {
"nsuri" : "http://www.w3.org/2001/XMLSchema",
"patterns" : [ "^[0-9A-Fa-f]+$" ],
"format" : function(value) {
return value.toUpperCase();
},
"parse" : function(value) {
return value.toUpperCase();
}
}
};
TypeDefs.XForms = {
"string" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"whiteSpace" : "preserve"
},
"boolean" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^(true|false|0|1)?$" ],
"class" : "boolean"
},
"decimal" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^([\\-+]?([0-9]+(\\.[0-9]*)?|\\.[0-9]+))?$" ],
"class" : "number",
"format" : function(value) {
return I8N.formatNumber(value, this.fractionDigits);
},
"parse" : function(value) {
return I8N.parseNumber(value);
}
},
"float" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^((([-+]?([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))([eE][-+]?[0-9]+)?|-?INF|NaN))?$" ],
"class" : "number"
},
"double" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^((([-+]?([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))([eE][-+]?[0-9]+)?|-?INF|NaN))?$" ],
"class" : "number"
},
"dateTime" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^(([12][0-9]{3})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\\.[0-9]+)?(Z|[+-]([01][0-9]|2[0-3]):[0-5][0-9])?)?$" ],
"class" : "datetime",
"displayLength" : 20,
"format" : function(value) {
return I8N.format(I8N.parse(value, "yyyy-MM-ddThh:mm:ss"), null, true);
},
"parse" : function(value) {
return I8N.format(I8N.parse(value), "yyyy-MM-ddThh:mm:ss", true);
}
},
"date" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^(([12][0-9]{3})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])(Z|[+-]([01][0-9]|2[0-3]):[0-5][0-9])?)?$" ],
"class" : "date",
"displayLength" : 10,
"format" : function(value) {
return I8N.formatDate(I8N.parse(value, "yyyy-MM-dd"), null, true);
},
"parse" : function(value) {
return I8N.format(I8N.parseDate(value), "yyyy-MM-dd", true);
}
},
"time" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\\.[0-9]+)?(Z|[+-]([01][0-9]|2[0-3]):[0-5][0-9])?)?$" ],
"displayLength" : 8
},
"duration" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^(-?P(?!$)([0-9]+Y)?([0-9]+M)?([0-9]+D)?(T(?!$)([0-9]+H)?([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?)?)?$" ]
},
"dayTimeDuration" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^([\-]?P([0-9]+D(T([0-9]+(H([0-9]+(M([0-9]+(\.[0-9]*)?S|\.[0-9]+S)?|(\.[0-9]*)?S)|(\.[0-9]*)?S)?|M([0-9]+(\.[0-9]*)?S|\.[0-9]+S)?|(\.[0-9]*)?S)|\.[0-9]+S))?|T([0-9]+(H([0-9]+(M([0-9]+(\.[0-9]*)?S|\.[0-9]+S)?|(\.[0-9]*)?S)|(\.[0-9]*)?S)?|M([0-9]+(\.[0-9]*)?S|\.[0-9]+S)?|(\.[0-9]*)?S)|\.[0-9]+S)))?$" ]
},
"yearMonthDuration" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^([\-]?P[0-9]+(Y([0-9]+M)?|M))?$" ]
},
"gDay" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^(---(0[1-9]|[12][0-9]|3[01]))?$" ]
},
"gMonth" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^(--(0[1-9]|1[012]))?$" ]
},
"gMonthDay" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^(--(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]))?$" ]
},
"gYear" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^([-+]?([0-9]{4}|[1-9][0-9]{4,}))?$" ]
},
"gYearMonth" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^(([12][0-9]{3})-(0[1-9]|1[012]))?$" ]
},
"integer" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:decimal",
"fractionDigits" : "0"
},
"nonPositiveInteger" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:integer",
"patterns" : [ "^(([\\-][0-9]+|0))?$" ]
},
"nonNegativeInteger" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:integer",
"patterns" : [ "^([+]?[0-9]+)?$" ]
},
"negativeInteger" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:integer",
"patterns" : [ "^([\\-][0-9]+)?$" ]
},
"positiveInteger" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:integer",
"patterns" : [ "^[+]?0*[1-9][0-9]*$" ]
},
"byte" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:integer",
"minInclusive" : -128,
"maxInclusive" : 127
},
"short" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:integer",
"minInclusive" : -32768,
"maxInclusive" : 32767
},
"int" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:integer",
"minInclusive" : -2147483648,
"maxInclusive" : 2147483647
},
"long" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:integer",
"minInclusive" : -9223372036854775808,
"maxInclusive" : 9223372036854775807
},
"unsignedByte" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:nonNegativeInteger",
"maxInclusive" : 255
},
"unsignedShort" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:nonNegativeInteger",
"maxInclusive" : 65535
},
"unsignedInt" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:nonNegativeInteger",
"maxInclusive" : 4294967295
},
"unsignedLong" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:nonNegativeInteger",
"maxInclusive" : 18446744073709551615
},
"normalizedString" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"whiteSpace" : "replace"
},
"token" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"whiteSpace" : "collapse"
},
"language" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:token",
"patterns" : [ "^([a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*)?$" ]
},
"anyURI" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:token",
"patterns" : [ "^((([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\>> -_!~*'()%]+)?(>> #[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?)?$" ]
},
"Name" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:token",
"patterns" : [ "^([" + TypeDefs.ctes.i + ":][" + TypeDefs.ctes.c + ":]*)?$" ]
},
"NCName" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:token",
"patterns" : [ "^([" + TypeDefs.ctes.i + "][" + TypeDefs.ctes.c + "]*)?$" ]
},
"QName" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:token",
"patterns" : [ "^((([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\>> -_!~*'()%]+)?(>> #[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?:[" + TypeDefs.ctes.i + "][" + TypeDefs.ctes.c + "]*)?$" ]
},
"ID" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:NCName"
},
"IDREF" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xforms:NCName"
},
"IDREFS" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^([" + TypeDefs.ctes.i + "][" + TypeDefs.ctes.c + "]+( +[" + TypeDefs.ctes.i + "][" + TypeDefs.ctes.c + "]*)*)?$" ]
},
"NMTOKEN" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^[" + TypeDefs.ctes.c + "]*$" ]
},
"NMTOKENS" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^([" + TypeDefs.ctes.c + "]+( +[" + TypeDefs.ctes.c + "]+)*)?$" ]
},
"base64Binary" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^[a-zA-Z0-9+/]*$" ]
},
"hexBinary" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"patterns" : [ "^[0-9A-Fa-f]*$" ],
"format" : function(value) {
return value.toUpperCase();
},
"parse" : function(value) {
return value.toUpperCase();
}
},
"email" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xsd_:string",
"whiteSpace" : "collapse",
"patterns" : [ "^([A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~]+(\.[A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~]+)*@[A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~]+(\.[A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~]+)*)?$" ]
},
"card-number" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xsd_:string",
"patterns" : [ "^[0-9]*$" ]
},
"url" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xsd_:string",
"whiteSpace" : "collapse",
"patterns" : [ "^(ht|f)tp(s?)://([a-z0-9]*:[a-z0-9]*@)?([a-z0-9.]*\\.[a-z]{2,7})$" ]
},
"amount" : {
"nsuri" : "http://www.w3.org/2002/xforms",
"base" : "xsd_:decimal",
"format" : function(value) {
return I8N.formatNumber(value, 2);
}
}
};
TypeDefs.XSLTForms = {
"decimal" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"patterns" : [ "^[-+]?\\(*[-+]?([0-9]+(\\.[0-9]*)?|\\.[0-9]+)(([+-/]|\\*)\\(*([0-9]+(\\.[0-9]*)?|\\.[0-9]+)\\)*)*$" ],
"class" : "number",
"eval" : "xsd:decimal"
},
"float" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"base" : "xsltforms:decimal",
"eval" : "xsd:float"
},
"double" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"base" : "xsltforms:decimal",
"eval" : "xsd:double"
},
"integer" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"base" : "xsltforms:decimal",
"eval" : "xsd:integer"
},
"nonPositiveInteger" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"base" : "xsltforms:decimal",
"eval" : "xsd:nonPositiveInteger"
},
"nonNegativeInteger" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"base" : "xsltforms:decimal",
"eval" : "xsd:nonNegativeInteger"
},
"negativeInteger" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"base" : "xsltforms:decimal",
"eval" : "xsd:negativeInteger"
},
"positiveInteger" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"base" : "xsltforms:decimal",
"eval" : "xsd:positiveInteger"
},
"byte" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"base" : "xsltforms:decimal",
"eval" : "xsd:byte"
},
"short" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"base" : "xsltforms:decimal",
"eval" : "xsd:short"
},
"int" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"base" : "xsltforms:decimal",
"eval" : "xsd:int"
},
"long" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"base" : "xsltforms:decimal",
"eval" : "xsd:long"
},
"unsignedByte" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"base" : "xsltforms:decimal",
"eval" : "xsd:unsignedByte"
},
"unsignedShort" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"base" : "xsltforms:decimal",
"eval" : "xsd:unsignedShort"
},
"unsignedInt" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"base" : "xsltforms:decimal",
"eval" : "xsd:unsignedInt"
},
"unsignedLong" : {
"nsuri" : "http://www.agencexml.com/xsltforms",
"base" : "xsltforms:decimal",
"eval" : "xsd:unsignedLong"
}
};
TypeDefs.initAll();
function Listener(observer, name, phase, handler) {
phase = phase || "default";
if (phase != "default" && phase != "capture") {
xforms.error(xforms.defaultModel, "xforms-compute-exception",
"Unknown event-phase(" + phase +") for event("
+ name + ")"+(observer? " on element(" + observer.id + ")":"") + "!");
return;
}
this.observer = observer;
this.name = name;
this.evtName = document.addEventListener? name : "errorupdate";
this.phase = phase;
this.handler = handler;
assert(observer);
if (!observer.listeners) {
observer.listeners = [];
}
observer.listeners.push(this);
this.callback = function(event) {
if (!document.addEventListener) {
event = event || window.event;
event.target = event.srcElement;
event.currentTarget = observer;
if (event.trueName && event.trueName != name) {
return;
}
if (!event.phase) {
if (phase == "capture") {
return;
}
} else if (event.phase != phase) {
return;
}
if (phase == "capture") {
event.cancelBubble = true;
}
event.preventDefault = function() {
this.returnValue = false;
};
event.stopPropagation = function() {
this.cancelBubble = true;
this.stopped = true;
};
}
var effectiveTarget = true;
if(event.currentTarget && event.type == "DOMActivate" && event.target.nodeName == "BUTTON" && !Core.isFF2) {
effectiveTarget = false;
}
if(event.eventPhase == 3 && !event.target.xfElement && !Core.isFF2) {
effectiveTarget = false;
}
if(event.eventPhase == 3 && event.target.xfElement && event.target == event.currentTarget && !Core.isFF2) {
effectiveTarget = false;
}
if (effectiveTarget) {
if (event.target != null && event.target.nodeType == 3) {
event.target = event.target.parentNode;
}
handler.call(event.target, event);
}
if (!document.addEventListener) {
try {
event.preventDefault = null;
event.stopPropagation = null;
} catch (e) {};
}
};
this.attach();
}
Listener.destructs = [];
Listener.prototype.attach = function() {
XSLTFormsEvent.attach(this.observer, this.evtName, this.callback, this.phase == "capture");
if (this.evtName == "xforms-model-destruct") {
Listener.destructs.push({observer: this.observer, callback: this.callback});
}
};
Listener.prototype.detach = function() {
XSLTFormsEvent.detach(this.observer, this.evtName, this.callback, this.phase == "capture");
};
Listener.prototype.clone = function(element) {
var unused = new Listener(element, this.name, this.phase, this.handler);
};
XMLEvents = {
REGISTRY : [],
EventContexts : [],
define : function(name, bubbles, cancelable, defaultAction) {
XMLEvents.REGISTRY[name] = {
bubbles: bubbles,
cancelable: cancelable,
defaultAction: defaultAction? defaultAction : function() { }
};
},
makeEventContext : function(evcontext, type, targetid, bubbles, cancelable) {
if (!evcontext) {
evcontext = {};
}
evcontext.type = type;
evcontext.targetid = targetid;
evcontext.bubbles = bubbles;
evcontext.cancelable = cancelable;
return evcontext;
}
};
XMLEvents.dispatchList = function(list, name) {
for (var id = 0, len = list.length; id < len; id++) {
XMLEvents.dispatch(list[id], name);
}
};
XMLEvents.dispatch = function(target, name, type, bubbles, cancelable, defaultAction, evcontext) {
target = target.element || target;
assert(target != null && typeof(target.nodeName) != "undefined");
DebugConsole.write("Dispatching event " + name + " on <" + target.nodeName
+ (target.className? " class=\"" + target.className + "\"" : "")
+ (target.id? " id=\"" + target.id + "\"" : "") + "/>");
var reg = XMLEvents.REGISTRY[name];
if (reg != null) {
bubbles = reg.bubbles;
cancelable = reg.cancelable;
defaultAction = reg.defaultAction;
}
if (!defaultAction) {
defaultAction = function() { };
}
evcontext = XMLEvents.makeEventContext(evcontext, name, target.id, bubbles, cancelable);
XMLEvents.EventContexts.push(evcontext);
try {
if (target.dispatchEvent) {
var event = document.createEvent("Event");
event.initEvent(name, bubbles, cancelable);
var res = target.dispatchEvent(event);
if ((res && !event.stopped) || !cancelable) {
defaultAction.call(target.xfElement, event);
}
} else {
var fauxName = "errorupdate";
var canceler = null;
// Capture phase.
var ancestors = [];
for (var a = target.parentNode; a != null; a = a.parentNode) {
ancestors.unshift(a);
}
for (var i = 0, len = ancestors.length; i < len; i++) {
var event = document.createEventObject();
event.trueName = name;
event.phase = "capture";
ancestors[i].fireEvent("onerrorupdate", event);
if (event.stopped) {
return;
}
}
var event = document.createEventObject();
event.trueName = name;
event.phase = "capture";
event.target = target;
target.fireEvent("onerrorupdate" , event);
// Bubble phase.
if (!bubbles) {
canceler = new Listener(target, name, "default",
function(event) { event.cancelBubble = true; });
}
var event = document.createEventObject();
event.trueName = name;
event.phase = "default";
event.target = target;
var res = target.fireEvent("onerrorupdate", event);
try {
if ((res && !event.stopped) || !cancelable) {
defaultAction.call(target.xfElement, event);
}
if (!bubbles) {
canceler.detach();
}
} catch (e) {
}
}
} catch (e) {
alert("XSLTForms Exception\n--------------------------\n\nError dispatching event '"+name+"' :\n\n"+(typeof(e.stack)=="undefined"?"":e.stack)+"\n\n"+(e.name?e.name+(e.message?"\n\n"+e.message:""):e));
} finally {
if (XMLEvents.EventContexts[XMLEvents.EventContexts.length - 1].rheadsdoc) {
XMLEvents.EventContexts[XMLEvents.EventContexts.length - 1].rheadsdoc = null;
}
if (XMLEvents.EventContexts[XMLEvents.EventContexts.length - 1]["response-body"]) {
XMLEvents.EventContexts[XMLEvents.EventContexts.length - 1]["response-body"] = null;
}
XMLEvents.EventContexts.pop();
}
};
XMLEvents.define("xforms-model-construct", true, false, function(event) { this.construct(); });
XMLEvents.define("xforms-model-construct-done", true, false);
XMLEvents.define("xforms-ready", true, false);
XMLEvents.define("xforms-model-destruct", true, false);
XMLEvents.define("xforms-rebuild", true, true, function(event) { this.rebuild(); });
XMLEvents.define("xforms-recalculate", true, true, function(event) { this.recalculate(); });
XMLEvents.define("xforms-revalidate", true, true, function(event) { this.revalidate(); });
XMLEvents.define("xforms-reset", true, true, function(event) { this.reset(); });
XMLEvents.define("xforms-submit", true, true, function(event) { this.submit(); });
XMLEvents.define("xforms-submit-serialize", true, false);
XMLEvents.define("xforms-refresh", true, true, function(event) { this.refresh(); });
XMLEvents.define("xforms-focus", true, true, function(event) { this.focus(); } );
XMLEvents.define("DOMActivate", true, true);
XMLEvents.define("DOMFocusIn", true, false);
XMLEvents.define("DOMFocusOut", true, false);
XMLEvents.define("xforms-select", true, false);
XMLEvents.define("xforms-deselect", true, false);
XMLEvents.define("xforms-value-changed", true, false);
XMLEvents.define("xforms-insert", true, false);
XMLEvents.define("xforms-delete", true, false);
XMLEvents.define("xforms-valid", true, false);
XMLEvents.define("xforms-invalid", true, false);
XMLEvents.define("xforms-enabled", true, false);
XMLEvents.define("xforms-disabled", true, false);
XMLEvents.define("xforms-optional", true, false);
XMLEvents.define("xforms-required", true, false);
XMLEvents.define("xforms-readonly", true, false);
XMLEvents.define("xforms-readwrite", true, false);
XMLEvents.define("xforms-in-range", true, false);
XMLEvents.define("xforms-out-of-range", true, false);
XMLEvents.define("xforms-submit-done", true, false);
XMLEvents.define("xforms-submit-error", true, false);
XMLEvents.define("xforms-compute-exception", true, false);
XMLEvents.define("xforms-binding-exception", true, false);
XMLEvents.define("ajx-start", true, true, function(evt) { evt.target.xfElement.start(); });
XMLEvents.define("ajx-stop", true, true, function(evt) { evt.target.xfElement.stop(); });
XMLEvents.define("ajx-time", true, true);
XMLEvents.define("xforms-dialog-open", true, true, function(evt) { Dialog.show(evt.target, null, true); });
XMLEvents.define("xforms-dialog-close", true, true, function(evt) { Dialog.hide(evt.target, true); });
var XPathAxis = {
ANCESTOR_OR_SELF: 'ancestor-or-self',
ANCESTOR: 'ancestor',
ATTRIBUTE: 'attribute',
CHILD: 'child',
DESCENDANT_OR_SELF: 'descendant-or-self',
DESCENDANT: 'descendant',
FOLLOWING_SIBLING: 'following-sibling',
FOLLOWING: 'following',
NAMESPACE: 'namespace',
PARENT: 'parent',
PRECEDING_SIBLING: 'preceding-sibling',
PRECEDING: 'preceding',
SELF: 'self'
};
var NodeType = {
ELEMENT : 1,
ATTRIBUTE : 2,
TEXT : 3,
CDATA_SECTION : 4,
ENTITY_REFERENCE : 5,
ENTITY : 6,
PROCESSING_INSTRUCTION : 7,
COMMENT : 8,
DOCUMENT : 9,
DOCUMENT_TYPE : 10,
DOCUMENT_FRAGMENT : 11,
NOTATION : 12
};
function ArrayExpr(exprs) {
this.exprs = exprs;
}
ArrayExpr.prototype.evaluate = function(ctx) {
var nodes = [];
for (var i = 0, len = this.exprs.length; i < len; i++) {
nodes[i] = this.exprs[i].evaluate(ctx);
}
return nodes;
};
function BinaryExpr(expr1, op, expr2) {
this.expr1 = expr1;
this.expr2 = expr2;
this.op = op.replace(">", ">").replace("<", "<");
}
BinaryExpr.prototype.evaluate = function(ctx) {
var v1 = this.expr1.evaluate(ctx);
var v2 = this.expr2.evaluate(ctx);
var n1;
var n2;
if ((((typeof v1) == "object" && v1.length > 1) || ((typeof v2) == "object" && v2.length > 1)) &&
(this.op == "=" || this.op == "!=" || this.op == "<" || this.op == "<=" || this.op == ">" || this.op == ">=")) {
for (var i = 0, len = v1.length; i < len; i++) {
n1 = numberValue([v1[i]]);
if (isNaN(n1)) {
n1 = stringValue([v1[i]]);
}
for (var j = 0, len1 = v2.length; j < len1; j++) {
n2 = numberValue([v2[j]]);
if (isNaN(n2)) {
n2 = stringValue([v2[j]]);
}
switch (this.op) {
case '=' : if (n1 == n2) return true; break;
case '!=' : if (n1 != n2) return true; break;
case '<' : if (n1 < n2) return true; break;
case '<=' : if (n1 <= n2) return true; break;
case '>' : if (n1 > n2) return true; break;
case '>=' : if (n1 >= n2) return true; break;
}
}
}
return false;
}
n1 = numberValue(v1);
n2 = numberValue(v2);
if (isNaN(n1) || isNaN(n2)) {
n1 = stringValue(v1);
n2 = stringValue(v2);
}
var res = 0;
switch (this.op) {
case 'or' : res = booleanValue(v1) || booleanValue(v2); break;
case 'and' : res = booleanValue(v1) && booleanValue(v2); break;
case '+' : res = n1 + n2; break;
case '-' : res = n1 - n2; break;
case '*' : res = n1 * n2; break;
case 'mod' : res = n1 % n2; break;
case 'div' : res = n1 / n2; break;
case '=' : res = n1 == n2; break;
case '!=' : res = n1 != n2; break;
case '<' : res = n1 < n2; break;
case '<=' : res = n1 <= n2; break;
case '>' : res = n1 > n2; break;
case '>=' : res = n1 >= n2; break;
}
return typeof res == "number" ? Math.round(res*1000000)/1000000 : res;
};
function ExprContext(node, position, nodelist, parent, nsresolver, current,
depsNodes, depsId, depsElements) {
/*
if(depsNodes) {
var s = depsNodes.length > 0 ? "ExprContext depsNodes=" : "";
for(var i = 0; i < depsNodes.length; i++) s += depsNodes[i].nodeName + " ";
if(s!="")alert(s);
}
*/
this.node = node;
this.current = current || node;
if(position == null) {
var repeat = node ? Core.getMeta(node, "repeat") : null;
if(repeat) {
var xrepeat = document.getElementById(repeat).xfElement;
for(position = 1, len = xrepeat.nodes.length; position <= len; position++) {
if(node == xrepeat.nodes[position-1]) {
break;
}
}
}
}
this.position = position || 1;
this.nodelist = nodelist || [ node ];
this.parent = parent;
this.root = parent? parent.root : node ? node.ownerDocument : null;
this.nsresolver = nsresolver;
this.depsId = depsId;
this.initDeps(depsNodes, depsElements);
}
ExprContext.prototype.clone = function(node, position, nodelist) {
return new ExprContext(node || this.node,
typeof position == "undefined"? this.position : position,
nodelist || this.nodelist, this, this.nsresolver, this.current,
this.depsNodes, this.depsId, this.depsElements);
};
ExprContext.prototype.setNode = function(node, position) {
this.node = node;
this.position = position;
};
ExprContext.prototype.initDeps = function(depsNodes, depsElements) {
this.depsNodes = depsNodes;
this.depsElements = depsElements;
};
ExprContext.prototype.addDepNode = function(node) {
var deps = this.depsNodes;
//alert("Binding:"+this.depsId+" "+deps+" addDepNode "+node.nodeName);
if (deps && !Core.getBoolMeta(node, "depfor_"+this.depsId)) { // !inArray(node, deps)) {
Core.setTrueBoolMeta(node, "depfor_"+this.depsId);
deps.push(node);
}
};
ExprContext.prototype.addDepElement = function(element) {
var deps = this.depsElements;
if (deps && !inArray(element, deps)) {
deps.push(element);
}
};
function TokenExpr(m) {
this.value = m;
}
TokenExpr.prototype.evaluate = function() {
return stringValue(this.value);
};
function UnaryMinusExpr(expr) {
this.expr = expr;
}
UnaryMinusExpr.prototype.evaluate = function(ctx) {
return -numberValue(this.expr.evaluate(ctx));
};
function CteExpr(value) {
this.value = value;
}
CteExpr.prototype.evaluate = function() {
return this.value;
};
function FilterExpr(expr, predicate) {
this.expr = expr;
this.predicate = predicate;
}
FilterExpr.prototype.evaluate = function(ctx) {
var nodes = nodeSetValue(this.expr.evaluate(ctx));
for (var i = 0, len = this.predicate.length; i < len; ++i) {
var nodes0 = nodes;
nodes = [];
for (var j = 0, len1 = nodes0.length; j < len1; ++j) {
var n = nodes0[j];
var newCtx = ctx.clone(n, j, nodes0);
if (booleanValue(this.predicate[i].evaluate(newCtx))) {
nodes.push(n);
}
}
}
return nodes;
};
function FunctionCallExpr(name) {
this.name = name;
this.func = XPathCoreFunctions[name];
this.args = [];
if (!this.func) {
throw {name: "Function " + name + "() not found"};
}
for (var i = 1, len = arguments.length; i < len; i++) {
this.args.push(arguments[i]);
}
}
FunctionCallExpr.prototype.evaluate = function(ctx) {
var arguments_ = [];
for (var i = 0, len = this.args.length; i < len; i++) {
arguments_[i] = this.args[i].evaluate(ctx);
}
return this.func.call(ctx, arguments_);
};
function LocationExpr(absolute) {
this.absolute = absolute;
this.steps = [];
for (var i = 1, len = arguments.length; i < len; i++) {
this.steps.push(arguments[i]);
}
}
LocationExpr.prototype.evaluate = function(ctx) {
var start = this.absolute? ctx.root : ctx.node;
var m = Core.getMeta((start.documentElement ? start.documentElement : start.ownerDocument.documentElement), "model");
if (m) {
ctx.addDepElement(document.getElementById(m).xfElement);
}
var nodes = [];
this.xPathStep(nodes, this.steps, 0, start, ctx);
return nodes;
};
LocationExpr.prototype.xPathStep = function(nodes, steps, step, input, ctx) {
var s = steps[step];
var nodelist = s.evaluate(ctx.clone(input));
for (var i = 0, len = nodelist.length; i < len; ++i) {
var node = nodelist[i];
if (step == steps.length - 1) {
if (!inArray(node, nodes)) {
nodes.push(node);
}
ctx.addDepNode(node);
} else {
this.xPathStep(nodes, steps, step + 1, node, ctx);
}
}
};
function NodeTestAny() {
}
NodeTestAny.prototype.evaluate = function(node) {
var n = node.localName || node.baseName;
return !n || (n.substr(0, 10) != "xsltforms_" && node.namespaceURI != "http://www.w3.org/2000/xmlns/");
};
function NodeTestName(prefix, name) {
this.prefix = prefix;
this.name = name;
}
NodeTestName.prototype.evaluate = function(node, nsresolver, csensitive) {
var pre = this.prefix;
if (this.name == "*") {
return pre && pre != "*" ? node.namespaceURI == nsresolver.lookupNamespaceURI(pre) : true;
}
var ns = node.namespaceURI;
var nodename = node.localName || node.baseName;
return (csensitive ? nodename.toUpperCase() == this.name.toUpperCase() : nodename == this.name )
&& (pre && pre != "*" ? ns == nsresolver.lookupNamespaceURI(pre)
: (pre != "*" ? ns == null || ns == "" || ns == nsresolver.lookupNamespaceURI("") : true));
};
function NodeTestPI(target) {
this.target = target;
}
NodeTestPI.prototype.evaluate = function(node) {
return node.nodeType == NodeType.PROCESSING_INSTRUCTION &&
(!this.target || node.nodeName == this.target);
};
function NodeTestType(type) {
this.type = type;
}
NodeTestType.prototype.evaluate = function(node) {
return node.nodeType == this.type;
};
function NSResolver() {
this.map = {};
this.notfound = false;
}
NSResolver.prototype.registerAll = function(resolver) {
for (var prefix in resolver.map) {
this.map[prefix] = resolver.map[prefix];
}
};
NSResolver.prototype.register = function(prefix, uri) {
this.map[prefix] = uri;
if( uri == "notfound" ) {
this.notfound = true;
}
};
NSResolver.prototype.registerNotFound = function(prefix, uri) {
if( this.map[prefix] == "notfound" ) {
this.map[prefix] = uri;
for(p in this.map) {
if( this.map[p] == "notfound" ) {
this.notfound = true;
}
}
}
};
NSResolver.prototype.lookupNamespaceURI = function(prefix) {
return this.map[prefix];
};
function PathExpr(filter, rel) {
this.filter = filter;
this.rel = rel;
}
PathExpr.prototype.evaluate = function(ctx) {
var nodes = nodeSetValue(this.filter.evaluate(ctx));
var nodes1 = [];
for (var i = 0, len = nodes.length; i < len; i++) {
var newCtx = ctx.clone(nodes[i], i, nodes);
var nodes0 = nodeSetValue(this.rel.evaluate(newCtx));
for (var j = 0, len1 = nodes0.length; j < len1; j++) {
nodes1.push(nodes0[j]);
}
}
return nodes1;
};
function PredicateExpr(expr) {
this.expr = expr;
}
PredicateExpr.prototype.evaluate = function(ctx) {
var v = this.expr.evaluate(ctx);
return typeof v == "number" ? ctx.position == v : booleanValue(v);
};
function StepExpr(axis, nodetest) {
this.axis = axis;
this.nodetest = nodetest;
this.predicates = [];
for (var i = 2, len = arguments.length; i < len; i++) {
this.predicates.push(arguments[i]);
}
}
StepExpr.prototype.evaluate = function(ctx) {
var input = ctx.node;
var list = [];
switch(this.axis) {
case XPathAxis.ANCESTOR_OR_SELF :
_push(ctx, list, input, this.nodetest);
// explicit no break here -- fallthrough
case XPathAxis.ANCESTOR :
if (input.nodeType == NodeType.ATTRIBUTE) {
input = input.ownerElement ? input.ownerElement : input.selectSingleNode("..");
_push(ctx, list, input, this.nodetest);
}
for (var pn = input.parentNode; pn.parentNode; pn = pn.parentNode) {
_push(ctx, list, pn, this.nodetest);
}
break;
case XPathAxis.ATTRIBUTE :
_pushList(ctx, list, input.attributes, this.nodetest, !input.namespaceURI || input.namespaceURI == "http://www.w3.org/1999/xhtml" || input.namespaceURI == null);
break;
case XPathAxis.CHILD :
_pushList(ctx, list, input.childNodes, this.nodetest);
break;
case XPathAxis.DESCENDANT_OR_SELF :
_push(ctx, list, input, this.nodetest);
// explicit no break here -- fallthrough
case XPathAxis.DESCENDANT :
_pushDescendants(ctx, list, input, this.nodetest);
break;
case XPathAxis.FOLLOWING :
var n = input.nodeType == NodeType.ATTRIBUTE ? input.ownerElement ? input.ownerElement : input.selectSingleNode("..") : input;
while (n.nodeType != NodeType.DOCUMENT) {
for (var nn = n.nextSibling; nn; nn = nn.nextSibling) {
_push(ctx, list, nn, this.nodetest);
_pushDescendants(ctx, list, nn, this.nodetest);
}
n = n.parentNode;
}
break;
case XPathAxis.FOLLOWING_SIBLING :
for (var ns = input.nextSibling; ns; ns = ns.nextSibling) {
_push(ctx, list, ns, this.nodetest);
}
break;
case XPathAxis.NAMESPACE :
alert('not implemented: axis namespace');
break;
case XPathAxis.PARENT :
if (input.parentNode) {
_push(ctx, list, input.parentNode, this.nodetest);
} else {
if (input.nodeType == NodeType.ATTRIBUTE) {
_push(ctx, list, input.ownerElement ? input.ownerElement : input.selectSingleNode(".."), this.nodetest);
}
}
break;
case XPathAxis.PRECEDING :
var p = input.nodeType == NodeType.ATTRIBUTE ? input.ownerElement ? input.ownerElement : input.selectSingleNode("..") : input;
while (p.nodeType != NodeType.DOCUMENT) {
for (var ps = p.previousSibling; ps; ps = ps.previousSibling) {
_pushDescendantsRev(ctx, list, ps, this.nodetest);
_push(ctx, list, ps, this.nodetest);
}
p = p.parentNode;
}
break;
case XPathAxis.PRECEDING_SIBLING :
for (var ps = input.previousSibling; ps; ps = ps.previousSibling) {
_push(ctx, list, ps, this.nodetest);
}
break;
case XPathAxis.SELF :
_push(ctx, list, input, this.nodetest);
break;
default :
throw {name:'ERROR -- NO SUCH AXIS: ' + this.axis};
}
for (var i = 0, len = this.predicates.length; i < len; i++) {
var pred = this.predicates[i];
var newList = [];
for (var j = 0, len1 = list.length; j < len1; j++) {
var x = list[j];
var newCtx = ctx.clone(x, j + 1, list);
if (booleanValue(pred.evaluate(newCtx))) {
newList.push(x);
}
}
list = newList;
}
return list;
};
function _push(ctx, list, node, test, csensitive) {
if (test.evaluate(node, ctx.nsresolver, csensitive) && !inArray(node, list)) {
list[list.length] = node;
}
}
function _pushList(ctx, list, l, test, csensitive) {
for (var i = 0, len = l ? l.length : 0; i < len; i++) {
_push(ctx, list, l[i], test, csensitive);
}
}
function _pushDescendants(ctx, list, node, test) {
for (var n = node.firstChild; n; n = n.nextSibling) {
_push(ctx, list, n, test);
arguments.callee(ctx, list, n, test);
}
}
function _pushDescendantsRev(ctx, list, node, test) {
for (var n = node.lastChild; n; n = n.previousSibling) {
_push(ctx, list, n, test);
arguments.callee(ctx, list, n, test);
}
}
function UnionExpr(expr1, expr2) {
this.expr1 = expr1;
this.expr2 = expr2;
}
UnionExpr.prototype.evaluate = function(ctx) {
var nodes1 = nodeSetValue(this.expr1.evaluate(ctx));
var nodes2 = nodeSetValue(this.expr2.evaluate(ctx));
var I1 = nodes1.length;
for (var i2 = 0, len = nodes2.length; i2 < len; ++i2) {
var found = false;
for (var i1 = 0; i1 < I1; ++i1) {
found = nodes1[i1] == nodes2[i2];
if (found) {
break;
}
}
if (!found) {
nodes1.push(nodes2[i2]);
}
}
return nodes1;
};
function stringValue(value) {
return typeof value != "object"? "" + value
: (value === null || value.length === 0 ? "" : xmlValue(value[0]));
}
function booleanValue(value) {
return typeof value == "undefined"? false
: (typeof value.length != "undefined"? value.length > 0 : !!value);
}
var nbvalcount = 0;
function numberValue(value) {
if (typeof value == "boolean") {
return 'A' - 0;
} else {
var v = typeof value == "object"? stringValue(value) : value;
return v === '' ? NaN : v - 0;
}
}
function nodeSetValue(value) {
if (typeof value != "object") {
throw {name: this, message: Error().stack};
}
return value;
}
if (Core.isIE) {
xmlValue = function(node) {
var ret = node.text;
var schtyp = Schema.getType(Core.getType(node) || "xsd_:string");
if (schtyp.eval) {
try {
ret = ret == "" ? 0 : eval(ret);
} catch (e) {}
}
return ret;
};
} else {
xmlValue = function(node) {
var ret = node.text != undefined ? node.text : node.textContent != undefined ? node.textContent : node.documentElement.text != undefined ? node.documentElement.text : node.documentElement.textContent;
var schtyp = Schema.getType(Core.getType(node) || "xsd_:string");
if (schtyp.eval) {
try {
ret = ret == "" ? 0 : eval(ret);
} catch (e) {}
}
return ret;
};
}
function xmlResolveEntities(s) {
var parts = stringSplit(s, '&');
var ret = parts[0];
for (var i = 1, len = parts.length; i < len; ++i) {
var p = parts[i];
var index = p.indexOf(";");
if (index == -1) {
ret += parts[i];
continue;
}
var rp = p.substring(0, index);
var ch;
switch (rp) {
case 'lt': ch = '<'; break;
case 'gt': ch = '>'; break;
case 'amp': ch = '&'; break;
case 'quot': ch = '"'; break;
case 'apos': ch = '\''; break;
case 'nbsp': ch = String.fromCharCode(160); break;
default:
var span = Core.isXhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", 'span') : document.createElement('span');
span.innerHTML = '&' + rp + '; ';
ch = span.childNodes[0].nodeValue.charAt(0);
}
ret += ch + p.substring(index + 1);
}
return ret;
}
function stringSplit(s, c) {
var a = s.indexOf(c);
if (a == -1) {
return [ s ];
}
var parts = [];
parts.push(s.substr(0,a));
while (a != -1) {
var a1 = s.indexOf(c, a + 1);
if (a1 != -1) {
parts.push(s.substr(a + 1, a1 - a - 1));
} else {
parts.push(s.substr(a + 1));
}
a = a1;
}
return parts;
}
function XPath(expression, compiled, ns) {
this.expression = expression;
if (typeof compiled == "string") {
alert("XSLTForms Exception\n--------------------------\n\nError parsing the following XPath expression :\n\n"+expression+"\n\n"+compiled);
return;
}
this.compiled = compiled;
this.compiled.isRoot = true;
this.nsresolver = new NSResolver();
XPath.expressions[expression] = this;
if (ns.length > 0) {
for (var i = 0, len = ns.length; i < len; i += 2) {
this.nsresolver.register(ns[i], ns[i + 1]);
}
} else {
this.nsresolver.register("", "http://www.w3.org/1999/xhtml");
}
if (this.nsresolver.notfound) {
XPath.notfound = true;
}
this.evaltime = 0;
}
XPath.prototype.evaluate = function(ctx, current) {
var d1 = new Date();
assert(ctx);
// alert("XPath evaluate \""+this.expression+"\"");
if (!ctx.node) {
ctx = new ExprContext(ctx, 1, null, null, this.nsresolver, current);
} else if (!ctx.nsresolver) {
ctx.nsresolver = this.nsresolver;
}
try {
var res = this.compiled.evaluate(ctx);
if ((res instanceof Array) && res.length > 1) {
var posres = [];
for (var i = 0, len = res.length; i < len; i++) {
posres.push({count: Core.selectNodesLength("preceding::* | ancestor::*", res[i]), node: res[i]});
}
posres.sort(function(a,b){return a.count - b.count;});
for (var i = 0, len = posres.length; i < len; i++) {
res[i] = posres[i].node;
}
}
var d2 = new Date();
this.evaltime += d2 - d1;
return res;
} catch(e) {
alert("XSLTForms Exception\n--------------------------\n\nError evaluating the following XPath expression :\n\n"+this.expression+"\n\n"+e.name+"\n\n"+e.message);
return null;
}
};
XPath.expressions = {};
XPath.notfound = false;
XPath.get = function(str) {
return XPath.expressions[str];
};
XPath.create = function(expression, compiled) {
if (XPath.get(expression) != null) {
delete compiled;
} else {
var ns = [];
for (var i = 2, len = arguments.length; i < len; i += 2) {
ns[i-2] = arguments[i];
ns[i-1] = arguments[i+1];
}
new XPath(expression, compiled, ns);
}
};
XPath.registerNS = function(prefix, uri) {
if (XPath.notfound) {
XPath.notfound = false;
for( e in XPath.expressions ) {
XPath.expressions[e].nsresolver.registerNotFound(prefix, uri);
if (XPath.expressions[e].nsresolver.notfound) {
XPath.notfound = true;
}
}
}
};
function XPathFunction(acceptContext, defaultTo, returnNodes, body) {
this.evaluate = body;
this.defaultTo = defaultTo;
this.acceptContext = acceptContext;
this.returnNodes = returnNodes;
}
XPathFunction.DEFAULT_NONE = null;
XPathFunction.DEFAULT_NODE = 0;
XPathFunction.DEFAULT_NODESET = 1;
XPathFunction.DEFAULT_STRING = 2;
XPathFunction.prototype.call = function(context, arguments_) {
if (arguments_.length === 0) {
switch (this.defaultTo) {
case XPathFunction.DEFAULT_NODE:
if (context.node != null) {
arguments_ = [context.node];
}
break;
case XPathFunction.DEFAULT_NODESET:
if (context.node != null) {
arguments_ = [[context.node]];
}
break;
case XPathFunction.DEFAULT_STRING:
arguments_ = [XPathCoreFunctions.string.evaluate([context.node])];
break;
}
}
if (this.acceptContext) {
arguments_.unshift(context);
}
return this.evaluate.apply(null, arguments_);
};
MathConstants = {
"PI": "3.14159265358979323846264338327950288419716939937510582",
"E": "2.71828182845904523536028747135266249775724709369995958",
"SQRT2": "1.41421356237309504880168872420969807856967187537694807",
"LN2": "0.693147180559945309417232121458176568075500134360255254",
"LN10": "2.30258509299404568401799145468436420760110148862877298",
"LOG2E": "1.44269504088896340735992468100189213742664595415298594",
"SQRT1_2": "0.707106781186547524400844362104849039284835937688474038"
};
XPathCoreFunctions = {
"http://www.w3.org/2005/xpath-functions last" : new XPathFunction(true, XPathFunction.DEFAULT_NONE, false,
function(ctx) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.lastInvalidArgumentsNumber;
}
return ctx.nodelist.length;
} ),
"http://www.w3.org/2005/xpath-functions position" : new XPathFunction(true, XPathFunction.DEFAULT_NONE, false,
function(ctx) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.positionInvalidArgumentsNumber;
}
return ctx.position;
} ),
"http://www.w3.org/2002/xforms context" : new XPathFunction(true, XPathFunction.DEFAULT_NONE, false,
function(ctx) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.positionInvalidArgumentsNumber;
}
return [ctx.current];
} ),
"http://www.w3.org/2005/xpath-functions count" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(nodeSet) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.countInvalidArgumentsNumber;
}
if (typeof nodeSet != "object") {
throw XPathCoreFunctionsExceptions.countInvalidArgumentType;
}
return nodeSet.length;
} ),
"http://www.w3.org/2005/xpath-functions id" : new XPathFunction(true, XPathFunction.DEFAULT_NODE, false,
function(context, object) {
if (arguments.length != 2) {
throw XPathCoreFunctionsExceptions.idInvalidArgumentsNumber;
}
if (typeof object != "object" && typeof object != "string") {
throw XPathCoreFunctionsExceptions.idInvalidArgumentType;
}
var result = [];
if (typeof(object.length) != "undefined") {
for (var i = 0, len = object.length; i < len; ++i) {
var res = XPathCoreFunctions['http://www.w3.org/2005/xpath-functions id'].evaluate(context, object[i]);
for (var j = 0, len1 = res.length; j < len1; j++) {
result.push(res[j]);
}
}
} else if (context.node != null) {
var ids = stringValue(object).split(/\s+/);
for (var j in ids) {
result.add(context.node.ownerDocument.getElementById(ids[j]));
}
}
return result;
} ),
"http://www.w3.org/2005/xpath-functions local-name" : new XPathFunction(false, XPathFunction.DEFAULT_NODESET, false,
function(nodeSet) {
if (arguments.length > 1) {
throw XPathCoreFunctionsExceptions.localNameInvalidArgumentsNumber;
}
if (arguments.length == 1 && typeof nodeSet != "object") {
throw XPathCoreFunctionsExceptions.localNameInvalidArgumentType;
}
if (arguments.length == 0) {
throw XPathCoreFunctionsExceptions.localNameNoContext;
}
return nodeSet.length === 0? "" : nodeSet[0].nodeName.replace(/^.*:/, "");
} ),
"http://www.w3.org/2005/xpath-functions namespace-uri" : new XPathFunction(false, XPathFunction.DEFAULT_NODESET, false,
function(nodeSet) {
if (arguments.length > 1) {
throw XPathCoreFunctionsExceptions.namespaceUriInvalidArgumentsNumber;
}
if (arguments.length == 1 && typeof nodeSet != "object") {
throw XPathCoreFunctionsExceptions.namespaceUriInvalidArgumentType;
}
return nodeSet.length === 0? "" : nodeSet[0].namespaceURI || "";
} ),
"http://www.w3.org/2005/xpath-functions name" : new XPathFunction(false, XPathFunction.DEFAULT_NODESET, false,
function(nodeSet) {
if (arguments.length > 1) {
throw XPathCoreFunctionsExceptions.nameInvalidArgumentsNumber;
}
if (arguments.length == 1 && typeof nodeSet != "object") {
throw XPathCoreFunctionsExceptions.nameInvalidArgumentType;
}
return nodeSet.length === 0? "" : nodeSet[0].nodeName;
} ),
"http://www.w3.org/2005/xpath-functions string" : new XPathFunction(false, XPathFunction.DEFAULT_NODESET, false,
function(object) {
if (arguments.length > 1) {
throw XPathCoreFunctionsExceptions.stringInvalidArgumentsNumber;
}
return stringValue(object);
} ),
"http://www.w3.org/2005/xpath-functions concat" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function() {
if (arguments.length <2) {
throw XPathCoreFunctionsExceptions.concatInvalidArgumentsNumber;
}
var string = "";
for (var i = 0, len = arguments.length; i < len; ++i) {
string += stringValue(arguments[i]);
}
return string;
} ),
"http://www.w3.org/2005/xpath-functions starts-with" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(string, prefix) {
if (arguments.length != 2) {
throw XPathCoreFunctionsExceptions.startsWithInvalidArgumentsNumber;
}
return stringValue(string).indexOf(stringValue(prefix)) === 0;
} ),
"http://www.w3.org/2005/xpath-functions contains" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(string, substring) {
if (arguments.length != 2) {
throw XPathCoreFunctionsExceptions.containsInvalidArgumentsNumber;
}
return stringValue(string).indexOf(stringValue(substring)) != -1;
} ),
"http://www.w3.org/2005/xpath-functions substring-before" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(string, substring) {
if (arguments.length != 2) {
throw XPathCoreFunctionsExceptions.substringBeforeInvalidArgumentsNumber;
}
string = stringValue(string);
return string.substring(0, string.indexOf(stringValue(substring)));
} ),
"http://www.w3.org/2005/xpath-functions substring-after" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(string, substring) {
if (arguments.length != 2) {
throw XPathCoreFunctionsExceptions.substringAfterInvalidArgumentsNumber;
}
string = stringValue(string);
substring = stringValue(substring);
var index = string.indexOf(substring);
return index == -1? "" : string.substring(index + substring.length);
} ),
"http://www.w3.org/2005/xpath-functions substring" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(string, index, length) {
if (arguments.length != 2 && arguments.length != 3) {
throw XPathCoreFunctionsExceptions.substringInvalidArgumentsNumber;
}
string = stringValue(string);
index = Math.round(numberValue(index));
if (isNaN(index)) {
return "";
}
if (length != null) {
length = Math.round(numberValue(length));
if (index <= 0) {
return string.substr(0, index + length - 1);
}
return string.substr(index - 1, length);
}
return string.substr(Math.max(index - 1, 0));
} ),
"http://www.w3.org/2005/xpath-functions compare" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(string1, string2) {
if (arguments.length != 2) {
throw XPathCoreFunctionsExceptions.compareInvalidArgumentsNumber;
}
string1 = stringValue(string1);
string2 = stringValue(string2);
return (string1 == string2 ? 0 : (string1 > string2 ? 1 : -1));
} ),
"http://www.w3.org/2005/xpath-functions string-length" : new XPathFunction(false, XPathFunction.DEFAULT_STRING, false,
function(string) {
if (arguments.length > 1) {
throw XPathCoreFunctionsExceptions.stringLengthInvalidArgumentsNumber;
}
return stringValue(string).length;
} ),
"http://www.w3.org/2005/xpath-functions normalize-space" : new XPathFunction(false, XPathFunction.DEFAULT_STRING, false,
function(string) {
if (arguments.length > 1) {
throw XPathCoreFunctionsExceptions.normalizeSpaceLengthInvalidArgumentsNumber;
}
return stringValue(string).replace(/^\s+|\s+$/g, "")
.replace(/\s+/, " ");
} ),
"http://www.w3.org/2005/xpath-functions translate" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(string, from, to) {
if (arguments.length != 3) {
throw XPathCoreFunctionsExceptions.translateInvalidArgumentsNumber;
}
string = stringValue(string);
from = stringValue(from);
to = stringValue(to);
var result = "";
for (var i = 0, len = string.length; i < len; ++i) {
var index = from.indexOf(string.charAt(i));
result += index == -1? string.charAt(i) : to.charAt(index);
}
return result;
} ),
"http://www.w3.org/2005/xpath-functions boolean" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(object) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.booleanInvalidArgumentsNumber;
}
return booleanValue(object);
} ),
"http://www.w3.org/2005/xpath-functions not" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(condition) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.notInvalidArgumentsNumber;
}
return !booleanValue(condition);
} ),
"http://www.w3.org/2005/xpath-functions true" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function() {
if (arguments.length != 0) {
throw XPathCoreFunctionsExceptions.trueInvalidArgumentsNumber;
}
return true;
} ),
"http://www.w3.org/2005/xpath-functions false" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function() {
if (arguments.length != 0) {
throw XPathCoreFunctionsExceptions.falseInvalidArgumentsNumber;
}
return false;
} ),
"http://www.w3.org/2005/xpath-functions lang" : new XPathFunction(true, XPathFunction.DEFAULT_NONE, false,
function(context, language) {
if (arguments.length != 2) {
throw XPathCoreFunctionsExceptions.langInvalidArgumentsNumber;
}
language = stringValue(language);
for (var node = context.node; node != null; node = node.parentNode) {
if (typeof(node.attributes) == "undefined") {
continue;
}
var xmlLang = node.attributes.getNamedItemNS(XML.Namespaces.XML, "lang");
if (xmlLang != null) {
xmlLang = xmlLang.value.toLowerCase();
language = language.toLowerCase();
return xmlLang.indexOf(language) === 0
&& (language.length == xmlLang.length || language.charAt(xmlLang.length) == '-');
}
}
return false;
} ),
"http://www.w3.org/2005/xpath-functions number" : new XPathFunction(false, XPathFunction.DEFAULT_NODESET, false,
function(object) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.numberInvalidArgumentsNumber;
}
return numberValue(object);
} ),
"http://www.w3.org/2005/xpath-functions sum" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(nodeSet) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.sumInvalidArgumentsNumber;
}
if (typeof nodeSet != "object") {
throw XPathCoreFunctionsExceptions.sumInvalidArgumentType;
}
var sum = 0;
for (var i = 0, len = nodeSet.length; i < len; ++i) {
sum += numberValue(xmlValue(nodeSet[i]));
}
return sum;
} ),
"http://www.w3.org/2005/xpath-functions floor" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.floorInvalidArgumentsNumber;
}
return Math.floor(numberValue(number));
} ),
"http://www.w3.org/2005/xpath-functions ceiling" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.ceilingInvalidArgumentsNumber;
}
return Math.ceil(numberValue(number));
} ),
"http://www.w3.org/2005/xpath-functions round" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.roundInvalidArgumentsNumber;
}
return Math.round(numberValue(number));
} ),
"http://www.w3.org/2002/xforms power" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(x, y) {
if (arguments.length != 2) {
throw XPathCoreFunctionsExceptions.powerInvalidArgumentsNumber;
}
return Math.pow(numberValue(x), numberValue(y));
} ),
"http://www.w3.org/2002/xforms random" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function() {
if (arguments.length > 1) {
throw XPathCoreFunctionsExceptions.randomInvalidArgumentsNumber;
}
return Math.random();
} ),
"http://www.w3.org/2002/xforms boolean-from-string" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(string) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.booleanFromStringInvalidArgumentsNumber;
}
string = stringValue(string);
switch (string.toLowerCase()) {
case "true": case "1": return true;
case "false": case "0": return false;
default: return false;
}
} ),
"http://www.w3.org/2002/xforms if" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, true,
function(condition, onTrue, onFalse) {
if (arguments.length != 3) {
throw XPathCoreFunctionsExceptions.ifInvalidArgumentsNumber;
}
return booleanValue(condition)? onTrue : onFalse;
} ),
"http://www.w3.org/2002/xforms choose" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, true,
function(condition, onTrue, onFalse) {
if (arguments.length != 3) {
throw XPathCoreFunctionsExceptions.chooseInvalidArgumentsNumber;
}
return booleanValue(condition)? onTrue : onFalse;
} ),
"http://www.w3.org/2005/xpath-functions avg" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(nodeSet) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.avgInvalidArgumentsNumber;
}
if (typeof nodeSet != "object") {
throw XPathCoreFunctionsExceptions.avgInvalidArgumentType;
}
var sum = XPathCoreFunctions['http://www.w3.org/2005/xpath-functions sum'].evaluate(nodeSet);
var quant = XPathCoreFunctions['http://www.w3.org/2005/xpath-functions count'].evaluate(nodeSet);
return sum / quant;
} ),
"http://www.w3.org/2005/xpath-functions min" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function (nodeSet) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.minInvalidArgumentsNumber;
}
if (typeof nodeSet != "object") {
throw XPathCoreFunctionsExceptions.minInvalidArgumentType;
}
if (nodeSet.length === 0) {
return Number.NaN;
}
var minimum = numberValue(xmlValue(nodeSet[0]));
for (var i = 1, len = nodeSet.length; i < len; ++i) {
var value = numberValue(xmlValue(nodeSet[i]));
if (isNaN(value)) {
return Number.NaN;
}
if (value < minimum) {
minimum = value;
}
}
return minimum;
} ),
"http://www.w3.org/2005/xpath-functions max" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function (nodeSet) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.maxInvalidArgumentsNumber;
}
if (typeof nodeSet != "object") {
throw XPathCoreFunctionsExceptions.maxInvalidArgumentType;
}
if (nodeSet.length === 0) {
return Number.NaN;
}
var maximum = numberValue(xmlValue(nodeSet[0]));
for (var i = 1, len = nodeSet.length; i < len; ++i) {
var value = numberValue(xmlValue(nodeSet[i]));
if (isNaN(value)) {
return Number.NaN;
}
if (value > maximum) {
maximum = value;
}
}
return maximum;
} ),
"http://www.w3.org/2002/xforms count-non-empty" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(nodeSet) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.countNonEmptyInvalidArgumentsNumber;
}
if (typeof nodeSet != "object") {
throw XPathCoreFunctionsExceptions.countNonEmptyInvalidArgumentType;
}
var count = 0;
for (var i = 0, len = nodeSet.length; i < len; ++i) {
if (xmlValue(nodeSet[i]).length > 0) {
count++;
}
}
return count;
} ),
"http://www.w3.org/2002/xforms index" : new XPathFunction(true, XPathFunction.DEFAULT_NONE, false,
function(ctx, id) {
if (arguments.length != 2) {
throw XPathCoreFunctionsExceptions.indexInvalidArgumentsNumber;
}
var xf = IdManager.find(stringValue(id)).xfElement;
ctx.addDepElement(xf);
return xf.index;
} ),
"http://www.w3.org/2002/xforms nodeindex" : new XPathFunction(true, XPathFunction.DEFAULT_NONE, false,
function(ctx, id) {
if (arguments.length != 2) {
throw XPathCoreFunctionsExceptions.nodeIndexInvalidArgumentsNumber;
}
var control = IdManager.find(stringValue(id));
var node = control.node;
ctx.addDepElement(control.xfElement);
if (node) {
ctx.addDepNode(node);
ctx.addDepElement(document.getElementById(Core.getMeta(node.documentElement ? node.documentElement : node.ownerDocument.documentElement, "model")).xfElement);
}
return node? [ node ] : [];
} ),
"http://www.w3.org/2002/xforms property" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(name) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.propertyInvalidArgumentsNumber;
}
name = stringValue(name);
switch (name) {
case "version" : return "1.1";
case "conformance-level" : return "full";
}
return "";
} ),
"http://www.w3.org/2002/xforms instance" : new XPathFunction(true, XPathFunction.DEFAULT_NONE, true,
function(ctx, idRef) {
if (arguments.length > 2) {
throw XPathCoreFunctionsExceptions.instanceInvalidArgumentsNumber;
}
var name = idRef ? stringValue(idRef) : "";
if (name != "") {
var instance = document.getElementById(name);
if (!instance) { throw {name: "instance " + name + " not found"}; }
return [instance.xfElement.doc.documentElement];
} else {
return [ctx.node.ownerDocument.documentElement];
}
} ),
"http://www.w3.org/2002/xforms now" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function() {
if (arguments.length != 0) {
throw XPathCoreFunctionsExceptions.nowInvalidArgumentsNumber;
}
return I8N.format(new Date(), "yyyy-MM-ddThh:mm:ssz", false);
} ),
"http://www.w3.org/2002/xforms local-date" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function() {
if (arguments.length != 0) {
throw XPathCoreFunctionsExceptions.localDateInvalidArgumentsNumber;
}
return I8N.format(new Date(), "yyyy-MM-ddz", true);
} ),
"http://www.w3.org/2002/xforms local-dateTime" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function() {
if (arguments.length != 0) {
throw XPathCoreFunctionsExceptions.localDateTimeInvalidArgumentsNumber;
}
return I8N.format(new Date(), "yyyy-MM-ddThh:mm:ssz", true);
} ),
"http://www.w3.org/2002/xforms days-from-date" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(string) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.daysFromDateInvalidArgumentsNumber;
}
string = stringValue(string);
if( !Schema.getType("xsd_:date").validate(string) && !Schema.getType("xsd_:dateTime").validate(string)) {
return "NaN";
}
p = /^([12][0-9]{3})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])/;
c = p.exec(string);
d = new Date(Date.UTC(c[1], c[2]-1, c[3]));
return Math.floor(d.getTime()/ 86400000 + 0.000001);
} ),
"http://www.w3.org/2002/xforms days-to-date" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.daysToDateInvalidArgumentsNumber;
}
number = numberValue(number);
if( isNaN(number) ) {
return "";
}
d = new Date();
d.setTime(Math.floor(number + 0.000001) * 86400000);
return I8N.format(d, "yyyy-MM-dd", false);
} ),
"http://www.w3.org/2002/xforms seconds-from-dateTime" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(string) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.secondsFromDateTimeInvalidArgumentsNumber;
}
string = stringValue(string);
if( !Schema.getType("xsd_:dateTime").validate(string)) {
return "NaN";
}
p = /^([12][0-9]{3})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(\.[0-9]+)?(Z|[+-])?([01][0-9]|2[0-3])?:?([0-5][0-9])?/;
c = p.exec(string);
d = new Date(Date.UTC(c[1], c[2]-1, c[3], c[4], c[5], c[6]));
if(c[8] && c[8] != "Z") {
d.setUTCMinutes(d.getUTCMinutes() + (c[8] == "+" ? 1 : -1)*(c[9]*60 + c[10]));
}
return Math.floor(d.getTime() / 1000 + 0.000001) + (c[7]?c[7]:0);
} ),
"http://www.w3.org/2002/xforms seconds-to-dateTime" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.secondsToDateTimeInvalidArgumentsNumber;
}
number = numberValue(number);
if( isNaN(number) ) {
return "";
}
d = new Date();
d.setTime(Math.floor(number + 0.000001) * 1000);
return I8N.format(d, "yyyy-MM-ddThh:mm:ssz", false);
} ),
"http://www.w3.org/2002/xforms current" : new XPathFunction(true, XPathFunction.DEFAULT_NONE, true,
function(ctx) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.currentInvalidArgumentsNumber;
}
ctx.addDepNode(ctx.node);
ctx.addDepElement(document.getElementById(Core.getMeta(ctx.node.documentElement ? ctx.node.documentElement : ctx.node.ownerDocument.documentElement, "model")).xfElement);
return [ctx.current];
} ),
"http://www.w3.org/2002/xforms is-valid" : new XPathFunction(false, XPathFunction.DEFAULT_NODESET, false,
function(nodeSet) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.isValidInvalidArgumentsNumber;
}
if (typeof nodeSet != "object") {
throw XPathCoreFunctionsExceptions.isValidInvalidArgumentType;
}
var valid = true;
for (var i = 0, len = nodeSet.length; valid && i < len; i++) {
valid = valid && validate_(nodeSet[i]);
}
return valid;
} ),
"http://www.w3.org/2002/xforms is-card-number" : new XPathFunction(false, XPathFunction.DEFAULT_NODESET, false,
function(string) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.isCardNumberInvalidArgumentsNumber;
}
string = stringValue(string).trim();
var sum = 0;
var tab = new Array(string.length);
for (var i = 0, l = string.length; i < l; i++) {
tab[i] = string.charAt(i) - '0';
if( tab[i] < 0 || tab[i] > 9 ) {
return false;
}
}
for (var i = tab.length-2; i >= 0; i -= 2) {
tab[i] *= 2;
if( tab[i] > 9 ) {
tab[i] -= 9;
}
}
for (var i = 0, l = tab.length; i < l; i++) {
sum += tab[i];
}
return sum % 10 == 0;
} ),
"http://www.w3.org/2002/xforms digest" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(str, algo, enco) {
if (arguments.length != 2 && arguments.length != 3) {
throw XPathCoreFunctionsExceptions.digestInvalidArgumentsNumber;
}
str = stringValue(str);
algo = stringValue(algo);
enco = enco ? stringValue(enco) : "base64";
switch(algo) {
case "SHA-1" :
var l = str.length;
var bl = l*8;
var W = [];
var H0 = 0x67452301;
var H1 = 0xefcdab89;
var H2 = 0x98badcfe;
var H3 = 0x10325476;
var H4 = 0xc3d2e1f0;
var a, b, c, d, e, T;
var msg = [];
for(var i = 0; i<l; i++){
msg[i >> 2] |= (str.charCodeAt(i)& 0xFF)<<((3-i%4)<<3);
}
msg[bl >> 5] |= 0x80 <<(24-bl%32);
msg[((bl+65 >> 9)<< 4)+ 15] = bl;
l = msg.length;
var rotl = function(x,n){
return(x << n)|(x >>>(32-n));
};
var add32 = function(x,y){
var lsw = (x & 0xFFFF)+(y & 0xFFFF);
return ((((x >>> 16)+(y >>> 16)+(lsw >>> 16)) & 0xFFFF)<< 16)|(lsw & 0xFFFF);
};
for(var i = 0; i<l; i += 16){
a = H0;
b = H1;
c = H2;
d = H3;
e = H4;
for(var t = 0; t<20; t++){
T = add32(add32(add32(add32(rotl(a,5),(b & c)^(~b & d)),e),0x5a827999),W[t] = t<16 ? msg[t+i] : rotl(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16],1));
e = d, d = c, c = rotl(b,30), b = a, a = T;
}
for(var t = 20; t<40; t++){
T = add32(add32(add32(add32(rotl(a,5),b^c^d),e),0x6ed9eba1),W[t] = rotl(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16],1));
e = d, d = c, c = rotl(b,30), b = a, a = T;
}
for(var t = 40; t<60; t++){
T = add32(add32(add32(add32(rotl(a,5),(b & c)^(b & d)^(c & d)),e),0x8f1bbcdc),W[t] = rotl(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16],1));
e = d, d = c, c = rotl(b,30), b = a, a = T;
}
for(var t = 60; t<80; t++){
T = add32(add32(add32(add32(rotl(a,5),b^c^d),e),0xca62c1d6),W[t] = rotl(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16],1));
e = d, d = c, c = rotl(b,30), b = a, a = T;
}
H0 = add32(a,H0);
H1 = add32(b,H1);
H2 = add32(c,H2);
H3 = add32(d,H3);
H4 = add32(e,H4);
}
var hex32 = function(v) {
var h = v >>> 16;
var l = v & 0xFFFF;
return (h >= 0x1000 ? "" : h >= 0x100 ? "0" : h >= 0x10 ? "00" : "000")+h.toString(16)+(l >= 0x1000 ? "" : l >= 0x100 ? "0" : l >= 0x10 ? "00" : "000")+l.toString(16);
};
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var b12 = function(v) {
return b64.charAt((v >>> 6) & 0x3F)+b64.charAt(v & 0x3F);
}
var b30 = function(v) {
return b64.charAt(v >>> 24)+b64.charAt((v >>> 18) & 0x3F)+b64.charAt((v >>> 12) & 0x3F)+b64.charAt((v >>> 6) & 0x3F)+b64.charAt(v & 0x3F);
}
switch(enco) {
case "hex" :
return hex32(H0)+hex32(H1)+hex32(H2)+hex32(H3)+hex32(H4);
break;
case "base64" :
return b30(H0 >>> 2)+b30(((H0 & 0x3) << 28) | (H1 >>> 4))+b30(((H1 & 0xF) << 26) | (H2 >>> 6))+b30(((H2 & 0x3F) << 24) | (H3 >>> 8))+b30(((H3 & 0xFF) << 22) | (H4 >>> 10))+b12((H4 & 0x3FF)<<2)+"=";
break;
default :
break;
}
break;
case 'BASE64':
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
str = str.replace(/\r\n/g,"\n");
var l = str.length;
var str2 = "";
for (var i = 0; i < l; i++) {
var c = str.charCodeAt(i);
str2 += c < 128 ? str.charAt(i) : c > 127 && c < 2048 ? String.fromCharCode(c >> 6 | 192, c & 63 | 128) : String.fromCharCode(c >> 12 | 224, c >> 6 & 63 | 128, c & 63 | 128);
}
l = str2.length;
var res = "";
for (var i = 0; i < l; i += 3) {
var c1 = str2.charCodeAt(i);
var c2 = i + 1 < l ? str2.charCodeAt(i + 1) : 0;
var c3 = i + 2 < l ? str2.charCodeAt(i + 2) : 0;
res += b64.charAt(c1 >> 2) + b64.charAt((c1 & 3) << 4 | c2 >> 4) + (i + 1 < l ? b64.charAt((c2 & 15) << 2 | c3 >> 6) : "=") + (i + 2 < l ? b64.charAt(c3 & 63) : "=");
}
return res;
break;
}
return "unsupported";
} ),
"http://www.w3.org/2005/xpath-functions upper-case" : new XPathFunction(false, XPathFunction.DEFAULT_NODESET, false,
function(str) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.upperCaseInvalidArgumentsNumber;
}
str = stringValue(str);
return str.toUpperCase();
} ),
"http://www.w3.org/2005/xpath-functions lower-case" : new XPathFunction(false, XPathFunction.DEFAULT_NODESET, false,
function(str) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.lowerCaseInvalidArgumentsNumber;
}
str = stringValue(str);
return str.toLowerCase();
} ),
"http://www.w3.org/2005/xpath-functions distinct-values" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(nodeSet) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.distinctValuesInvalidArgumentsNumber;
}
var nodeSet2 = [];
var values = {};
for (var i = 0, len = nodeSet.length; i < len; ++i) {
var xvalue = xmlValue(nodeSet[i]);
if (!values[xvalue]) {
nodeSet2.push(nodeSet[i]);
values[xvalue] = true;
}
}
return nodeSet2;
} ),
"http://www.w3.org/2002/xforms transform" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(nodeSet, xslhref) {
if (arguments.length != 2) {
throw XPathCoreFunctionsExceptions.transformInvalidArgumentsNumber;
}
xslhref = stringValue(xslhref);
return nodeSet.length === 0? "" : Core.transformText(Core.saveXML(nodeSet[0]), xslhref, false);
;
} ),
"http://www.w3.org/2002/xforms serialize" : new XPathFunction(false, XPathFunction.DEFAULT_NODE, false,
function(nodeSet) {
if (arguments.length > 1) {
throw XPathCoreFunctionsExceptions.serializeInvalidArgumentsNumber;
}
if (arguments.length == 1 && typeof nodeSet != "object") {
throw XPathCoreFunctionsExceptions.serializeInvalidArgumentType;
}
if (arguments.length == 0) {
throw XPathCoreFunctionsExceptions.serializeNoContext;
}
return nodeSet.length === 0? "" : Core.saveXML(nodeSet[0]);
} ),
"http://www.w3.org/2002/xforms event" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(attribute) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.eventInvalidArgumentsNumber;
}
var context = XMLEvents.EventContexts[XMLEvents.EventContexts.length - 1];
if (context) {
return context[attribute];
} else {
return null;
}
} ),
"http://www.w3.org/2005/xpath-functions is-non-empty-array" : new XPathFunction(false, XPathFunction.DEFAULT_NODESET, false,
function(nodeset) {
if (arguments.length > 1) {
throw XPathCoreFunctionsExceptions.isNonEmptyArrayInvalidArgumentsNumber;
}
if (typeof nodeset[0] != "object") {
throw XPathCoreFunctionsExceptions.isNonEmptyArrayInvalidArgumentType;
}
return nodeset[0].getAttribute("exsi:maxOccurs") && nodeset[0].getAttribute("xsi:nil") != "true";
} ),
"http://exslt.org/math abs" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.math1InvalidArgumentsNumber;
}
return Math.abs(numberValue(number));
} ),
"http://exslt.org/math acos" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.math1InvalidArgumentsNumber;
}
return Math.acos(numberValue(number));
} ),
"http://exslt.org/math asin" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.math1InvalidArgumentsNumber;
}
return Math.asin(numberValue(number));
} ),
"http://exslt.org/math atan" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.math1InvalidArgumentsNumber;
}
return Math.atan(numberValue(number));
} ),
"http://exslt.org/math atan2" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number1, number2) {
if (arguments.length != 2) {
throw XPathCoreFunctionsExceptions.math2InvalidArgumentsNumber;
}
return Math.atan2(numberValue(number1), numberValue(number2));
} ),
"http://exslt.org/math constant" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(string, number) {
if (arguments.length != 2) {
throw XPathCoreFunctionsExceptions.math2InvalidArgumentsNumber;
}
var val = MathConstants[stringValue(string)] || "0";
return parseFloat(val.substr(0, numberValue(number)+2));
} ),
"http://exslt.org/math cos" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.math1InvalidArgumentsNumber;
}
return Math.cos(numberValue(number));
} ),
"http://exslt.org/math exp" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.math1InvalidArgumentsNumber;
}
return Math.exp(numberValue(number));
} ),
"http://exslt.org/math log" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.math1InvalidArgumentsNumber;
}
return Math.log(numberValue(number));
} ),
"http://exslt.org/math power" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number1, number2) {
if (arguments.length != 2) {
throw XPathCoreFunctionsExceptions.math2InvalidArgumentsNumber;
}
return Math.pow(numberValue(number1), numberValue(number2));
} ),
"http://exslt.org/math sin" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.math1InvalidArgumentsNumber;
}
return Math.sin(numberValue(number));
} ),
"http://exslt.org/math sqrt" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.math1InvalidArgumentsNumber;
}
return Math.sqrt(numberValue(number));
} ),
"http://exslt.org/math tan" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(number) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.math1InvalidArgumentsNumber;
}
return Math.tan(numberValue(number));
} ),
"http://www.w3.org/2005/xpath-functions alert" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(arg) {
if (arguments.length != 1) {
throw XPathCoreFunctionsExceptions.alertInvalidArgumentsNumber;
}
alert(stringValue(arg));
return arg;
} ),
"http://www.w3.org/2005/xpath-functions string-join" : new XPathFunction(false, XPathFunction.DEFAULT_NONE, false,
function(nodeSet, joinString) {
if (arguments.length != 1 && arguments.length != 2) {
throw XPathCoreFunctionsExceptions.stringJoinInvalidArgumentsNumber;
}
if (typeof nodeSet != "object") {
throw XPathCoreFunctionsExceptions.stringJoinInvalidArgumentType;
}
var strings = [];
joinString = joinString || "";
for (var i = 0, len = nodeSet.length; i < len; i++) {
strings.push(xmlValue(nodeSet[i]));
}
return strings.join(joinString);
} )
};
XPathCoreFunctionsExceptions = {
lastInvalidArgumentsNumber : {
name : "last() : Invalid number of arguments",
message : "last() function has no argument"
},
positionInvalidArgumentsNumber : {
name : "position() : Invalid number of arguments",
message : "position() function has no argument"
},
countInvalidArgumentsNumber : {
name : "count() : Invalid number of arguments",
message : "count() function must have one argument exactly"
},
countInvalidArgumentType : {
name : "count() : Invalid type of argument",
message : "count() function must have a nodeset argument"
},
idInvalidArgumentsNumber : {
name : "id() : Invalid number of arguments",
message : "id() function must have one argument exactly"
},
idInvalidArgumentType : {
name : "id() : Invalid type of argument",
message : "id() function must have a nodeset or string argument"
},
localNameInvalidArgumentsNumber : {
name : "local-name() : Invalid number of arguments",
message : "local-name() function must have one argument at most"
},
localNameInvalidArgumentType : {
name : "local-name() : Invalid type of argument",
message : "local-name() function must have a nodeset argument"
},
localNameNoContext : {
name : "local-name() : no context node",
message : "local-name() function must have a nodeset argument"
},
namespaceUriInvalidArgumentsNumber : {
name : "namespace-uri() : Invalid number of arguments",
message : "namespace-uri() function must have one argument at most"
},
namespaceUriInvalidArgumentType : {
name : "namespace-uri() : Invalid type of argument",
message : "namespace-uri() function must have a nodeset argument"
},
nameInvalidArgumentsNumber : {
name : "name() : Invalid number of arguments",
message : "name() function must have one argument at most"
},
nameInvalidArgumentType : {
name : "name() : Invalid type of argument",
message : "name() function must have a nodeset argument"
},
stringInvalidArgumentsNumber : {
name : "string() : Invalid number of arguments",
message : "string() function must have one argument at most"
},
concatInvalidArgumentsNumber : {
name : "concat() : Invalid number of arguments",
message : "concat() function must have at least two arguments"
},
startsWithInvalidArgumentsNumber : {
name : "starts-with() : Invalid number of arguments",
message : "starts-with() function must have two arguments exactly"
},
containsInvalidArgumentsNumber : {
name : "contains() : Invalid number of arguments",
message : "contains() function must have two arguments exactly"
},
substringBeforeInvalidArgumentsNumber : {
name : "substring-before() : Invalid number of arguments",
message : "substring-before() function must have two arguments exactly"
},
substringAfterInvalidArgumentsNumber : {
name : "substring-after() : Invalid number of arguments",
message : "substring-after() function must have two arguments exactly"
},
substringInvalidArgumentsNumber : {
name : "substring() : Invalid number of arguments",
message : "substring() function must have two or three arguments"
},
compareInvalidArgumentsNumber : {
name : "compare() : Invalid number of arguments",
message : "compare() function must have two arguments exactly"
},
stringLengthInvalidArgumentsNumber : {
name : "string-length() : Invalid number of arguments",
message : "string-length() function must have one argument at most"
},
normalizeSpaceInvalidArgumentsNumber : {
name : "normalize-space() : Invalid number of arguments",
message : "normalize-space() function must have one argument at most"
},
translateInvalidArgumentsNumber : {
name : "translate() : Invalid number of arguments",
message : "translate() function must have three argument exactly"
},
booleanInvalidArgumentsNumber : {
name : "boolean() : Invalid number of arguments",
message : "boolean() function must have one argument exactly"
},
notInvalidArgumentsNumber : {
name : "not() : Invalid number of arguments",
message : "not() function must have one argument exactly"
},
trueInvalidArgumentsNumber : {
name : "true() : Invalid number of arguments",
message : "true() function must have no argument"
},
falseInvalidArgumentsNumber : {
name : "false() : Invalid number of arguments",
message : "false() function must have no argument"
},
langInvalidArgumentsNumber : {
name : "lang() : Invalid number of arguments",
message : "lang() function must have one argument exactly"
},
numberInvalidArgumentsNumber : {
name : "number() : Invalid number of arguments",
message : "number() function must have one argument exactly"
},
sumInvalidArgumentsNumber : {
name : "sum() : Invalid number of arguments",
message : "sum() function must have one argument exactly"
},
sumInvalidArgumentType : {
name : "sum() : Invalid type of argument",
message : "sum() function must have a nodeset argument"
},
floorInvalidArgumentsNumber : {
name : "floor() : Invalid number of arguments",
message : "floor() function must have one argument exactly"
},
ceilingInvalidArgumentsNumber : {
name : "ceiling() : Invalid number of arguments",
message : "ceiling() function must have one argument exactly"
},
roundInvalidArgumentsNumber : {
name : "round() : Invalid number of arguments",
message : "round() function must have one argument exactly"
},
powerInvalidArgumentsNumber : {
name : "power() : Invalid number of arguments",
message : "power() function must have one argument exactly"
},
randomInvalidArgumentsNumber : {
name : "random() : Invalid number of arguments",
message : "random() function must have no argument"
},
booleanFromStringInvalidArgumentsNumber : {
name : "boolean-from-string() : Invalid number of arguments",
message : "boolean-from-string() function must have one argument exactly"
},
ifInvalidArgumentsNumber : {
name : "if() : Invalid number of arguments",
message : "if() function must have three argument exactly"
},
chooseInvalidArgumentsNumber : {
name : "choose() : Invalid number of arguments",
message : "choose() function must have three argument exactly"
},
avgInvalidArgumentsNumber : {
name : "avg() : Invalid number of arguments",
message : "avg() function must have one argument exactly"
},
avgInvalidArgumentType : {
name : "avg() : Invalid type of argument",
message : "avg() function must have a nodeset argument"
},
minInvalidArgumentsNumber : {
name : "min() : Invalid number of arguments",
message : "min() function must have one argument exactly"
},
minInvalidArgumentType : {
name : "min() : Invalid type of argument",
message : "min() function must have a nodeset argument"
},
maxInvalidArgumentsNumber : {
name : "max() : Invalid number of arguments",
message : "max() function must have one argument exactly"
},
maxInvalidArgumentType : {
name : "max() : Invalid type of argument",
message : "max() function must have a nodeset argument"
},
serializeInvalidArgumentType : {
name : "serialize() : Invalid type of argument",
message : "serialize() function must have a nodeset argument"
},
countNonEmptyInvalidArgumentsNumber : {
name : "count-non-empty() : Invalid number of arguments",
message : "count-non-empty() function must have one argument exactly"
},
countNonEmptyInvalidArgumentType : {
name : "count-non-empty() : Invalid type of argument",
message : "count-non-empty() function must have a nodeset argument"
},
indexInvalidArgumentsNumber : {
name : "index() : Invalid number of arguments",
message : "index() function must have one argument exactly"
},
nodeIndexInvalidArgumentsNumber : {
name : "nodeIndex() : Invalid number of arguments",
message : "nodeIndex() function must have one argument exactly"
},
propertyInvalidArgumentsNumber : {
name : "property() : Invalid number of arguments",
message : "property() function must have one argument exactly"
},
propertyInvalidArgument : {
name : "property() : Invalid argument",
message : "Invalid property name"
},
instanceInvalidArgumentsNumber : {
name : "instance() : Invalid number of arguments",
message : "instance() function must have zero or one argument"
},
nowInvalidArgumentsNumber : {
name : "now() : Invalid number of arguments",
message : "now() function must have no argument"
},
localDateInvalidArgumentsNumber : {
name : "local-date() : Invalid number of arguments",
message : "local-date() function must have no argument"
},
localDateTimeInvalidArgumentsNumber : {
name : "local-dateTime() : Invalid number of arguments",
message : "local-dateTime() function must have no argument"
},
daysFromDateInvalidArgumentsNumber : {
name : "days-from-date() : Invalid number of arguments",
message : "days-from-date() function must have one argument exactly"
},
daysToDateInvalidArgumentsNumber : {
name : "days-to-date() : Invalid number of arguments",
message : "days-to-date() function must have one argument exactly"
},
secondsToDateTimeInvalidArgumentsNumber : {
name : "seconds-to-dateTime() : Invalid number of arguments",
message : "seconds-to-dateTime() function must have one argument exactly"
},
secondsFromDateTimeInvalidArgumentsNumber : {
name : "seconds-from-dateTime() : Invalid number of arguments",
message : "seconds-from-dateTime() function must have one argument exactly"
},
currentInvalidArgumentsNumber : {
name : "current() : Invalid number of arguments",
message : "current() function must have no argument"
},
isValidInvalidArgumentsNumber : {
name : "is-valid() : Invalid number of arguments",
message : "is-valid() function must have one argument exactly"
},
isValidInvalidArgumentType : {
name : "is-valid() : Invalid type of argument",
message : "is-valid() function must have a nodeset argument"
},
isNonEmptyArrayArgumentsNumber : {
name : "is-non-empty-array() : Invalid number of arguments",
message : "is-non-empty-array() function must have zero or one argument"
},
isNonEmptyArrayInvalidArgumentType : {
name : "is-non-empty-array() : Invalid type of argument",
message : "is-non-empty-array() function must have a node argument"
},
isCardNumberInvalidArgumentsNumber : {
name : "is-card-number() : Invalid number of arguments",
message : "is-card-number() function must have one argument exactly"
},
upperCaseInvalidArgumentsNumber : {
name : "upper-case() : Invalid number of arguments",
message : "upper-case() function must have one argument exactly"
},
lowerCaseInvalidArgumentsNumber : {
name : "lower-case() : Invalid number of arguments",
message : "lower-case() function must have one argument exactly"
},
distinctValuesInvalidArgumentsNumber : {
name : "distinct-values() : Invalid number of arguments",
message : "distinct-values() function must have one argument exactly"
},
transformInvalidArgumentsNumber : {
name : "transform() : Invalid number of arguments",
message : "transform() function must have two arguments exactly"
},
serializeNoContext : {
name : "serialize() : no context node",
message : "serialize() function must have a node argument"
},
serializeInvalidArgumentsNumber : {
name : "serialize() : Invalid number of arguments",
message : "serialize() function must have one argument exactly"
},
eventInvalidArgumentsNumber : {
name : "event() : Invalid number of arguments",
message : "event() function must have one argument exactly"
},
alertInvalidArgumentsNumber : {
name : "alert() : Invalid number of arguments",
message : "alert() function must have one argument exactly"
},
stringJoinInvalidArgumentsNumber : {
name : "string-join() : Invalid number of arguments",
message : "string-join() function must have one or two arguments"
},
stringJoinInvalidArgumentType : {
name : "string-join() : Invalid type of argument",
message : "string-join() function must have a nodeset argument"
}
};
function validate_(node) {
if (Core.getBoolMeta(node, "notvalid")) {
return false;
}
var atts = node.attributes || [];
for (var i = 0, len = atts.length; i < len; i++) {
if (atts[i].nodeName.substr(0,10) != "xsltforms_" && !this.validate_(atts[i])) {
return false;
}
}
var childs = node.childNodes || [];
for (var i = 0, len = childs.length; i < len; i++) {
if (!this.validate_(childs[i])) {
return false;
}
}
return true;
}
var MAX_DUMP_DEPTH = 30;
function dumpObj(obj, name, indent, depth) {
if (depth > MAX_DUMP_DEPTH) {
return indent + name + ": <Maximum Depth Reached>\n";
}
if (typeof obj == "object") {
var child = null;
var output = indent + name + "\n";
indent += "\t";
for (var item in obj) {
try {
child = obj[item];
} catch (e) {
child = "<Unable to Evaluate>";
}
if (typeof child == "object") {
output += dumpObj(child, item, indent, depth + 1);
} else {
output += indent + item + ": " + child + "\n";
}
}
return output;
} else {
return obj;
}
}
function var_dump(data,addwhitespace,safety,level) {
var rtrn = '';
var dt,it,spaces = '';
if(!level) {level = 1;}
for(var i=0; i<level; i++) {
spaces += ' ';
}//end for i<level
if(typeof(data) != 'object') {
dt = data;
if(typeof(data) == 'string') {
if(addwhitespace == 'html') {
dt = dt.replace(/&/g,'&');
dt = dt.replace(/>/g,'>');
dt = dt.replace(/</g,'<');
}//end if addwhitespace == html
dt = dt.replace(/\"/g,'\"');
dt = '"' + dt + '"';
}//end if typeof == string
if(typeof(data) == 'function' && addwhitespace) {
dt = new String(dt).replace(/\n/g,"\n"+spaces);
if(addwhitespace == 'html') {
dt = dt.replace(/&/g,'&');
dt = dt.replace(/>/g,'>');
dt = dt.replace(/</g,'<');
}//end if addwhitespace == html
}//end if typeof == function
if(typeof(data) == 'undefined') {
dt = 'undefined';
}//end if typeof == undefined
if(addwhitespace == 'html') {
if(typeof(dt) != 'string') {
dt = new String(dt);
}//end typeof != string
dt = dt.replace(/ /g," ").replace(/\n/g,"<br>");
}//end if addwhitespace == html
return dt;
}//end if typeof != object && != array
for (var x in data) {
if(safety && (level > safety)) {
dt = '*RECURSION*';
} else {
try {
dt = var_dump(data[x],addwhitespace,safety,level+1);
} catch (e) {continue;}
}//end if-else level > safety
it = var_dump(x,addwhitespace,safety,level+1);
rtrn += it + ':' + dt + ',';
if(addwhitespace) {
rtrn += '\n'+spaces;
}//end if addwhitespace
}//end for...in
if(addwhitespace) {
rtrn = '{\n' + spaces + rtrn.substr(0,rtrn.length-(2+(level*3))) + '\n' + spaces.substr(0,spaces.length-3) + '}';
} else {
rtrn = '{' + rtrn.substr(0,rtrn.length-1) + '}';
}//end if-else addwhitespace
if(addwhitespace == 'html') {
rtrn = rtrn.replace(/ /g," ").replace(/\n/g,"<br>");
}//end if addwhitespace == html
return rtrn;
}
| JavaScript |
var objFSO = WScript.CreateObject("Scripting.FileSystemObject");
//worst case, the stream we are updating should be blank to avoid false data.
//Creating temp.xml here and overwriting the previous file should guarantee that.
objFSO.CreateTextFile('C:\\temp\\temp.xml', true);
var objDM = WScript.CreateObject("IONTOF.DataManager");
var objITMStream = WScript.CreateObject("ADODB.Stream");
// to contain the XML output, with a Byte Order Mark, because that's how MS likes to write unicode text
var objXMLBOMStream = WScript.CreateObject("ADODB.Stream");
// to contain the XML output, without a BOM, because Calabash's XML parser doesn't like BOMs
var objXMLStream = WScript.CreateObject("ADODB.Stream");
var objXMLHTTP = WScript.CreateObject("MSXML2.XMLHTTP.6.0");
var itmURI = WScript.Arguments.Item(0);
var username = WScript.Arguments.Item(1);
var password = WScript.Arguments.Item(2);
var tempFileLoc = "C:\\temp\\temp.itm";
objXMLHTTP.open("GET", itmURI, false, username, password);
objXMLHTTP.send();
while(objXMLHTTP.Status < 200) {
WScript.sleep(60);
}
objITMStream.Open();
objITMStream.type = 1;
objITMStream.Write(objXMLHTTP.ResponseBody);
objITMStream.Position = 0;
if(objFSO.Fileexists(tempFileLoc)){
objFSO.DeleteFile(tempFileLoc);
}
objITMStream.saveToFile(tempFileLoc);
objITMStream.Close();
var objTemp = objDM.loadMeasurement(tempFileLoc);
var data = objTemp.Header;
var properties = new Enumerator(data);
//<?xml version='1.0' encoding='ISO-8859-1'?>\n
var output = "<values xmlns='http://hdl.handle.net/102.100.100/6929'>\n";
for (properties.moveFirst(); !properties.atEnd(); properties.moveNext()) {
var property = properties.item();
output += "\t<" + property.name + ">" + property.StringValue.replace(/\x00/g, "\t").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") + "</" + property.name + ">\n";
}
output += "</values>";
//WScript.StdOut.WriteLine(output);
// 2 means it's a "text" stream
objXMLBOMStream.Type = 2;
objXMLBOMStream.Charset='UTF-8';
objXMLBOMStream.Open();
// This is the binary stream which we use to create a BOM-less XML file
// 1 means it's a binary stream
objXMLStream.Type = 1;
objXMLStream.Open();
objXMLBOMStream.writeText(output);
// skip past the BOM
objXMLBOMStream.Position = 3;
objXMLBOMStream.copyTo(objXMLStream);
objXMLStream.saveToFile('C:\\temp\\temp.xml', 2);
objXMLBOMStream.close();
objXMLStream.close();
objFSO.DeleteFile(tempFileLoc);
| JavaScript |
@(user: String, host: Boolean, ready: Boolean, started: Boolean)
$(function() {
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var Socket = new WS("@routes.Application.connect(user).webSocketURL(request)")
var User = "";
var PlayersNumber = 1;
var BotsNumber = 1;
var Total = PlayersNumber+BotsNumber;
var StartTokens = 300;
var Ante = 20;
var OtherPlayers = new Array(3);
var Cards = new Array(4);
var Selected = new Array(5);
var SelectedCards = 0;
var LastAction = [0,0,0,0];
var CurrentBet = [0,0,0,0];
var CurrentPot = [0,0,0,0];
var PlayerTokens = [StartTokens,StartTokens,StartTokens,StartTokens];
var MyTurn = false;
var GameStatus = 0;
var Ability = 0;
var GS_STOPPED = 0;
var GS_FIRST_BETTING = 1;
var GS_REPLACING = 2;
var GS_SECOND_BETTING = 3;
var GS_SUMUP = 4;
function GetGameStatus(GS) {
if ( GS == GS_STOPPED ) return "Game stopped!";
if ( GS == GS_FIRST_BETTING ) return "First betting!";
if ( GS == GS_REPLACING ) return "Exchanging cards!";
if ( GS == GS_SECOND_BETTING ) return "Second betting!";
if ( GS == GS_SUMUP ) return "Sumup!";
}
var AB_NONE = 0;
var AB_CHECKBETFOLD = 1;
var AB_RAISECALLFOLD = 2;
var AB_FOLDALLIN = 3;
var AB_REPLACE = 4;
var AB_CONFIRM = 5;
function GetAbility(AB) {
if ( AB == AB_NONE ) return "No rights!";
if ( AB == AB_CHECKBETFOLD ) return "Check, bet or fold!";
if ( AB == AB_RAISECALLFOLD ) return "Raise, call or fold!";
if ( AB == AB_FOLDALLIN ) return "Fold or all-in!";
if ( AB == AB_REPLACE ) return "Replace!";
if ( AB == AB_CONFIRM ) return "Confirm!";
}
var MO_FOLD = 0;
var MO_BET = 1;
var MO_CHECK = 2;
var MO_RAISE = 3;
var MO_CALL = 4;
var MO_ALLIN = 5;
var MO_REPLACE = 6;
var MO_READY = 7;
function GetAction(AC) {
if ( AC == MO_FOLD ) return "folds";
if ( AC == MO_BET ) return "bets";
if ( AC == MO_CHECK ) return "checks";
if ( AC == MO_RAISE ) return "raises";
if ( AC == MO_CALL ) return "calls";
if ( AC == MO_ALLIN ) return "goes all-in";
if ( AC == MO_REPLACE ) return "replaces cards";
if ( AC == MO_READY ) return "is ready";
}
var CardIterator = [0,0,0,0];
for (var i=0; i<4; i++) {
Cards[i] = new Array(5);
OtherPlayers[i] = "";
}
for (var i=0; i<4; i++) {
for (var j=0; j<5; j++)
Cards[i][j] = 0;
}
function SetUserID(s) {
for (var i = 0; i < 3; i++) {
if ( OtherPlayers[i] == "" ) {
OtherPlayers[i] = s;
$( "#cards"+(i+1).toString() ).show();
break;
}
}
}
function GetUserID(s) {
for (var i = 0; i < 3; i++) {
if ( OtherPlayers[i] == s ) {
return i;
}
}
}
var sendMessage = function( field, value ) {
Socket.send('{"'+field+'":"'+value+'"}')
}
var receiveEvent = function(event) {
var data = JSON.parse(event.data);
// Handle errors
if(data.error) {
Socket.close()
return
} else {
$("#messages").show()
}
var key, keys = [];
for (key in data) {
if (data.hasOwnProperty(key))
keys.push(key)
}
for (var i=0; i<keys.length; i++) {
if ( key == 'username' ) {
User = data[key];
$( "#game" ).hide();
}
else
if ( key == 'game_status' ) {
if ( data[key] == 'game_created' )
{
$( "#create" ).hide();
$( "#settings" ).hide();
if ( @host == false ) {
$( "#header" ).text("The game is ready, join in!");
$( "#join" ).show();
}
else
{
$( "#header" ).text("The game is ready, waiting for players ...");
$( "#parameters" ).show();
$( "#parameters" ).html("Players: "+PlayersNumber.toString()+"<br>"+"Bots: "+BotsNumber.toString()+"<br>"+"Starting tokens: "+StartTokens.toString()+"<br>"+"Ante: "+Ante.toString()+"<br>");
}
fAppendToLog("New game has been created!");
}
else
if ( data[key] == 'game_started' )
{
$( "#staging" ).hide();
$( "#game" ).show();
UpdateMyCards();
UpdateMyBets();
fAppendToLog("All ready! Game started!");
}
else
if ( data[key] == 'game_stopped' )
{
$( "#staging" ).hide();
$( "#game" ).hide();
//fAppendToLog("Game stopped! Ouch ...");
}
else
if ( data[key] == 'game_end' )
{
$( "#staging" ).hide();
$( "#game" ).hide();
$( "#summary" ).show();
fAppendToLog("Game finished!");
}
}
else
if ( key == 'game_joined' ) {
if ( User == data[key] )
{
$( "#join" ).hide();
$( "#header" ).text("The game is ready, waiting for players ...");
}
else
{
}
fAppendToLog(data[key]+" joined the game!");
}
else
if ( key == 'game_left' ) {
if ( User == data[key] )
{
}
else
{
for (var i = 0; i < 3; i++) {
if ( OtherPlayers[i] == data[key] ) {
OtherPlayers[i] = "";
$( "#cards"+(i+1).toString() ).hide();
$( "#bets"+(i+1).toString() ).hide();
break;
}
}
}
fAppendToLog(data[key]+" left the game!");
}
else
if ( key == 'game_summary' ) {
var Summary = data[key];
$( "#summarytext" ).html(Summary);
}
else
if ( key == 'send_player' ) {
if ( User == data[key] )
{
}
else
{
SetUserID(data[key]);
var id = GetUserID(data[key]);
$( "#name"+(id+1).toString() ).html("Player: "+data[key]+" cards");
}
}
else
if ( keys[i] == 'send_card' ) {
//var data_ = JSON.parse(data);
if ( User == data[keys[i]] )
{
var CardID = data[keys[i+1]];
Cards[0][CardIterator[0]] = parseInt(CardID);
CardIterator[0]++;
if (CardIterator[0]>4) CardIterator[0]=0;
UpdateMyCards();
//fAppendToLog("You have received card from the server!");
}
else
{
var id = GetUserID(data[keys[i]]);
var CardID = data[keys[i+1]];
Cards[id+1][CardIterator[id+1]] = parseInt(CardID);
CardIterator[id+1]++;
if (CardIterator[id+1]>4) CardIterator[id+1]=0;
UpdateOtherCards(id);
//fAppendToLog((id+1).toString()+" have received card - "+CardID);
}
}
else
if ( keys[i] == 'send_info' ) {
//var data_ = JSON.parse(data);
if ( User == data[keys[i]] )
{
LastAction[0] = parseInt(data[keys[i+1]]);
CurrentBet[0] = parseInt(data[keys[i+2]]);
CurrentPot[0] = parseInt(data[keys[i+3]]);
PlayerTokens[0] = parseInt(data[keys[i+4]]);
//alert(LastAction[0].toString());
UpdateMyBets();
//fAppendToLog("You "+GetAction(LastAction[0]));
}
else
{
var id = GetUserID(data[keys[i]]);
LastAction[id+1] = parseInt(data[keys[i+1]]);
CurrentBet[id+1] = parseInt(data[keys[i+2]]);
CurrentPot[id+1] = parseInt(data[keys[i+3]]);
PlayerTokens[id+1] = parseInt(data[keys[i+4]]);
UpdateOtherBets(id);
}
}
else
if ( key == 'new_turn' ) {
if ( User == data[key] )
{
MyTurn = true;
ResetCards();
fAppendToLog("It's your turn "+User+"!");
}
else
{
MyTurn = false;
HideActionsPanel();
ResetCards();
fAppendToLog(data[key]+"'s turn!");
}
}
else
if ( key == 'turn_status' ) {
var GetStatus = parseInt(data[key]);
HideSumUp();
if ( GameStatus != GetStatus )
fAppendToLog("Current game status - "+GetGameStatus(GetStatus));
GameStatus = GetStatus;
}
else
if ( key == 'turn_ability' ) {
Ability = parseInt(data[key]);
UpdateActionsPanel(Ability);
fAppendToLog("Your abilities in this turn - "+GetAbility(Ability));
}
else
if ( key == 'send_sumup' ) {
var SumupMessage = data[key];
ShowSumUp(SumupMessage);
fAppendToLog("End of turn - sumup!");
}
else
if ( keys[i] == 'send_action' ) {
if ( User == data[keys[i]] )
{
//fAppendToLog("It's your turn "+User+"!");
}
else
{
var action = parseInt(data[keys[i+1]]);
var id = GetUserID(data[keys[i]]);
//alert(data[keys[i]]);
if ( action == MO_BET || action == MO_RAISE ) {
var value = data[keys[i+2]];
fAppendToLog(data[keys[i]]+" "+GetAction(action)+": "+value.toString()+"!");
}
else
fAppendToLog(data[keys[i]]+" "+GetAction(action)+"!");
}
}
else
if ( key == 'remove' ) {
if ( User == data[key] )
{
Socket.close();
$( "#join" ).hide();
$( "#header" ).text("The game is full ...");
//location.reload();
}
else
{
}
fAppendToLog("You have been removed from the game!");
}
else
if ( key == 'message' ) {
fAppendToLog(data[key]);
}
else
if ( key == 'game_error' ) {
alert(data[key]);
}
}
}
if ( @started == false )
{
$( "#parameters" ).hide();
$( "#create" ).hide();
$( "#settings" ).hide();
if ( @host == true ) {
if ( @ready == false ) {
$( "#header" ).text("You are the host, create a new game!");
$( "#create" ).show();
$( "#join" ).hide();
$( "#settings" ).show();
}
}
else
{
if ( @ready == false ) {
$( "#header" ).text("Please wait, host is configuring a new game ...");
$( "#join" ).hide();
}
else
{
$( "#header" ).text("The game is ready, join in!");
$( "#join" ).show();
}
}
}
$( "#create" ).on( "click", fNewGame );
$( "#join" ).on( "click", fJoinGame );
$( ".mycard" ).on( "click", function() {
var a = $(this).attr("alt");
if ( MyTurn && Ability == AB_REPLACE && GameStatus == GS_REPLACING )
{
if ( a == 'N' )
{
if ( SelectedCards < 4 ) {
SelectedCards++;
$(this).attr("alt",'S');
$(this).css('position', 'relative');
$(this).css('top', '-20px');
}
}
else
{
SelectedCards--;
$(this).attr("alt",'N');
$(this).css('position', 'relative');
$(this).css('top', '0px');
}
}
} );
$( "#fold" ).on( "click", fFold );
$( "#bet" ).on( "click", fBet );
$( "#check" ).on( "click", fCheck );
$( "#raise" ).on( "click", fRaise );
$( "#call" ).on( "click", fCall );
$( "#allin" ).on( "click", fAllin );
$( "#replace" ).on( "click", fReplace );
$( "#confirm" ).on( "click", fConfirm );
$( "#end" ).on( "click", fEnd );
function fConfirm() {
sendMessage("action","confirm");
}
function fEnd() {
window.location = "@routes.Application.quit(user)";
}
function fFold() {
sendMessage("action","fold");
}
function fCheck() {
sendMessage("action","check");
}
function fCall() {
sendMessage("action","call");
}
function fAllin() {
sendMessage("action","allin");
}
function fReplace() {
var replace = new Array(5);
var a;
for (var i=0; i<5; i++) {
a = $( "#card"+i.toString() ).attr("alt");
if ( a == 'S' )
replace[i] = Cards[0][i].toString();
else
replace[i] = "0";
}
Socket.send('{"action":"replace","card0":"'+replace[0]+'","card1":"'+replace[1]+'","card2":"'+replace[2]+'","card3":"'+replace[3]+'","card4":"'+replace[4]+'"}')
}
function fBet() {
var YourBet = $( "#betval" ).val();
Socket.send('{"action":"bet","amount":"'+YourBet+'"}')
}
function fRaise() {
var YourBet = $( "#raiseval" ).val();
Socket.send('{"action":"raise","amount":"'+YourBet+'"}')
}
function fNewGame() {
PlayersNumber = $("#players").val();
BotsNumber = $("#bots").val();
StartTokens = $("#tokens").val();
Ante = $("#ante").val();
Socket.send('{"action":"new_game","settings_players":"'+PlayersNumber+'","settings_bots":"'+BotsNumber+'","settings_tokens":"'+StartTokens+'","settings_ante":"'+Ante+'"}')
}
function fJoinGame() {
sendMessage("action","join_game");
}
function fAppendToLog(m) {
var el = $('<div class="message"><p style="font-size:12px"></p></div>')
$("p", el).text("LOG ->"+m)
$(el).addClass('me')
$('#messages').append(el)
$('#messages').scrollTop = $('#messages').scrollHeight;
}
function HideActionsPanel() {
$( "#fold" ).hide();
$( "#bet" ).hide();
$( "#betval" ).hide();
$( "#raiseval" ).hide();
$( "#check" ).hide();
$( "#raise" ).hide();
$( "#call" ).hide();
$( "#allin" ).hide();
$( "#replace" ).hide();
$( "#confirm" ).hide();
$( "#end" ).hide();
}
function ShowSumUp(s) {
$( "#sumuptext" ).html(s);
$( "#sumup" ).show();
for (var i = 0; i < 3; i++) {
if ( OtherPlayers[i] != "" ) {
$( "#cards"+(1+i).toString() ).show();
}
}
}
function HideSumUp() {
$( "#sumup" ).hide();
for (var j = 0; j < 3; j++) {
if ( OtherPlayers[j] != "" ) {
//$( "#cards"+(1+j).toString() ).hide();
for (var i=0; i<5; i++) {
$( "#card"+(i+(1+j)*5).toString() ).attr("src", "../assets/images/0.png");
}
}
}
}
function UpdateActionsPanel(ab) {
$( "#fold" ).hide();
$( "#bet" ).hide();
$( "#betval" ).hide();
$( "#raiseval" ).hide();
$( "#check" ).hide();
$( "#raise" ).hide();
$( "#call" ).hide();
$( "#allin" ).hide();
$( "#replace" ).hide();
$( "#confirm" ).hide();
$( "#end" ).hide();
if ( GameStatus != GS_STOPPED ) {
if ( ab == AB_CHECKBETFOLD ) {
$( "#fold" ).show();
$( "#bet" ).show();
$( "#betval" ).show();
$( "#check" ).show();
FillBetVal();
}
else
if ( ab == AB_RAISECALLFOLD ) {
$( "#fold" ).show();
$( "#raise" ).show();
$( "#raiseval" ).show();
$( "#call" ).show();
FillRaiseVal();
}
else
if ( ab == AB_FOLDALLIN ) {
$( "#fold" ).show();
$( "#allin" ).show();
}
else
if ( ab == AB_REPLACE ) {
$( "#replace" ).show();
}
else
if ( ab == AB_CONFIRM ) {
$( "#confirm" ).show();
}
}
else
{
$( "#end" ).show();
}
}
function FillBetVal() {
$( "#betval" ).val("1");
}
function FillRaiseVal() {
var maxBet = 0;
for (var i=0; i<3; i++) {
if ( CurrentPot[i+1] > maxBet )
maxBet = CurrentPot[i+1];
}
var RaiseVal = maxBet - CurrentPot[0];
$( "#raiseval" ).val((RaiseVal+1).toString());
}
function ResetCards() {
SelectedCards = 0;
for (var i=0; i<5; i++) {
$( "#card"+i.toString() ).attr("alt", "N");
$( "#card"+i.toString() ).css('position', 'relative');
$( "#card"+i.toString() ).css('top', '0px');
}
}
function UpdateMyCards() {
for (var i=0; i<5; i++) {
$( "#card"+i.toString() ).attr("src", "../assets/images/"+(Cards[0][i]).toString()+".png");
}
}
function UpdateMyBets() {
$( "#bets0" ).html("<strong>Player: "+User+"</strong><br>Last action: "+GetAction(LastAction[0])+"<br>Last bet: "+CurrentBet[0].toString()+"<br>Total bet: "+CurrentPot[0].toString()+"<br>Tokens: "+PlayerTokens[0].toString()+"<br>");
}
function UpdateOtherCards(id) {
for (var i=0; i<5; i++) {
//fAppendToLog("Card "+(i+(1+id)*5).toString()+": "+(Cards[id+1][i]).toString());
$( "#card"+(i+(1+id)*5).toString() ).attr("src", "../assets/images/"+(Cards[id+1][i]).toString()+".png");
}
}
function UpdateOtherBets(id) {
//alert((id+1).toString());
$( "#bets"+(id+1).toString() ).html("<strong>Player: "+OtherPlayers[id]+"</strong><br>Last action: "+GetAction(LastAction[id+1])+"<br>Last bet: "+CurrentBet[id+1].toString()+"<br>Total bet: "+CurrentPot[id+1].toString()+"<br>Tokens: "+PlayerTokens[id+1].toString()+"<br>");
}
Socket.onmessage = receiveEvent;
Socket.onclose = location.reload;
})
| JavaScript |
var gSelectedIndex = -1;
var gSelectedID = -1;
var gMatches = new Array();
var gLastText = "";
var ROW_COUNT = 20;
var gInitialized = false;
var DEFAULT_TEXT = "search developer docs";
var HAS_SEARCH_PAGE = false;
function set_row_selected(row, selected)
{
var c1 = row.cells[0];
// var c2 = row.cells[1];
if (selected) {
c1.className = "jd-autocomplete jd-selected";
// c2.className = "jd-autocomplete jd-selected jd-linktype";
} else {
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
}
}
function set_row_values(toroot, row, match)
{
var link = row.cells[0].childNodes[0];
link.innerHTML = match.__hilabel || match.label;
link.href = toroot + match.link
// row.cells[1].innerHTML = match.type;
}
function sync_selection_table(toroot)
{
var filtered = document.getElementById("search_filtered");
var r; //TR DOM object
var i; //TR iterator
gSelectedID = -1;
filtered.onmouseover = function() {
if(gSelectedIndex >= 0) {
set_row_selected(this.rows[gSelectedIndex], false);
gSelectedIndex = -1;
}
}
//initialize the table; draw it for the first time (but not visible).
if (!gInitialized) {
for (i=0; i<ROW_COUNT; i++) {
var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
// var c2 = r.insertCell(-1);
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
var link = document.createElement("a");
c1.onmousedown = function() {
window.location = this.firstChild.getAttribute("href");
}
c1.onmouseover = function() {
this.className = this.className + " jd-selected";
}
c1.onmouseout = function() {
this.className = "jd-autocomplete";
}
c1.appendChild(link);
}
/* var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
c1.className = "jd-autocomplete jd-linktype";
c1.colSpan = 2; */
gInitialized = true;
}
//if we have results, make the table visible and initialize result info
if (gMatches.length > 0) {
document.getElementById("search_filtered_div").className = "showing";
var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT;
for (i=0; i<N; i++) {
r = filtered.rows[i];
r.className = "show-row";
set_row_values(toroot, r, gMatches[i]);
set_row_selected(r, i == gSelectedIndex);
if (i == gSelectedIndex) {
gSelectedID = gMatches[i].id;
}
}
//start hiding rows that are no longer matches
for (; i<ROW_COUNT; i++) {
r = filtered.rows[i];
r.className = "no-display";
}
//if there are more results we're not showing, so say so.
/* if (gMatches.length > ROW_COUNT) {
r = filtered.rows[ROW_COUNT];
r.className = "show-row";
c1 = r.cells[0];
c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more";
} else {
filtered.rows[ROW_COUNT].className = "hide-row";
}*/
//if we have no results, hide the table
} else {
document.getElementById("search_filtered_div").className = "no-display";
}
}
function search_changed(e, kd, toroot)
{
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// 13 = enter
if (e.keyCode == 13) {
document.getElementById("search_filtered_div").className = "no-display";
if (kd && gSelectedIndex >= 0) {
window.location = toroot + gMatches[gSelectedIndex].link;
return false;
} else if (gSelectedIndex < 0) {
if (HAS_SEARCH_PAGE) {
return true;
} else {
sync_selection_table(toroot);
return false;
}
}
}
// 38 -- arrow up
else if (kd && (e.keyCode == 38)) {
if (gSelectedIndex >= 0) {
gSelectedIndex--;
}
sync_selection_table(toroot);
return false;
}
// 40 -- arrow down
else if (kd && (e.keyCode == 40)) {
if (gSelectedIndex < gMatches.length-1
&& gSelectedIndex < ROW_COUNT-1) {
gSelectedIndex++;
}
sync_selection_table(toroot);
return false;
}
else if (!kd) {
gMatches = new Array();
matchedCount = 0;
gSelectedIndex = -1;
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_results(text);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
if (gSelectedID == s.id) {
gSelectedIndex = i;
}
}
highlight_autocomplete_result_labels(text);
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
function rank_autocomplete_results(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__resultScore = _resultScoreFn(gMatches[i]);
}
gMatches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
function highlight_autocomplete_result_labels(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (focused) {
if(obj.value == DEFAULT_TEXT){
obj.value = "";
obj.style.color="#000000";
}
} else {
if(obj.value == ""){
obj.value = DEFAULT_TEXT;
obj.style.color="#aaaaaa";
}
document.getElementById("search_filtered_div").className = "no-display";
}
}
function submit_search() {
if (HAS_SEARCH_PAGE) {
var query = document.getElementById('search_autocomplete').value;
document.location = toRoot + 'search.html#q=' + query + '&t=0';
}
return false;
}
| JavaScript |
var NAVTREE_DATA =
[ [ "com.caverock.androidsvg", "com/caverock/androidsvg/package-summary.html", [ [ "Classes", null, [ [ "PreserveAspectRatio", "com/caverock/androidsvg/PreserveAspectRatio.html", null, "" ], [ "SimpleAssetResolver", "com/caverock/androidsvg/SimpleAssetResolver.html", null, "" ], [ "SVG", "com/caverock/androidsvg/SVG.html", null, "" ], [ "SVGExternalFileResolver", "com/caverock/androidsvg/SVGExternalFileResolver.html", null, "" ], [ "SVGImageView", "com/caverock/androidsvg/SVGImageView.html", null, "" ] ]
, "" ], [ "Enums", null, [ [ "PreserveAspectRatio.Alignment", "com/caverock/androidsvg/PreserveAspectRatio.Alignment.html", null, "" ], [ "PreserveAspectRatio.Scale", "com/caverock/androidsvg/PreserveAspectRatio.Scale.html", null, "" ] ]
, "" ], [ "Exceptions", null, [ [ "SVGParseException", "com/caverock/androidsvg/SVGParseException.html", null, "" ] ]
, "" ] ]
, "" ] ]
;
| JavaScript |
var API_LEVEL_ENABLED_COOKIE = "api_level_enabled";
var API_LEVEL_INDEX_COOKIE = "api_level_index";
var minLevelIndex = 0;
function toggleApiLevelSelector(checkbox) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
if (checkbox.checked) {
$("#apiLevelSelector").removeAttr("disabled");
$("#api-level-toggle label").removeClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 1, null, expiration);
} else {
$("#apiLevelSelector").attr("disabled","disabled");
$("#api-level-toggle label").addClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 0, null, expiration);
}
changeApiLevel();
}
function buildApiLevelSelector() {
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var userApiLevelIndex = readCookie(API_LEVEL_INDEX_COOKIE); // No cookie (zero) is the same as maxLevel.
if (userApiLevelEnabled == 0) {
$("#apiLevelSelector").attr("disabled","disabled");
} else {
$("#apiLevelCheckbox").attr("checked","checked");
$("#api-level-toggle label").removeClass("disabled");
}
minLevelValue = $("body").attr("class");
minLevelIndex = apiKeyToIndex(minLevelValue);
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = SINCE_DATA.length-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_LABELS[i]);
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option").get(SINCE_DATA.length - userApiLevelIndex - 1);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var selectedLevelIndex = SINCE_DATA.length - 1;
if (userApiLevelEnabled == 0) {
toggleVisisbleApis(selectedLevelIndex, "body");
} else {
selectedLevelIndex = getSelectedLevelIndex();
toggleVisisbleApis(selectedLevelIndex, "body");
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
writeCookie(API_LEVEL_INDEX_COOKIE, selectedLevelIndex, null, expiration);
}
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
showApiWarning(thing, selectedLevelIndex, minLevelIndex);
}
function showApiWarning(thing, selectedLevelIndex, minLevelIndex) {
if (selectedLevelIndex < minLevelIndex) {
$("#naMessage").show().html("<div><p><strong>This " + thing
+ " is not available with API version "
+ SINCE_LABELS[selectedLevelIndex] + ".</strong></p>"
+ "<p>To reveal this "
+ "document, change the value in the API filter above.</p>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevelIndex, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelPos = className.lastIndexOf("-")+1;
var apiLevelEndPos = className.indexOf(" ", apiLevelPos);
apiLevelEndPos = apiLevelEndPos != -1 ? apiLevelEndPos : className.length;
var apiLevelName = className.substring(apiLevelPos, apiLevelEndPos);
var apiLevelIndex = apiKeyToIndex(apiLevelName);
if (apiLevelIndex > selectedLevelIndex) {
obj.addClass("absent").attr("title","Requires API Level "+SINCE_LABELS[apiLevelIndex]+" or higher");
} else {
obj.removeClass("absent").removeAttr("title");
}
});
}
function apiKeyToIndex(key) {
for (i = 0; i < SINCE_DATA.length; i++) {
if (SINCE_DATA[i] == key) {
return i;
}
}
return -1;
}
function getSelectedLevelIndex() {
return SINCE_DATA.length - $("#apiLevelSelector").attr("selectedIndex") - 1;
}
/* NAVTREE */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
node.label_div.style.paddingLeft = 10*node.depth + "px";
if (children_data == null) {
// 12 is the width of the triangle and padding extra space
node.label_div.style.paddingLeft = ((10*node.depth)+12) + "px";
} else {
node.label_div.style.paddingLeft = 10*node.depth + "px";
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = toAssets + "images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = toAssets + "images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary.
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) $(node.get_children_ul()).addClass("absent");
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = toAssets + "images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector").attr("selectedIndex");
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function load_navtree_data() {
var navtreeData = document.createElement("script");
navtreeData.setAttribute("type","text/javascript");
navtreeData.setAttribute("src", toAssets + "navtree_data.js");
$("head").append($(navtreeData));
}
function init_default_navtree(toroot) {
init_navtree("nav-tree", toroot, NAVTREE_DATA);
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector").attr("selectedIndex");
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toAssets + "images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toAssets + "images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#doc-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#doc-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
}); | JavaScript |
var resizePackagesNav;
var classesNav;
var devdocNav;
var sidenav;
var content;
var HEADER_HEIGHT = -1;
var cookie_namespace = 'doclava_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var toRoot;
var toAssets;
var isMobile = false; // true if mobile, so we can adjust some layout
var isIE6 = false; // true if IE6
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
addLoadEvent(mobileSetup);
// If not a mobile browser, set the onresize event for IE6, and others
} else if (agent.indexOf("msie 6") != -1) {
isIE6 = true;
addLoadEvent(function() {
window.onresize = resizeAll;
});
} else {
addLoadEvent(function() {
window.onresize = resizeHeight;
});
}
function mobileSetup() {
$("body").css({'overflow':'auto'});
$("html").css({'overflow':'auto'});
$("#body-content").css({'position':'relative', 'top':'0'});
$("#doc-content").css({'overflow':'visible', 'border-left':'3px solid #DDD'});
$("#side-nav").css({'padding':'0'});
$("#nav-tree").css({'overflow-y': 'auto'});
}
/* loads the lists.js file to the page.
Loading this in the head was slowing page load time */
addLoadEvent( function() {
var lists = document.createElement("script");
lists.setAttribute("type","text/javascript");
lists.setAttribute("src", toRoot+"lists.js");
document.getElementsByTagName("head")[0].appendChild(lists);
} );
addLoadEvent( function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
} );
function setToRoot(root, assets) {
toRoot = root;
toAssets = assets;
// note: toRoot also used by carousel.js
}
function restoreWidth(navWidth) {
var windowWidth = $(window).width() + "px";
content.css({marginLeft:parseInt(navWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(navWidth) - 6 + "px"}); // necessary in order for scrollbars to be visible
}
sidenav.css({width:navWidth});
resizePackagesNav.css({width:navWidth});
classesNav.css({width:navWidth});
$("#packages-nav").css({width:navWidth});
}
function restoreHeight(packageHeight) {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
sidenav.css({height:windowHeight + "px"});
content.css({height:windowHeight + "px"});
resizePackagesNav.css({maxHeight:swapperHeight + "px", height:packageHeight});
classesNav.css({height:swapperHeight - parseInt(packageHeight) + "px"});
$("#packages-nav").css({height:parseInt(packageHeight) - 6 + "px"}); //move 6px to give space for the resize handle
devdocNav.css({height:sidenav.css("height")});
$("#nav-tree").css({height:swapperHeight + "px"});
}
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section, expiration) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
if (expiration == null) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
expiration = date.toGMTString();
}
document.cookie = cookie_namespace + section + cookie + "=" + val + "; expires=" + expiration+"; path=/";
}
function getSection() {
if (location.href.indexOf("/reference/") != -1) {
return "reference";
} else if (location.href.indexOf("/guide/") != -1) {
return "guide";
} else if (location.href.indexOf("/resources/") != -1) {
return "resources";
}
var basePath = getBaseUri(location.pathname);
return basePath.substring(1,basePath.indexOf("/",1));
}
function init() {
HEADER_HEIGHT = $("#header").height()+3;
$("#side-nav").css({position:"absolute",left:0});
content = $("#doc-content");
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
sidenav = $("#side-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = getSection() + "_";
if (!isMobile) {
$("#resize-packages-nav").resizable({handles: "s", resize: function(e, ui) { resizePackagesHeight(); } });
$(".side-nav-resizable").resizable({handles: "e", resize: function(e, ui) { resizeWidth(); } });
var cookieWidth = readCookie(cookiePath+'width');
var cookieHeight = readCookie(cookiePath+'height');
if (cookieWidth) {
restoreWidth(cookieWidth);
} else if ($(".side-nav-resizable").length) {
resizeWidth();
}
if (cookieHeight) {
restoreHeight(cookieHeight);
} else {
resizeHeight();
}
}
if (devdocNav.length) { // only dev guide, resources, and sdk
tryPopulateResourcesNav();
highlightNav(location.href);
}
}
function highlightNav(fullPageName) {
var lastSlashPos = fullPageName.lastIndexOf("/");
var firstSlashPos;
if (fullPageName.indexOf("/guide/") != -1) {
firstSlashPos = fullPageName.indexOf("/guide/");
} else if (fullPageName.indexOf("/sdk/") != -1) {
firstSlashPos = fullPageName.indexOf("/sdk/");
} else {
firstSlashPos = fullPageName.indexOf("/resources/");
}
if (lastSlashPos == (fullPageName.length - 1)) { // if the url ends in slash (add 'index.html')
fullPageName = fullPageName + "index.html";
}
// First check if the exact URL, with query string and all, is in the navigation menu
var pathPageName = fullPageName.substr(firstSlashPos);
var link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if (link.length == 0) {
var htmlPos = fullPageName.lastIndexOf(".html", fullPageName.length);
pathPageName = fullPageName.slice(firstSlashPos, htmlPos + 5); // +5 advances past ".html"
link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if ((link.length == 0) && ((fullPageName.indexOf("/guide/") != -1) || (fullPageName.indexOf("/resources/") != -1))) {
// if there's no match, then let's backstep through the directory until we find an index.html page
// that matches our ancestor directories (only for dev guide and resources)
lastBackstep = pathPageName.lastIndexOf("/");
while (link.length == 0) {
backstepDirectory = pathPageName.lastIndexOf("/", lastBackstep);
link = $("#devdoc-nav a[href$='"+ pathPageName.slice(0, backstepDirectory + 1)+"index.html']");
lastBackstep = pathPageName.lastIndexOf("/", lastBackstep - 1);
if (lastBackstep == 0) break;
}
}
}
// add 'selected' to the <li> or <div> that wraps this <a>
link.parent().addClass('selected');
// if we're in a toggleable root link (<li class=toggle-list><div><a>)
if (link.parent().parent().hasClass('toggle-list')) {
toggle(link.parent().parent(), false); // open our own list
// then also check if we're in a third-level nested list that's toggleable
if (link.parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent(), false); // open the super parent list
}
}
// if we're in a normal nav link (<li><a>) and the parent <ul> is hidden
else if (link.parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent(), false); // open the parent list
// then also check if the parent list is also nested in a hidden list
if (link.parent().parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent().parent(), false); // open the super parent list
}
}
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function resizePackagesHeight() {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13; // move 13px for swapper link at the bottom
resizePackagesNav.css({maxHeight:swapperHeight + "px"});
classesNav.css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#swapper").css({height:swapperHeight + "px"});
$("#packages-nav").css({height:parseInt(resizePackagesNav.css("height")) - 6 + "px"}); //move 6px for handle
var section = getSection();
writeCookie("height", resizePackagesNav.css("height"), section, null);
}
/* Resize the height of the side-nav and doc-content divs,
* which creates the frame effect */
function resizeHeight() {
var docContent = $("#doc-content");
// Get the window height and always resize the doc-content and side-nav divs
var windowHeight = ($(window).height() - HEADER_HEIGHT);
docContent.css({height:windowHeight + "px"});
$("#side-nav").css({height:windowHeight + "px"});
var href = location.href;
// If in the reference docs, also resize the "swapper", "classes-nav", and "nav-tree" divs
if (href.indexOf("/reference/") != -1) {
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
$("#classes-nav").css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#nav-tree").css({height:swapperHeight + "px"});
// If in the dev guide docs, also resize the "devdoc-nav" div
} else if (href.indexOf("/guide/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
} else if (href.indexOf("/resources/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
}
// Hide the "Go to top" link if there's no vertical scroll
if ( parseInt($("#jd-content").css("height")) <= parseInt(docContent.css("height")) ) {
$("a[href='#top']").css({'display':'none'});
} else {
$("a[href='#top']").css({'display':'inline'});
}
}
/* Resize the width of the "side-nav" and the left margin of the "doc-content" div,
* which creates the resizable side bar */
function resizeWidth() {
var windowWidth = $(window).width() + "px";
if (sidenav.length) {
var sidenavWidth = sidenav.css("width");
} else {
var sidenavWidth = 0;
}
content.css({marginLeft:parseInt(sidenavWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(sidenavWidth) - 6 + "px"}); // necessary in order to for scrollbars to be visible
}
resizePackagesNav.css({width:sidenavWidth});
classesNav.css({width:sidenavWidth});
$("#packages-nav").css({width:sidenavWidth});
if ($(".side-nav-resizable").length) { // Must check if the nav is resizable because IE6 calls resizeWidth() from resizeAll() for all pages
var section = getSection();
writeCookie("width", sidenavWidth, section, null);
}
}
/* For IE6 only,
* because it can't properly perform auto width for "doc-content" div,
* avoiding this for all browsers provides better performance */
function resizeAll() {
resizeHeight();
resizeWidth();
}
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function loadLast(cookiePath) {
var location = window.location.href;
if (location.indexOf("/"+cookiePath+"/") != -1) {
return true;
}
var lastPage = readCookie(cookiePath + "_lastpage");
if (lastPage) {
window.location = lastPage;
return false;
}
return true;
}
$(window).unload(function(){
var path = getBaseUri(location.pathname);
if (path.indexOf("/reference/") != -1) {
writeCookie("lastpage", path, "reference", null);
} else if (path.indexOf("/guide/") != -1) {
writeCookie("lastpage", path, "guide", null);
} else if (path.indexOf("/resources/") != -1) {
writeCookie("lastpage", path, "resources", null);
}
});
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
writeCookie("nav", nav_pref, "reference", date.toGMTString());
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
if ($("#nav-tree").is(':visible')) scrollIntoView("nav-tree");
else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
function scrollIntoView(nav) {
var navObj = $("#"+nav);
if (navObj.is(':visible')) {
var selected = $(".selected", navObj);
if (selected.length == 0) return;
if (selected.is("div")) selected = selected.parent();
var scrolling = document.getElementById(nav);
var navHeight = navObj.height();
var offsetTop = selected.position().top;
if (selected.parent().parent().is(".toggle-list")) offsetTop += selected.parent().parent().position().top;
if(offsetTop > navHeight - 92) {
scrolling.scrollTop = offsetTop - navHeight + 92;
}
}
}
function changeTabLang(lang) {
var nodes = $("#header-tabs").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { //if this languages node has a translation, show it
node.css("display","inline");
} else { //otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeNavLang(lang) {
var nodes = $("#side-nav").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { // if this languages node has a translation, show it
node.css("display","inline");
} else { // otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeDocLang(lang) {
changeTabLang(lang);
changeNavLang(lang);
}
function changeLangPref(lang, refresh) {
var date = new Date();
expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000))); // keep this for 50 years
//alert("expires: " + expires)
writeCookie("pref_lang", lang, null, expires);
//changeDocLang(lang);
if (refresh) {
l = getBaseUri(location.pathname);
window.location = l;
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
function toggleContent(obj) {
var button = $(obj);
var div = $(obj.parentNode);
var toggleMe = $(".toggle-content-toggleme",div);
if (button.hasClass("show")) {
toggleMe.slideDown();
button.removeClass("show").addClass("hide");
} else {
toggleMe.slideUp();
button.removeClass("hide").addClass("show");
}
$("span", button).toggle();
} | JavaScript |
var DATA = [
{ id:0, label:"com.caverock.androidsvg", link:"com/caverock/androidsvg/package-summary.html", type:"package" },
{ id:1, label:"com.caverock.androidsvg.PreserveAspectRatio", link:"com/caverock/androidsvg/PreserveAspectRatio.html", type:"class" },
{ id:2, label:"com.caverock.androidsvg.PreserveAspectRatio.Alignment", link:"com/caverock/androidsvg/PreserveAspectRatio.Alignment.html", type:"class" },
{ id:3, label:"com.caverock.androidsvg.PreserveAspectRatio.Scale", link:"com/caverock/androidsvg/PreserveAspectRatio.Scale.html", type:"class" },
{ id:4, label:"com.caverock.androidsvg.SVG", link:"com/caverock/androidsvg/SVG.html", type:"class" },
{ id:5, label:"com.caverock.androidsvg.SVGExternalFileResolver", link:"com/caverock/androidsvg/SVGExternalFileResolver.html", type:"class" },
{ id:6, label:"com.caverock.androidsvg.SVGImageView", link:"com/caverock/androidsvg/SVGImageView.html", type:"class" },
{ id:7, label:"com.caverock.androidsvg.SVGParseException", link:"com/caverock/androidsvg/SVGParseException.html", type:"class" },
{ id:8, label:"com.caverock.androidsvg.SimpleAssetResolver", link:"com/caverock/androidsvg/SimpleAssetResolver.html", type:"class" }
];
| JavaScript |
var gSelectedIndex = -1;
var gSelectedID = -1;
var gMatches = new Array();
var gLastText = "";
var ROW_COUNT = 20;
var gInitialized = false;
var DEFAULT_TEXT = "search developer docs";
var HAS_SEARCH_PAGE = false;
function set_row_selected(row, selected)
{
var c1 = row.cells[0];
// var c2 = row.cells[1];
if (selected) {
c1.className = "jd-autocomplete jd-selected";
// c2.className = "jd-autocomplete jd-selected jd-linktype";
} else {
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
}
}
function set_row_values(toroot, row, match)
{
var link = row.cells[0].childNodes[0];
link.innerHTML = match.__hilabel || match.label;
link.href = toroot + match.link
// row.cells[1].innerHTML = match.type;
}
function sync_selection_table(toroot)
{
var filtered = document.getElementById("search_filtered");
var r; //TR DOM object
var i; //TR iterator
gSelectedID = -1;
filtered.onmouseover = function() {
if(gSelectedIndex >= 0) {
set_row_selected(this.rows[gSelectedIndex], false);
gSelectedIndex = -1;
}
}
//initialize the table; draw it for the first time (but not visible).
if (!gInitialized) {
for (i=0; i<ROW_COUNT; i++) {
var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
// var c2 = r.insertCell(-1);
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
var link = document.createElement("a");
c1.onmousedown = function() {
window.location = this.firstChild.getAttribute("href");
}
c1.onmouseover = function() {
this.className = this.className + " jd-selected";
}
c1.onmouseout = function() {
this.className = "jd-autocomplete";
}
c1.appendChild(link);
}
/* var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
c1.className = "jd-autocomplete jd-linktype";
c1.colSpan = 2; */
gInitialized = true;
}
//if we have results, make the table visible and initialize result info
if (gMatches.length > 0) {
document.getElementById("search_filtered_div").className = "showing";
var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT;
for (i=0; i<N; i++) {
r = filtered.rows[i];
r.className = "show-row";
set_row_values(toroot, r, gMatches[i]);
set_row_selected(r, i == gSelectedIndex);
if (i == gSelectedIndex) {
gSelectedID = gMatches[i].id;
}
}
//start hiding rows that are no longer matches
for (; i<ROW_COUNT; i++) {
r = filtered.rows[i];
r.className = "no-display";
}
//if there are more results we're not showing, so say so.
/* if (gMatches.length > ROW_COUNT) {
r = filtered.rows[ROW_COUNT];
r.className = "show-row";
c1 = r.cells[0];
c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more";
} else {
filtered.rows[ROW_COUNT].className = "hide-row";
}*/
//if we have no results, hide the table
} else {
document.getElementById("search_filtered_div").className = "no-display";
}
}
function search_changed(e, kd, toroot)
{
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// 13 = enter
if (e.keyCode == 13) {
document.getElementById("search_filtered_div").className = "no-display";
if (kd && gSelectedIndex >= 0) {
window.location = toroot + gMatches[gSelectedIndex].link;
return false;
} else if (gSelectedIndex < 0) {
if (HAS_SEARCH_PAGE) {
return true;
} else {
sync_selection_table(toroot);
return false;
}
}
}
// 38 -- arrow up
else if (kd && (e.keyCode == 38)) {
if (gSelectedIndex >= 0) {
gSelectedIndex--;
}
sync_selection_table(toroot);
return false;
}
// 40 -- arrow down
else if (kd && (e.keyCode == 40)) {
if (gSelectedIndex < gMatches.length-1
&& gSelectedIndex < ROW_COUNT-1) {
gSelectedIndex++;
}
sync_selection_table(toroot);
return false;
}
else if (!kd) {
gMatches = new Array();
matchedCount = 0;
gSelectedIndex = -1;
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_results(text);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
if (gSelectedID == s.id) {
gSelectedIndex = i;
}
}
highlight_autocomplete_result_labels(text);
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
function rank_autocomplete_results(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__resultScore = _resultScoreFn(gMatches[i]);
}
gMatches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
function highlight_autocomplete_result_labels(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (focused) {
if(obj.value == DEFAULT_TEXT){
obj.value = "";
obj.style.color="#000000";
}
} else {
if(obj.value == ""){
obj.value = DEFAULT_TEXT;
obj.style.color="#aaaaaa";
}
document.getElementById("search_filtered_div").className = "no-display";
}
}
function submit_search() {
if (HAS_SEARCH_PAGE) {
var query = document.getElementById('search_autocomplete').value;
document.location = toRoot + 'search.html#q=' + query + '&t=0';
}
return false;
}
| JavaScript |
var NAVTREE_DATA =
[ [ "com.caverock.androidsvg", "com/caverock/androidsvg/package-summary.html", [ [ "Classes", null, [ [ "PreserveAspectRatio", "com/caverock/androidsvg/PreserveAspectRatio.html", null, "" ], [ "SimpleAssetResolver", "com/caverock/androidsvg/SimpleAssetResolver.html", null, "" ], [ "SVG", "com/caverock/androidsvg/SVG.html", null, "" ], [ "SVGExternalFileResolver", "com/caverock/androidsvg/SVGExternalFileResolver.html", null, "" ], [ "SVGImageView", "com/caverock/androidsvg/SVGImageView.html", null, "" ] ]
, "" ], [ "Enums", null, [ [ "PreserveAspectRatio.Alignment", "com/caverock/androidsvg/PreserveAspectRatio.Alignment.html", null, "" ], [ "PreserveAspectRatio.Scale", "com/caverock/androidsvg/PreserveAspectRatio.Scale.html", null, "" ] ]
, "" ], [ "Exceptions", null, [ [ "SVGParseException", "com/caverock/androidsvg/SVGParseException.html", null, "" ] ]
, "" ] ]
, "" ] ]
;
| JavaScript |
var API_LEVEL_ENABLED_COOKIE = "api_level_enabled";
var API_LEVEL_INDEX_COOKIE = "api_level_index";
var minLevelIndex = 0;
function toggleApiLevelSelector(checkbox) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
if (checkbox.checked) {
$("#apiLevelSelector").removeAttr("disabled");
$("#api-level-toggle label").removeClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 1, null, expiration);
} else {
$("#apiLevelSelector").attr("disabled","disabled");
$("#api-level-toggle label").addClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 0, null, expiration);
}
changeApiLevel();
}
function buildApiLevelSelector() {
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var userApiLevelIndex = readCookie(API_LEVEL_INDEX_COOKIE); // No cookie (zero) is the same as maxLevel.
if (userApiLevelEnabled == 0) {
$("#apiLevelSelector").attr("disabled","disabled");
} else {
$("#apiLevelCheckbox").attr("checked","checked");
$("#api-level-toggle label").removeClass("disabled");
}
minLevelValue = $("body").attr("class");
minLevelIndex = apiKeyToIndex(minLevelValue);
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = SINCE_DATA.length-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_LABELS[i]);
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option").get(SINCE_DATA.length - userApiLevelIndex - 1);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var selectedLevelIndex = SINCE_DATA.length - 1;
if (userApiLevelEnabled == 0) {
toggleVisisbleApis(selectedLevelIndex, "body");
} else {
selectedLevelIndex = getSelectedLevelIndex();
toggleVisisbleApis(selectedLevelIndex, "body");
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
writeCookie(API_LEVEL_INDEX_COOKIE, selectedLevelIndex, null, expiration);
}
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
showApiWarning(thing, selectedLevelIndex, minLevelIndex);
}
function showApiWarning(thing, selectedLevelIndex, minLevelIndex) {
if (selectedLevelIndex < minLevelIndex) {
$("#naMessage").show().html("<div><p><strong>This " + thing
+ " is not available with API version "
+ SINCE_LABELS[selectedLevelIndex] + ".</strong></p>"
+ "<p>To reveal this "
+ "document, change the value in the API filter above.</p>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevelIndex, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelPos = className.lastIndexOf("-")+1;
var apiLevelEndPos = className.indexOf(" ", apiLevelPos);
apiLevelEndPos = apiLevelEndPos != -1 ? apiLevelEndPos : className.length;
var apiLevelName = className.substring(apiLevelPos, apiLevelEndPos);
var apiLevelIndex = apiKeyToIndex(apiLevelName);
if (apiLevelIndex > selectedLevelIndex) {
obj.addClass("absent").attr("title","Requires API Level "+SINCE_LABELS[apiLevelIndex]+" or higher");
} else {
obj.removeClass("absent").removeAttr("title");
}
});
}
function apiKeyToIndex(key) {
for (i = 0; i < SINCE_DATA.length; i++) {
if (SINCE_DATA[i] == key) {
return i;
}
}
return -1;
}
function getSelectedLevelIndex() {
return SINCE_DATA.length - $("#apiLevelSelector").attr("selectedIndex") - 1;
}
/* NAVTREE */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
node.label_div.style.paddingLeft = 10*node.depth + "px";
if (children_data == null) {
// 12 is the width of the triangle and padding extra space
node.label_div.style.paddingLeft = ((10*node.depth)+12) + "px";
} else {
node.label_div.style.paddingLeft = 10*node.depth + "px";
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = toAssets + "images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = toAssets + "images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary.
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) $(node.get_children_ul()).addClass("absent");
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = toAssets + "images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector").attr("selectedIndex");
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function load_navtree_data() {
var navtreeData = document.createElement("script");
navtreeData.setAttribute("type","text/javascript");
navtreeData.setAttribute("src", toAssets + "navtree_data.js");
$("head").append($(navtreeData));
}
function init_default_navtree(toroot) {
init_navtree("nav-tree", toroot, NAVTREE_DATA);
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector").attr("selectedIndex");
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toAssets + "images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toAssets + "images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#doc-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#doc-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
}); | JavaScript |
var resizePackagesNav;
var classesNav;
var devdocNav;
var sidenav;
var content;
var HEADER_HEIGHT = -1;
var cookie_namespace = 'doclava_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var toRoot;
var toAssets;
var isMobile = false; // true if mobile, so we can adjust some layout
var isIE6 = false; // true if IE6
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
addLoadEvent(mobileSetup);
// If not a mobile browser, set the onresize event for IE6, and others
} else if (agent.indexOf("msie 6") != -1) {
isIE6 = true;
addLoadEvent(function() {
window.onresize = resizeAll;
});
} else {
addLoadEvent(function() {
window.onresize = resizeHeight;
});
}
function mobileSetup() {
$("body").css({'overflow':'auto'});
$("html").css({'overflow':'auto'});
$("#body-content").css({'position':'relative', 'top':'0'});
$("#doc-content").css({'overflow':'visible', 'border-left':'3px solid #DDD'});
$("#side-nav").css({'padding':'0'});
$("#nav-tree").css({'overflow-y': 'auto'});
}
/* loads the lists.js file to the page.
Loading this in the head was slowing page load time */
addLoadEvent( function() {
var lists = document.createElement("script");
lists.setAttribute("type","text/javascript");
lists.setAttribute("src", toRoot+"lists.js");
document.getElementsByTagName("head")[0].appendChild(lists);
} );
addLoadEvent( function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
} );
function setToRoot(root, assets) {
toRoot = root;
toAssets = assets;
// note: toRoot also used by carousel.js
}
function restoreWidth(navWidth) {
var windowWidth = $(window).width() + "px";
content.css({marginLeft:parseInt(navWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(navWidth) - 6 + "px"}); // necessary in order for scrollbars to be visible
}
sidenav.css({width:navWidth});
resizePackagesNav.css({width:navWidth});
classesNav.css({width:navWidth});
$("#packages-nav").css({width:navWidth});
}
function restoreHeight(packageHeight) {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
sidenav.css({height:windowHeight + "px"});
content.css({height:windowHeight + "px"});
resizePackagesNav.css({maxHeight:swapperHeight + "px", height:packageHeight});
classesNav.css({height:swapperHeight - parseInt(packageHeight) + "px"});
$("#packages-nav").css({height:parseInt(packageHeight) - 6 + "px"}); //move 6px to give space for the resize handle
devdocNav.css({height:sidenav.css("height")});
$("#nav-tree").css({height:swapperHeight + "px"});
}
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section, expiration) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
if (expiration == null) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
expiration = date.toGMTString();
}
document.cookie = cookie_namespace + section + cookie + "=" + val + "; expires=" + expiration+"; path=/";
}
function getSection() {
if (location.href.indexOf("/reference/") != -1) {
return "reference";
} else if (location.href.indexOf("/guide/") != -1) {
return "guide";
} else if (location.href.indexOf("/resources/") != -1) {
return "resources";
}
var basePath = getBaseUri(location.pathname);
return basePath.substring(1,basePath.indexOf("/",1));
}
function init() {
HEADER_HEIGHT = $("#header").height()+3;
$("#side-nav").css({position:"absolute",left:0});
content = $("#doc-content");
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
sidenav = $("#side-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = getSection() + "_";
if (!isMobile) {
$("#resize-packages-nav").resizable({handles: "s", resize: function(e, ui) { resizePackagesHeight(); } });
$(".side-nav-resizable").resizable({handles: "e", resize: function(e, ui) { resizeWidth(); } });
var cookieWidth = readCookie(cookiePath+'width');
var cookieHeight = readCookie(cookiePath+'height');
if (cookieWidth) {
restoreWidth(cookieWidth);
} else if ($(".side-nav-resizable").length) {
resizeWidth();
}
if (cookieHeight) {
restoreHeight(cookieHeight);
} else {
resizeHeight();
}
}
if (devdocNav.length) { // only dev guide, resources, and sdk
tryPopulateResourcesNav();
highlightNav(location.href);
}
}
function highlightNav(fullPageName) {
var lastSlashPos = fullPageName.lastIndexOf("/");
var firstSlashPos;
if (fullPageName.indexOf("/guide/") != -1) {
firstSlashPos = fullPageName.indexOf("/guide/");
} else if (fullPageName.indexOf("/sdk/") != -1) {
firstSlashPos = fullPageName.indexOf("/sdk/");
} else {
firstSlashPos = fullPageName.indexOf("/resources/");
}
if (lastSlashPos == (fullPageName.length - 1)) { // if the url ends in slash (add 'index.html')
fullPageName = fullPageName + "index.html";
}
// First check if the exact URL, with query string and all, is in the navigation menu
var pathPageName = fullPageName.substr(firstSlashPos);
var link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if (link.length == 0) {
var htmlPos = fullPageName.lastIndexOf(".html", fullPageName.length);
pathPageName = fullPageName.slice(firstSlashPos, htmlPos + 5); // +5 advances past ".html"
link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if ((link.length == 0) && ((fullPageName.indexOf("/guide/") != -1) || (fullPageName.indexOf("/resources/") != -1))) {
// if there's no match, then let's backstep through the directory until we find an index.html page
// that matches our ancestor directories (only for dev guide and resources)
lastBackstep = pathPageName.lastIndexOf("/");
while (link.length == 0) {
backstepDirectory = pathPageName.lastIndexOf("/", lastBackstep);
link = $("#devdoc-nav a[href$='"+ pathPageName.slice(0, backstepDirectory + 1)+"index.html']");
lastBackstep = pathPageName.lastIndexOf("/", lastBackstep - 1);
if (lastBackstep == 0) break;
}
}
}
// add 'selected' to the <li> or <div> that wraps this <a>
link.parent().addClass('selected');
// if we're in a toggleable root link (<li class=toggle-list><div><a>)
if (link.parent().parent().hasClass('toggle-list')) {
toggle(link.parent().parent(), false); // open our own list
// then also check if we're in a third-level nested list that's toggleable
if (link.parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent(), false); // open the super parent list
}
}
// if we're in a normal nav link (<li><a>) and the parent <ul> is hidden
else if (link.parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent(), false); // open the parent list
// then also check if the parent list is also nested in a hidden list
if (link.parent().parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent().parent(), false); // open the super parent list
}
}
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function resizePackagesHeight() {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13; // move 13px for swapper link at the bottom
resizePackagesNav.css({maxHeight:swapperHeight + "px"});
classesNav.css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#swapper").css({height:swapperHeight + "px"});
$("#packages-nav").css({height:parseInt(resizePackagesNav.css("height")) - 6 + "px"}); //move 6px for handle
var section = getSection();
writeCookie("height", resizePackagesNav.css("height"), section, null);
}
/* Resize the height of the side-nav and doc-content divs,
* which creates the frame effect */
function resizeHeight() {
var docContent = $("#doc-content");
// Get the window height and always resize the doc-content and side-nav divs
var windowHeight = ($(window).height() - HEADER_HEIGHT);
docContent.css({height:windowHeight + "px"});
$("#side-nav").css({height:windowHeight + "px"});
var href = location.href;
// If in the reference docs, also resize the "swapper", "classes-nav", and "nav-tree" divs
if (href.indexOf("/reference/") != -1) {
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
$("#classes-nav").css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#nav-tree").css({height:swapperHeight + "px"});
// If in the dev guide docs, also resize the "devdoc-nav" div
} else if (href.indexOf("/guide/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
} else if (href.indexOf("/resources/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
}
// Hide the "Go to top" link if there's no vertical scroll
if ( parseInt($("#jd-content").css("height")) <= parseInt(docContent.css("height")) ) {
$("a[href='#top']").css({'display':'none'});
} else {
$("a[href='#top']").css({'display':'inline'});
}
}
/* Resize the width of the "side-nav" and the left margin of the "doc-content" div,
* which creates the resizable side bar */
function resizeWidth() {
var windowWidth = $(window).width() + "px";
if (sidenav.length) {
var sidenavWidth = sidenav.css("width");
} else {
var sidenavWidth = 0;
}
content.css({marginLeft:parseInt(sidenavWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(sidenavWidth) - 6 + "px"}); // necessary in order to for scrollbars to be visible
}
resizePackagesNav.css({width:sidenavWidth});
classesNav.css({width:sidenavWidth});
$("#packages-nav").css({width:sidenavWidth});
if ($(".side-nav-resizable").length) { // Must check if the nav is resizable because IE6 calls resizeWidth() from resizeAll() for all pages
var section = getSection();
writeCookie("width", sidenavWidth, section, null);
}
}
/* For IE6 only,
* because it can't properly perform auto width for "doc-content" div,
* avoiding this for all browsers provides better performance */
function resizeAll() {
resizeHeight();
resizeWidth();
}
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function loadLast(cookiePath) {
var location = window.location.href;
if (location.indexOf("/"+cookiePath+"/") != -1) {
return true;
}
var lastPage = readCookie(cookiePath + "_lastpage");
if (lastPage) {
window.location = lastPage;
return false;
}
return true;
}
$(window).unload(function(){
var path = getBaseUri(location.pathname);
if (path.indexOf("/reference/") != -1) {
writeCookie("lastpage", path, "reference", null);
} else if (path.indexOf("/guide/") != -1) {
writeCookie("lastpage", path, "guide", null);
} else if (path.indexOf("/resources/") != -1) {
writeCookie("lastpage", path, "resources", null);
}
});
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
writeCookie("nav", nav_pref, "reference", date.toGMTString());
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
if ($("#nav-tree").is(':visible')) scrollIntoView("nav-tree");
else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
function scrollIntoView(nav) {
var navObj = $("#"+nav);
if (navObj.is(':visible')) {
var selected = $(".selected", navObj);
if (selected.length == 0) return;
if (selected.is("div")) selected = selected.parent();
var scrolling = document.getElementById(nav);
var navHeight = navObj.height();
var offsetTop = selected.position().top;
if (selected.parent().parent().is(".toggle-list")) offsetTop += selected.parent().parent().position().top;
if(offsetTop > navHeight - 92) {
scrolling.scrollTop = offsetTop - navHeight + 92;
}
}
}
function changeTabLang(lang) {
var nodes = $("#header-tabs").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { //if this languages node has a translation, show it
node.css("display","inline");
} else { //otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeNavLang(lang) {
var nodes = $("#side-nav").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { // if this languages node has a translation, show it
node.css("display","inline");
} else { // otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeDocLang(lang) {
changeTabLang(lang);
changeNavLang(lang);
}
function changeLangPref(lang, refresh) {
var date = new Date();
expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000))); // keep this for 50 years
//alert("expires: " + expires)
writeCookie("pref_lang", lang, null, expires);
//changeDocLang(lang);
if (refresh) {
l = getBaseUri(location.pathname);
window.location = l;
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
function toggleContent(obj) {
var button = $(obj);
var div = $(obj.parentNode);
var toggleMe = $(".toggle-content-toggleme",div);
if (button.hasClass("show")) {
toggleMe.slideDown();
button.removeClass("show").addClass("hide");
} else {
toggleMe.slideUp();
button.removeClass("hide").addClass("show");
}
$("span", button).toggle();
} | JavaScript |
var DATA = [
{ id:0, label:"com.caverock.androidsvg", link:"com/caverock/androidsvg/package-summary.html", type:"package" },
{ id:1, label:"com.caverock.androidsvg.PreserveAspectRatio", link:"com/caverock/androidsvg/PreserveAspectRatio.html", type:"class" },
{ id:2, label:"com.caverock.androidsvg.PreserveAspectRatio.Alignment", link:"com/caverock/androidsvg/PreserveAspectRatio.Alignment.html", type:"class" },
{ id:3, label:"com.caverock.androidsvg.PreserveAspectRatio.Scale", link:"com/caverock/androidsvg/PreserveAspectRatio.Scale.html", type:"class" },
{ id:4, label:"com.caverock.androidsvg.SVG", link:"com/caverock/androidsvg/SVG.html", type:"class" },
{ id:5, label:"com.caverock.androidsvg.SVGExternalFileResolver", link:"com/caverock/androidsvg/SVGExternalFileResolver.html", type:"class" },
{ id:6, label:"com.caverock.androidsvg.SVGImageView", link:"com/caverock/androidsvg/SVGImageView.html", type:"class" },
{ id:7, label:"com.caverock.androidsvg.SVGParseException", link:"com/caverock/androidsvg/SVGParseException.html", type:"class" },
{ id:8, label:"com.caverock.androidsvg.SimpleAssetResolver", link:"com/caverock/androidsvg/SimpleAssetResolver.html", type:"class" }
];
| JavaScript |
/**
* Creates a new level control.
* @constructor
* @param {IoMap} iomap the IO map controller.
* @param {Array.<string>} levels the levels to create switchers for.
*/
function LevelControl(iomap, levels) {
var that = this;
this.iomap_ = iomap;
this.el_ = this.initDom_(levels);
google.maps.event.addListener(iomap, 'level_changed', function() {
that.changeLevel_(iomap.get('level'));
});
}
/**
* Gets the DOM element for the control.
* @return {Element}
*/
LevelControl.prototype.getElement = function() {
return this.el_;
};
/**
* Creates the necessary DOM for the control.
* @return {Element}
*/
LevelControl.prototype.initDom_ = function(levelDefinition) {
var controlDiv = document.createElement('DIV');
controlDiv.setAttribute('id', 'levels-wrapper');
var levels = document.createElement('DIV');
levels.setAttribute('id', 'levels');
controlDiv.appendChild(levels);
var levelSelect = this.levelSelect_ = document.createElement('DIV');
levelSelect.setAttribute('id', 'level-select');
levels.appendChild(levelSelect);
this.levelDivs_ = [];
var that = this;
for (var i = 0, level; level = levelDefinition[i]; i++) {
var div = document.createElement('DIV');
div.innerHTML = 'Level ' + level;
div.setAttribute('id', 'level-' + level);
div.className = 'level';
levels.appendChild(div);
this.levelDivs_.push(div);
google.maps.event.addDomListener(div, 'click', function(e) {
var id = e.currentTarget.getAttribute('id');
var level = parseInt(id.replace('level-', ''), 10);
that.iomap_.setHash('level' + level);
});
}
controlDiv.index = 1;
return controlDiv;
};
/**
* Changes the highlighted level in the control.
* @param {number} level the level number to select.
*/
LevelControl.prototype.changeLevel_ = function(level) {
if (this.currentLevelDiv_) {
this.currentLevelDiv_.className =
this.currentLevelDiv_.className.replace(' level-selected', '');
}
var h = 25;
if (window['ioEmbed']) {
h = (window.screen.availWidth > 600) ? 34 : 24;
}
this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px';
var div = this.levelDivs_[level - 1];
div.className += ' level-selected';
this.currentLevelDiv_ = div;
};
| JavaScript |
// Copyright 2011 Google
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The Google IO Map
* @constructor
*/
var IoMap = function() {
var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025);
/** @type {Node} */
this.mapDiv_ = document.getElementById(this.MAP_ID);
var ioStyle = [
{
'featureType': 'road',
stylers: [
{ hue: '#00aaff' },
{ gamma: 1.67 },
{ saturation: -24 },
{ lightness: -38 }
]
},{
'featureType': 'road',
'elementType': 'labels',
stylers: [
{ invert_lightness: true }
]
}];
/** @type {boolean} */
this.ready_ = false;
/** @type {google.maps.Map} */
this.map_ = new google.maps.Map(this.mapDiv_, {
zoom: 18,
center: moscone,
navigationControl: true,
mapTypeControl: false,
scaleControl: true,
mapTypeId: 'io',
streetViewControl: false
});
var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle));
this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style));
google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['onMapReady']();
}
});
/** @type {Array.<Floor>} */
this.floors_ = [];
for (var i = 0; i < this.LEVELS_.length; i++) {
this.floors_.push(new Floor(this.map_));
}
this.addLevelControl_();
this.addMapOverlay_();
this.loadMapContent_();
this.initLocationHashWatcher_();
if (!document.location.hash) {
this.showLevel(1, true);
}
}
IoMap.prototype = new google.maps.MVCObject;
/**
* The id of the Element to add the map to.
*
* @type {string}
* @const
*/
IoMap.prototype.MAP_ID = 'map-canvas';
/**
* The levels of the Moscone Center.
*
* @type {Array.<string>}
* @private
*/
IoMap.prototype.LEVELS_ = ['1', '2', '3'];
/**
* Location where the tiles are hosted.
*
* @type {string}
* @private
*/
IoMap.prototype.BASE_TILE_URL_ =
'http://www.gstatic.com/io2010maps/tiles/5/';
/**
* The minimum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MIN_ZOOM_ = 16;
/**
* The maximum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MAX_ZOOM_ = 20;
/**
* The template for loading tiles. Replace {L} with the level, {Z} with the
* zoom level, {X} and {Y} with respective tile coordinates.
*
* @type {string}
* @private
*/
IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ +
'L{L}_{Z}_{X}_{Y}.png';
/**
* @type {string}
* @private
*/
IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ =
IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png';
/**
* The extent of the overlay at certain zoom levels.
*
* @type {Object.<string, Array.<Array.<number>>>}
* @private
*/
IoMap.prototype.RESOLUTION_BOUNDS_ = {
16: [[10484, 10485], [25328, 25329]],
17: [[20969, 20970], [50657, 50658]],
18: [[41939, 41940], [101315, 101317]],
19: [[83878, 83881], [202631, 202634]],
20: [[167757, 167763], [405263, 405269]]
};
/**
* The previous hash to compare against.
*
* @type {string?}
* @private
*/
IoMap.prototype.prevHash_ = null;
/**
* Initialise the location hash watcher.
*
* @private
*/
IoMap.prototype.initLocationHashWatcher_ = function() {
var that = this;
if ('onhashchange' in window) {
window.addEventListener('hashchange', function() {
that.parseHash_();
}, true);
} else {
var that = this
window.setInterval(function() {
that.parseHash_();
}, 100);
}
this.parseHash_();
};
/**
* Called from Android.
*
* @param {Number} x A percentage to pan left by.
*/
IoMap.prototype.panLeft = function(x) {
var div = this.map_.getDiv();
var left = div.clientWidth * x;
this.map_.panBy(left, 0);
};
IoMap.prototype['panLeft'] = IoMap.prototype.panLeft;
/**
* Adds the level switcher to the top left of the map.
*
* @private
*/
IoMap.prototype.addLevelControl_ = function() {
var control = new LevelControl(this, this.LEVELS_).getElement();
this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control);
};
/**
* Shows a floor based on the content of location.hash.
*
* @private
*/
IoMap.prototype.parseHash_ = function() {
var hash = document.location.hash;
if (hash == this.prevHash_) {
return;
}
this.prevHash_ = hash;
var level = 1;
if (hash) {
var match = hash.match(/level(\d)(?:\:([\w-]+))?/);
if (match && match[1]) {
level = parseInt(match[1], 10);
}
}
this.showLevel(level, true);
};
/**
* Updates location.hash based on the currently shown floor.
*
* @param {string?} opt_hash
*/
IoMap.prototype.setHash = function(opt_hash) {
var hash = document.location.hash.substring(1);
if (hash == opt_hash) {
return;
}
if (opt_hash) {
document.location.hash = opt_hash;
} else {
document.location.hash = 'level' + this.get('level');
}
};
IoMap.prototype['setHash'] = IoMap.prototype.setHash;
/**
* Called from spreadsheets.
*/
IoMap.prototype.loadSandboxCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.companyName = entry['gsx$companyname']['$t'];
item.companyUrl = entry['gsx$companyurl']['$t'];
var p = entry['gsx$companypod']['$t'];
item.pod = p;
p = p.toLowerCase().replace(/\s+/, '');
item.sessionRoom = p;
contentItems.push(item);
};
this.sandboxItems_ = contentItems;
this.ready_ = true;
this.addMapContent_();
};
/**
* Called from spreadsheets.
*
* @param {Object} json The json feed from the spreadsheet.
*/
IoMap.prototype.loadSessionsCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.sessionDate = entry['gsx$sessiondate']['$t'];
item.sessionAbstract = entry['gsx$sessionabstract']['$t'];
item.sessionHashtag = entry['gsx$sessionhashtag']['$t'];
item.sessionLevel = entry['gsx$sessionlevel']['$t'];
item.sessionTitle = entry['gsx$sessiontitle']['$t'];
item.sessionTrack = entry['gsx$sessiontrack']['$t'];
item.sessionUrl = entry['gsx$sessionurl']['$t'];
item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t'];
item.sessionTime = entry['gsx$sessiontime']['$t'];
item.sessionRoom = entry['gsx$sessionroom']['$t'];
item.sessionTags = entry['gsx$sessiontags']['$t'];
item.sessionSpeakers = entry['gsx$sessionspeakers']['$t'];
if (item.sessionDate.indexOf('10') != -1) {
item.sessionDay = 10;
} else {
item.sessionDay = 11;
}
var timeParts = item.sessionTime.split('-');
item.sessionStart = this.convertTo24Hour_(timeParts[0]);
item.sessionEnd = this.convertTo24Hour_(timeParts[1]);
contentItems.push(item);
}
this.sessionItems_ = contentItems;
};
/**
* Converts the time in the spread sheet to 24 hour time.
*
* @param {string} time The time like 10:42am.
*/
IoMap.prototype.convertTo24Hour_ = function(time) {
var pm = time.indexOf('pm') != -1;
time = time.replace(/[am|pm]/ig, '');
if (pm) {
var bits = time.split(':');
var hr = parseInt(bits[0], 10);
if (hr < 12) {
time = (hr + 12) + ':' + bits[1];
}
}
return time;
};
/**
* Loads the map content from Google Spreadsheets.
*
* @private
*/
IoMap.prototype.loadMapContent_ = function() {
// Initiate a JSONP request.
var that = this;
// Add a exposed call back function
window['loadSessionsCallback'] = function(json) {
that.loadSessionsCallback(json);
}
// Add a exposed call back function
window['loadSandboxCallback'] = function(json) {
that.loadSandboxCallback(json);
}
var key = 'tmaLiaNqIWYYtuuhmIyG0uQ';
var worksheetIDs = {
sessions: 'od6',
sandbox: 'od4'
};
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sessions + '/public/values' +
'?alt=json-in-script&callback=loadSessionsCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sandbox + '/public/values' +
'?alt=json-in-script&callback=loadSandboxCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
/**
* Called from Android.
*
* @param {string} roomId The id of the room to load.
*/
IoMap.prototype.showLocationById = function(roomId) {
var locations = this.LOCATIONS_;
for (var level in locations) {
var levelId = level.replace('LEVEL', '');
for (var loc in locations[level]) {
var room = locations[level][loc];
if (loc == roomId) {
var pos = new google.maps.LatLng(room.lat, room.lng);
this.map_.panTo(pos);
this.map_.setZoom(19);
this.showLevel(levelId);
if (room.marker_) {
room.marker_.setAnimation(google.maps.Animation.BOUNCE);
// Disable the animation after 5 seconds.
window.setTimeout(function() {
room.marker_.setAnimation();
}, 5000);
}
return;
}
}
}
};
IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById;
/**
* Called when the level is changed. Hides and shows floors.
*/
IoMap.prototype['level_changed'] = function() {
var level = this.get('level');
if (this.infoWindow_) {
this.infoWindow_.setMap(null);
}
for (var i = 1, floor; floor = this.floors_[i - 1]; i++) {
if (i == level) {
floor.show();
} else {
floor.hide();
}
}
this.setHash('level' + level);
};
/**
* Shows a particular floor.
*
* @param {string} level The level to show.
* @param {boolean=} opt_force if true, changes the floor even if it's already
* the current floor.
*/
IoMap.prototype.showLevel = function(level, opt_force) {
if (!opt_force && level == this.get('level')) {
return;
}
this.set('level', level);
};
IoMap.prototype['showLevel'] = IoMap.prototype.showLevel;
/**
* Create a marker with the content item's correct icon.
*
* @param {Object} item The content item for the marker.
* @return {google.maps.Marker} The new marker.
* @private
*/
IoMap.prototype.createContentMarker_ = function(item) {
if (!item.icon) {
item.icon = 'generic';
}
var image;
var shadow;
switch(item.icon) {
case 'generic':
case 'info':
case 'media':
var image = new google.maps.MarkerImage(
'marker-' + item.icon + '.png',
new google.maps.Size(30, 28),
new google.maps.Point(0, 0),
new google.maps.Point(13, 26));
var shadow = new google.maps.MarkerImage(
'marker-shadow.png',
new google.maps.Size(30, 28),
new google.maps.Point(0,0),
new google.maps.Point(13, 26));
break;
case 'toilets':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(35, 35),
new google.maps.Point(0, 0),
new google.maps.Point(17, 17));
break;
case 'elevator':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(48, 26),
new google.maps.Point(0, 0),
new google.maps.Point(24, 13));
break;
}
var inactive = item.type == 'inactive';
var latLng = new google.maps.LatLng(item.lat, item.lng);
var marker = new SmartMarker({
position: latLng,
shadow: shadow,
icon: image,
title: item.title,
minZoom: inactive ? 19 : 18,
clickable: !inactive
});
marker['type_'] = item.type;
if (!inactive) {
var that = this;
google.maps.event.addListener(marker, 'click', function() {
that.openContentInfo_(item);
});
}
return marker;
};
/**
* Create a label with the content item's title atribute, if it exists.
*
* @param {Object} item The content item for the marker.
* @return {MapLabel?} The new label.
* @private
*/
IoMap.prototype.createContentLabel_ = function(item) {
if (!item.title || item.suppressLabel) {
return null;
}
var latLng = new google.maps.LatLng(item.lat, item.lng);
return new MapLabel({
'text': item.title,
'position': latLng,
'minZoom': item.labelMinZoom || 18,
'align': item.labelAlign || 'center',
'fontColor': item.labelColor,
'fontSize': item.labelSize || 12
});
}
/**
* Open a info window a content item.
*
* @param {Object} item A content item with content and a marker.
*/
IoMap.prototype.openContentInfo_ = function(item) {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['openContentInfo'](item.room);
return;
}
var sessionBase = 'http://www.google.com/events/io/2011/sessions.html';
var now = new Date();
var may11 = new Date('May 11, 2011');
var day = now < may11 ? 10 : 11;
var type = item.type;
var id = item.id;
var title = item.title;
var content = ['<div class="infowindow">'];
var sessions = [];
var empty = true;
if (item.type == 'session') {
if (day == 10) {
content.push('<h3>' + title + ' - Tuesday May 10</h3>');
} else {
content.push('<h3>' + title + ' - Wednesday May 11</h3>');
}
for (var i = 0, session; session = this.sessionItems_[i]; i++) {
if (session.sessionRoom == item.room && session.sessionDay == day) {
sessions.push(session);
empty = false;
}
}
sessions.sort(this.sortSessions_);
for (var i = 0, session; session = sessions[i]; i++) {
content.push('<div class="session"><div class="session-time">' +
session.sessionTime + '</div><div class="session-title"><a href="' +
session.sessionUrl + '">' +
session.sessionTitle + '</a></div></div>');
}
}
if (item.type == 'sandbox') {
var sandboxName;
for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) {
if (sandbox.sessionRoom == item.room) {
if (!sandboxName) {
sandboxName = sandbox.pod;
content.push('<h3>' + sandbox.pod + '</h3>');
content.push('<div class="sandbox">');
}
content.push('<div class="sandbox-items"><a href="http://' +
sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>');
empty = false;
}
}
content.push('</div>');
empty = false;
}
if (empty) {
return;
}
content.push('</div>');
var pos = new google.maps.LatLng(item.lat, item.lng);
if (!this.infoWindow_) {
this.infoWindow_ = new google.maps.InfoWindow();
}
this.infoWindow_.setContent(content.join(''));
this.infoWindow_.setPosition(pos);
this.infoWindow_.open(this.map_);
};
/**
* A custom sort function to sort the sessions by start time.
*
* @param {string} a SessionA<enter description here>.
* @param {string} b SessionB.
* @return {boolean} True if sessionA is after sessionB.
*/
IoMap.prototype.sortSessions_ = function(a, b) {
var aStart = parseInt(a.sessionStart.replace(':', ''), 10);
var bStart = parseInt(b.sessionStart.replace(':', ''), 10);
return aStart > bStart;
};
/**
* Adds all overlays (markers, labels) to the map.
*/
IoMap.prototype.addMapContent_ = function() {
if (!this.ready_) {
return;
}
for (var i = 0, level; level = this.LEVELS_[i]; i++) {
var floor = this.floors_[i];
var locations = this.LOCATIONS_['LEVEL' + level];
for (var roomId in locations) {
var room = locations[roomId];
if (room.room == undefined) {
room.room = roomId;
}
if (room.type != 'label') {
var marker = this.createContentMarker_(room);
floor.addOverlay(marker);
room.marker_ = marker;
}
var label = this.createContentLabel_(room);
floor.addOverlay(label);
}
}
};
/**
* Gets the correct tile url for the coordinates and zoom.
*
* @param {google.maps.Point} coord The coordinate of the tile.
* @param {Number} zoom The current zoom level.
* @return {string} The url to the tile.
*/
IoMap.prototype.getTileUrl = function(coord, zoom) {
// Ensure that the requested resolution exists for this tile layer.
if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) {
return '';
}
// Ensure that the requested tile x,y exists.
if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x ||
coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) ||
(this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y ||
coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) {
return '';
}
var template = this.TILE_TEMPLATE_URL_;
if (16 <= zoom && zoom <= 17) {
template = this.SIMPLE_TILE_TEMPLATE_URL_;
}
return template
.replace('{L}', /** @type string */(this.get('level')))
.replace('{Z}', /** @type string */(zoom))
.replace('{X}', /** @type string */(coord.x))
.replace('{Y}', /** @type string */(coord.y));
};
/**
* Add the floor overlay to the map.
*
* @private
*/
IoMap.prototype.addMapOverlay_ = function() {
var that = this;
var overlay = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return that.getTileUrl(coord, zoom);
},
tileSize: new google.maps.Size(256, 256)
});
google.maps.event.addListener(this, 'level_changed', function() {
var overlays = that.map_.overlayMapTypes;
if (overlays.length) {
overlays.removeAt(0);
}
overlays.push(overlay);
});
};
/**
* All the features of the map.
* @type {Object.<string, Object.<string, Object.<string, *>>>}
*/
IoMap.prototype.LOCATIONS_ = {
'LEVEL1': {
'northentrance': {
lat: 37.78381535905965,
lng: -122.40362226963043,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'eastentrance': {
lat: 37.78328434094279,
lng: -122.40319311618805,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'lunchroom': {
lat: 37.783112633669575,
lng: -122.40407556295395,
title: 'Lunch Room'
},
'restroom1a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator1a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'gearpickup': {
lat: 37.78367863020862,
lng: -122.4037617444992,
title: 'Gear Pickup',
type: 'label'
},
'checkin': {
lat: 37.78334369645064,
lng: -122.40335404872894,
title: 'Check In',
type: 'label'
},
'escalators1': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
}
},
'LEVEL2': {
'escalators2': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left',
labelMinZoom: 19
},
'press': {
lat: 37.78316774962791,
lng: -122.40360751748085,
title: 'Press Room',
type: 'label'
},
'restroom2a': {
lat: 37.7835334217721,
lng: -122.40386635065079,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom2b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator2a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'1': {
lat: 37.78346240732338,
lng: -122.40415401756763,
icon: 'media',
title: 'Room 1',
type: 'session',
room: '1'
},
'2': {
lat: 37.78335005596647,
lng: -122.40431495010853,
icon: 'media',
title: 'Room 2',
type: 'session',
room: '2'
},
'3': {
lat: 37.783215446097124,
lng: -122.404490634799,
icon: 'media',
title: 'Room 3',
type: 'session',
room: '3'
},
'4': {
lat: 37.78332461789977,
lng: -122.40381203591824,
icon: 'media',
title: 'Room 4',
type: 'session',
room: '4'
},
'5': {
lat: 37.783186828219335,
lng: -122.4039850383997,
icon: 'media',
title: 'Room 5',
type: 'session',
room: '5'
},
'6': {
lat: 37.783013000871364,
lng: -122.40420497953892,
icon: 'media',
title: 'Room 6',
type: 'session',
room: '6'
},
'7': {
lat: 37.7828783903882,
lng: -122.40438133478165,
icon: 'media',
title: 'Room 7',
type: 'session',
room: '7'
},
'8': {
lat: 37.78305009820564,
lng: -122.40378588438034,
icon: 'media',
title: 'Room 8',
type: 'session',
room: '8'
},
'9': {
lat: 37.78286673120095,
lng: -122.40402393043041,
icon: 'media',
title: 'Room 9',
type: 'session',
room: '9'
},
'10': {
lat: 37.782719401312626,
lng: -122.40420028567314,
icon: 'media',
title: 'Room 10',
type: 'session',
room: '10'
},
'appengine': {
lat: 37.783362774996625,
lng: -122.40335941314697,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'App Engine'
},
'chrome': {
lat: 37.783730566003555,
lng: -122.40378990769386,
type: 'sandbox',
icon: 'generic',
title: 'Chrome'
},
'googleapps': {
lat: 37.783303419504094,
lng: -122.40320384502411,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Apps'
},
'geo': {
lat: 37.783365954753805,
lng: -122.40314483642578,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Geo'
},
'accessibility': {
lat: 37.783414711013485,
lng: -122.40342646837234,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Accessibility'
},
'developertools': {
lat: 37.783457107734876,
lng: -122.40347877144814,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Dev Tools'
},
'commerce': {
lat: 37.78349102509448,
lng: -122.40351900458336,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Commerce'
},
'youtube': {
lat: 37.783537661438515,
lng: -122.40358605980873,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'YouTube'
},
'officehoursfloor2a': {
lat: 37.78249045644304,
lng: -122.40410104393959,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2': {
lat: 37.78266852473624,
lng: -122.40387573838234,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2b': {
lat: 37.782844472747406,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
}
},
'LEVEL3': {
'escalators3': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
},
'restroom3a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom3b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator3a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'keynote': {
lat: 37.783250423488326,
lng: -122.40417748689651,
icon: 'media',
title: 'Keynote',
type: 'label'
},
'11': {
lat: 37.78283069370135,
lng: -122.40408763289452,
icon: 'media',
title: 'Room 11',
type: 'session',
room: '11'
},
'googletv': {
lat: 37.7837125474666,
lng: -122.40362092852592,
type: 'sandbox',
icon: 'generic',
title: 'Google TV'
},
'android': {
lat: 37.783530242022124,
lng: -122.40358874201775,
type: 'sandbox',
icon: 'generic',
title: 'Android'
},
'officehoursfloor3': {
lat: 37.782843412820846,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor3a': {
lat: 37.78267170452323,
lng: -122.40387842059135,
title: 'Office Hours',
type: 'label'
}
}
};
google.maps.event.addDomListener(window, 'load', function() {
window['IoMap'] = new IoMap();
});
| JavaScript |
/**
* Creates a new Floor.
* @constructor
* @param {google.maps.Map=} opt_map
*/
function Floor(opt_map) {
/**
* @type Array.<google.maps.MVCObject>
*/
this.overlays_ = [];
/**
* @type boolean
*/
this.shown_ = true;
if (opt_map) {
this.setMap(opt_map);
}
}
/**
* @param {google.maps.Map} map
*/
Floor.prototype.setMap = function(map) {
this.map_ = map;
};
/**
* @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel.
* Requires a setMap method.
*/
Floor.prototype.addOverlay = function(overlay) {
if (!overlay) return;
this.overlays_.push(overlay);
overlay.setMap(this.shown_ ? this.map_ : null);
};
/**
* Sets the map on all the overlays
* @param {google.maps.Map} map The map to set.
*/
Floor.prototype.setMapAll_ = function(map) {
this.shown_ = !!map;
for (var i = 0, overlay; overlay = this.overlays_[i]; i++) {
overlay.setMap(map);
}
};
/**
* Hides the floor and all associated overlays.
*/
Floor.prototype.hide = function() {
this.setMapAll_(null);
};
/**
* Shows the floor and all associated overlays.
*/
Floor.prototype.show = function() {
this.setMapAll_(this.map_);
};
| JavaScript |
/**
* @license
*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview SmartMarker.
*
* @author Chris Broadfoot (cbro@google.com)
*/
/**
* A google.maps.Marker that has some smarts about the zoom levels it should be
* shown.
*
* Options are the same as google.maps.Marker, with the addition of minZoom and
* maxZoom. These zoom levels are inclusive. That is, a SmartMarker with
* a minZoom and maxZoom of 13 will only be shown at zoom level 13.
* @constructor
* @extends google.maps.Marker
* @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom.
*/
function SmartMarker(opts) {
var marker = new google.maps.Marker;
// default min/max Zoom - shows the marker all the time.
marker.setValues({
'minZoom': 0,
'maxZoom': Infinity
});
// the current listener (if any), triggered on map zoom_changed
var mapZoomListener;
google.maps.event.addListener(marker, 'map_changed', function() {
if (mapZoomListener) {
google.maps.event.removeListener(mapZoomListener);
}
var map = marker.getMap();
if (map) {
var listener = SmartMarker.newZoomListener_(marker);
mapZoomListener = google.maps.event.addListener(map, 'zoom_changed',
listener);
// Call the listener straight away. The map may already be initialized,
// so it will take user input for zoom_changed to be fired.
listener();
}
});
marker.setValues(opts);
return marker;
}
window['SmartMarker'] = SmartMarker;
/**
* Creates a new listener to be triggered on 'zoom_changed' event.
* Hides and shows the target Marker based on the map's zoom level.
* @param {google.maps.Marker} marker The target marker.
* @return Function
*/
SmartMarker.newZoomListener_ = function(marker) {
var map = marker.getMap();
return function() {
var zoom = map.getZoom();
var minZoom = Number(marker.get('minZoom'));
var maxZoom = Number(marker.get('maxZoom'));
marker.setVisible(zoom >= minZoom && zoom <= maxZoom);
};
};
| JavaScript |
//=============================================================================
// System : Sandcastle Help File Builder
// File : TOC.js
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 04/11/2008
// Note : Copyright 2006-2008, Eric Woodruff, All rights reserved
// Compiler: JavaScript
//
// This file contains the methods necessary to implement a simple tree view
// for the table of content with a resizable splitter and Ajax support to
// load tree nodes on demand. It also contains the script necessary to do
// full-text searches.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://www.CodePlex.com/SHFB. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.3.0.0 09/12/2006 EFW Created the code
// 1.4.0.2 06/15/2007 EFW Reworked to get rid of frame set and to add
// support for Ajax to load tree nodes on demand.
// 1.5.0.0 06/24/2007 EFW Added full-text search capabilities
// 1.6.0.7 04/01/2008 EFW Merged changes from Ferdinand Prantl to add a
// website keyword index. Added support for "topic"
// query string option.
//=============================================================================
// IE flag
var isIE = (navigator.userAgent.indexOf("MSIE") >= 0);
// Minimum width of the TOC div
var minWidth = 100;
// Elements and sizing info
var divTOC, divSizer, topicContent, divNavOpts, divSearchOpts, divSearchResults,
divIndexOpts, divIndexResults, divTree, docBody, maxWidth, offset,
txtSearchText, chkSortByTitle;
// Last node selected
var lastNode, lastSearchNode, lastIndexNode;
// Last page with keyword index
var currentIndexPage = 0;
//============================================================================
// Initialize the tree view and resize the content
function Initialize()
{
docBody = document.getElementsByTagName("body")[0];
divTOC = document.getElementById("TOCDiv");
divSizer = document.getElementById("TOCSizer");
topicContent = document.getElementById("TopicContent");
divNavOpts = document.getElementById("divNavOpts");
divSearchOpts = document.getElementById("divSearchOpts");
divSearchResults = document.getElementById("divSearchResults");
divIndexOpts = document.getElementById("divIndexOpts");
divIndexResults = document.getElementById("divIndexResults");
divTree = document.getElementById("divTree");
txtSearchText = document.getElementById("txtSearchText");
chkSortByTitle = document.getElementById("chkSortByTitle");
// The sizes are bit off in FireFox
if(!isIE)
divNavOpts.style.width = divSearchOpts.style.width =
divIndexOpts.style.width = 292;
ResizeTree();
SyncTOC();
// Use an alternate default page if a topic is specified in
// the query string.
var queryString = document.location.search;
if(queryString != "")
{
var idx, options = queryString.split(/[\?\=\&]/);
for(idx = 0; idx < options.length; idx++)
if(options[idx] == "topic" && idx + 1 < options.length)
{
topicContent.src = options[idx + 1];
break;
}
}
}
//============================================================================
// Navigation and expand/collaps code
// Synchronize the table of content with the selected page if possible
function SyncTOC()
{
var idx, anchor, base, href, url, anchors, treeNode, saveNode;
base = window.location.href;
base = base.substr(0, base.lastIndexOf("/") + 1);
if(base.substr(0, 5) == "file:" && base.substr(0, 8) != "file:///")
base = base.replace("file://", "file:///");
url = GetCurrentUrl();
if(url == "")
return false;
if(url.substr(0, 5) == "file:" && url.substr(0, 8) != "file:///")
url = url.replace("file://", "file:///");
while(true)
{
anchors = divTree.getElementsByTagName("A");
anchor = null;
for(idx = 0; idx < anchors.length; idx++)
{
href = anchors[idx].href;
if(href.substring(0, 7) != 'http://' &&
href.substring(0, 8) != 'https://' &&
href.substring(0, 7) != 'file://')
href = base + href;
if(href == url)
{
anchor = anchors[idx];
break;
}
}
if(anchor == null)
{
// If it contains a "#", strip anything after that and try again
if(url.indexOf("#") != -1)
{
url = url.substr(0, url.indexOf("#"));
continue;
}
return;
}
break;
}
// If found, select it and find the parent tree node
SelectNode(anchor);
saveNode = anchor;
lastNode = null;
while(anchor != null)
{
if(anchor.className == "TreeNode")
{
treeNode = anchor;
break;
}
anchor = anchor.parentNode;
}
// Expand it and all of its parents
while(anchor != null)
{
Expand(anchor);
anchor = anchor.parentNode;
while(anchor != null)
{
if(anchor.className == "TreeNode")
break;
anchor = anchor.parentNode;
}
}
lastNode = saveNode;
// Scroll the node into view
var windowTop = lastNode.offsetTop - divTree.offsetTop - divTree.scrollTop;
var windowBottom = divTree.clientHeight - windowTop - lastNode.offsetHeight;
if(windowTop < 0)
divTree.scrollTop += windowTop - 30;
else
if(windowBottom < 0)
divTree.scrollTop -= windowBottom - 30;
}
// Get the currently loaded URL from the IFRAME
function GetCurrentUrl()
{
var base, url = "";
try
{
url = window.frames["TopicContent"].document.URL.replace(/\\/g, "/");
}
catch(e)
{
// If this happens the user probably navigated to another frameset
// that didn't make itself the topmost frameset and we don't have
// control of the other frame anymore. In that case, just reload
// our index page.
base = window.location.href;
base = base.substr(0, base.lastIndexOf("/") + 1);
if(base.substr(0, 5) == "file:" && base.substr(0, 8) != "file:///")
base = base.replace("file://", "file:///");
if(base.substr(0, 5) == "file:")
top.location.href = base + "Index.html";
else
top.location.href = base + "Index.aspx";
}
return url;
}
// Expand or collapse all nodes
function ExpandOrCollapseAll(expandNodes)
{
var divIdx, childIdx, img, divs = document.getElementsByTagName("DIV");
var childNodes, child, div, link, img;
for(divIdx = 0; divIdx < divs.length; divIdx++)
if(divs[divIdx].className == "Hidden" ||
divs[divIdx].className == "Visible")
{
childNodes = divs[divIdx].parentNode.childNodes;
for(childIdx = 0; childIdx < childNodes.length; childIdx++)
{
child = childNodes[childIdx];
if(child.className == "TreeNodeImg")
img = child;
if(child.className == "Hidden" || child.className == "Visible")
{
div = child;
break;
}
}
if(div.className == "Visible" && !expandNodes)
{
div.className = "Hidden";
img.src = "Collapsed.gif";
}
else
if(div.className == "Hidden" && expandNodes)
{
div.className = "Visible";
img.src = "Expanded.gif";
if(div.innerHTML == "")
FillNode(div, true)
}
}
}
// Toggle the state of the specified node
function Toggle(node)
{
var i, childNodes, child, div, link;
childNodes = node.parentNode.childNodes;
for(i = 0; i < childNodes.length; i++)
{
child = childNodes[i];
if(child.className == "Hidden" || child.className == "Visible")
{
div = child;
break;
}
}
if(div.className == "Visible")
{
div.className = "Hidden";
node.src = "Collapsed.gif";
}
else
{
div.className = "Visible";
node.src = "Expanded.gif";
if(div.innerHTML == "")
FillNode(div, false)
}
}
// Expand the selected node
function Expand(node)
{
var i, childNodes, child, div, img;
// If not valid, don't bother
if(GetCurrentUrl() == "")
return false;
if(node.tagName == "A")
childNodes = node.parentNode.childNodes;
else
childNodes = node.childNodes;
for(i = 0; i < childNodes.length; i++)
{
child = childNodes[i];
if(child.className == "TreeNodeImg")
img = child;
if(child.className == "Hidden" || child.className == "Visible")
{
div = child;
break;
}
}
if(lastNode != null)
lastNode.className = "UnselectedNode";
div.className = "Visible";
img.src = "Expanded.gif";
if(node.tagName == "A")
{
node.className = "SelectedNode";
lastNode = node;
}
if(div.innerHTML == "")
FillNode(div, false)
return true;
}
// Set the style of the specified node to "selected"
function SelectNode(node)
{
// If not valid, don't bother
if(GetCurrentUrl() == "")
return false;
if(lastNode != null)
lastNode.className = "UnselectedNode";
node.className = "SelectedNode";
lastNode = node;
return true;
}
//============================================================================
// Ajax-related code used to fill the tree nodes on demand
function GetXmlHttpRequest()
{
var xmlHttp = null;
// If IE7, Mozilla, Safari, etc., use the native object.
// Otherwise, use the ActiveX control for IE5.x and IE6.
if(window.XMLHttpRequest)
xmlHttp = new XMLHttpRequest();
else
if(window.ActiveXObject)
xmlHttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");
return xmlHttp;
}
// Perform an AJAX-style request for the contents of a node and put the
// contents into the empty div.
function FillNode(div, expandChildren)
{
var xmlHttp = GetXmlHttpRequest(), now = new Date();
if(xmlHttp == null)
{
div.innerHTML = "<b>XML HTTP request not supported!</b>";
return;
}
div.innerHTML = "Loading...";
// Add a unique hash to ensure it doesn't use cached results
xmlHttp.open("GET", "FillNode.aspx?Id=" + div.id + "&hash=" +
now.getTime(), true);
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
div.innerHTML = xmlHttp.responseText;
if(expandChildren)
ExpandOrCollapseAll(true);
}
}
xmlHttp.send(null)
}
//============================================================================
// Resizing code
// Resize the tree div so that it fills the document body
function ResizeTree()
{
var y, newHeight;
if(self.innerHeight) // All but IE
y = self.innerHeight;
else // IE - Strict
if(document.documentElement && document.documentElement.clientHeight)
y = document.documentElement.clientHeight;
else // Everything else
if(document.body)
y = document.body.clientHeight;
newHeight = y - parseInt(divNavOpts.style.height, 10) - 6;
if(newHeight < 50)
newHeight = 50;
divTree.style.height = newHeight;
newHeight = y - parseInt(divSearchOpts.style.height, 10) - 6;
if(newHeight < 100)
newHeight = 100;
divSearchResults.style.height = newHeight;
newHeight = y - parseInt(divIndexOpts.style.height, 10) - 6;
if(newHeight < 25)
newHeight = 25;
divIndexResults.style.height = newHeight;
// Resize the content div
ResizeContent();
}
// Resize the content div
function ResizeContent()
{
if(isIE)
maxWidth = docBody.clientWidth;
else
maxWidth = docBody.clientWidth - 4;
topicContent.style.width = maxWidth - (divSizer.offsetLeft +
divSizer.offsetWidth);
maxWidth -= minWidth;
}
// This is called to prepare for dragging the sizer div
function OnMouseDown(event)
{
var x;
// Make sure the splitter is at the top of the z-index
divSizer.style.zIndex = 5000;
// The content is in an IFRAME which steals mouse events so
// hide it while resizing.
topicContent.style.display = "none";
if(isIE)
x = window.event.clientX + document.documentElement.scrollLeft +
document.body.scrollLeft;
else
x = event.clientX + window.scrollX;
// Save starting offset
offset = parseInt(divSizer.style.left, 10);
if(isNaN(offset))
offset = 0;
offset -= x;
if(isIE)
{
document.attachEvent("onmousemove", OnMouseMove);
document.attachEvent("onmouseup", OnMouseUp);
window.event.cancelBubble = true;
window.event.returnValue = false;
}
else
{
document.addEventListener("mousemove", OnMouseMove, true);
document.addEventListener("mouseup", OnMouseUp, true);
event.preventDefault();
}
}
// Resize the TOC and content divs as the sizer is dragged
function OnMouseMove(event)
{
var x, pos;
// Get cursor position with respect to the page
if(isIE)
x = window.event.clientX + document.documentElement.scrollLeft +
document.body.scrollLeft;
else
x = event.clientX + window.scrollX;
left = offset + x;
// Adjusts the width of the TOC divs
pos = (event.clientX > maxWidth) ? maxWidth :
(event.clientX < minWidth) ? minWidth : event.clientX;
divTOC.style.width = divSearchResults.style.width =
divIndexResults.style.width = divTree.style.width = pos;
if(!isIE)
pos -= 8;
divNavOpts.style.width = divSearchOpts.style.width =
divIndexOpts.style.width = pos;
// Resize the content div to fit in the remaining space
ResizeContent();
}
// Finish the drag operation when the mouse button is released
function OnMouseUp(event)
{
if(isIE)
{
document.detachEvent("onmousemove", OnMouseMove);
document.detachEvent("onmouseup", OnMouseUp);
}
else
{
document.removeEventListener("mousemove", OnMouseMove, true);
document.removeEventListener("mouseup", OnMouseUp, true);
}
// Show the content div again
topicContent.style.display = "inline";
}
//============================================================================
// Search code
function ShowHideSearch(show)
{
if(show)
{
divNavOpts.style.display = divTree.style.display = "none";
divSearchOpts.style.display = divSearchResults.style.display = "";
}
else
{
divSearchOpts.style.display = divSearchResults.style.display = "none";
divNavOpts.style.display = divTree.style.display = "";
}
}
// When enter is hit in the search text box, do the search
function OnSearchTextKeyPress(evt)
{
if(evt.keyCode == 13)
{
PerformSearch();
return false;
}
return true;
}
// Perform a keyword search
function PerformSearch()
{
var xmlHttp = GetXmlHttpRequest(), now = new Date();
if(xmlHttp == null)
{
divSearchResults.innerHTML = "<b>XML HTTP request not supported!</b>";
return;
}
divSearchResults.innerHTML = "<span class=\"PaddedText\">Searching...</span>";
// Add a unique hash to ensure it doesn't use cached results
xmlHttp.open("GET", "SearchHelp.aspx?Keywords=" + txtSearchText.value +
"&SortByTitle=" + (chkSortByTitle.checked ? "true" : "false") +
"&hash=" + now.getTime(), true);
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
divSearchResults.innerHTML = xmlHttp.responseText;
lastSearchNode = divSearchResults.childNodes[0].childNodes[1];
if(lastSearchNode != null)
{
if(lastSearchNode.tagName != "A")
lastSearchNode = lastSearchNode.nextSibling;
SelectSearchNode(lastSearchNode);
topicContent.src = lastSearchNode.href;
}
}
}
xmlHttp.send(null)
}
// Set the style of the specified search result node to "selected"
function SelectSearchNode(node)
{
if(lastSearchNode != null)
lastSearchNode.className = "UnselectedNode";
node.className = "SelectedNode";
lastSearchNode = node;
return true;
}
//============================================================================
// KeyWordIndex code
function ShowHideIndex(show)
{
if(show)
{
PopulateIndex(currentIndexPage);
divNavOpts.style.display = divTree.style.display = "none";
divIndexOpts.style.display = divIndexResults.style.display = "";
}
else
{
divIndexOpts.style.display = divIndexResults.style.display = "none";
divNavOpts.style.display = divTree.style.display = "";
}
}
// Populate keyword index
function PopulateIndex(startIndex)
{
var xmlHttp = GetXmlHttpRequest(), now = new Date();
var firstNode;
if(xmlHttp == null)
{
divIndexResults.innerHTML = "<b>XML HTTP request not supported!</b>";
return;
}
divIndexResults.innerHTML = "<span class=\"PaddedText\">Loading " +
"keyword index...</span>";
// Add a unique hash to ensure it doesn't use cached results
xmlHttp.open("GET", "LoadIndexKeywords.aspx?StartIndex=" + startIndex +
"&hash=" + now.getTime(), true);
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
divIndexResults.innerHTML = xmlHttp.responseText;
if(startIndex > 0)
{
firstNode = divIndexResults.childNodes[1];
if(firstNode != null && !firstNode.innerHTML)
firstNode = divIndexResults.childNodes[2];
}
else
firstNode = divIndexResults.childNodes[0];
if(firstNode != null)
lastIndexNode = firstNode.childNodes[0];
if(lastIndexNode != null)
{
if(lastIndexNode.tagName != "A")
lastIndexNode = lastIndexNode.nextSibling;
SelectIndexNode(lastIndexNode);
topicContent.src = lastIndexNode.href;
}
currentIndexPage = startIndex;
}
}
xmlHttp.send(null)
}
// Set the style of the specified keyword index node to "selected"
function SelectIndexNode(node)
{
if(lastIndexNode != null)
lastIndexNode.className = "UnselectedNode";
node.className = "SelectedNode";
lastIndexNode = node;
return true;
}
// Changes the current page with keyword index forward or backward
function ChangeIndexPage(direction)
{
PopulateIndex(currentIndexPage + direction);
return false;
}
| JavaScript |
//=============================================================================
// System : Color Syntax Highlighter
// File : Highlight.js
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 11/13/2007
// Note : Copyright 2006, Eric Woodruff, All rights reserved
//
// This contains the script to expand and collapse the regions in the
// syntax highlighted code.
//
//=============================================================================
// Expand/collapse a region
function HighlightExpandCollapse(showId, hideId)
{
var showSpan = document.getElementById(showId),
hideSpan = document.getElementById(hideId);
showSpan.style.display = "inline";
hideSpan.style.display = "none";
}
// Copy the code if Enter or Space is hit with the image focused
function CopyColorizedCodeCheckKey(titleDiv, eventObj)
{
if(eventObj != undefined && (eventObj.keyCode == 13 ||
eventObj.keyCode == 32))
CopyColorizedCode(titleDiv);
}
// Change the icon as the mouse moves in and out of the Copy Code link
// There should be an image with the same name but an "_h" suffix just
// before the extension.
function CopyCodeChangeIcon(linkSpan)
{
var image = linkSpan.firstChild.src;
var pos = image.lastIndexOf(".");
if(linkSpan.className == "highlight-copycode")
{
linkSpan.className = "highlight-copycode_h";
linkSpan.firstChild.src = image.substr(0, pos) + "_h" +
image.substr(pos);
}
else
{
linkSpan.className = "highlight-copycode";
linkSpan.firstChild.src = image.substr(0, pos - 2) + image.substr(pos);
}
}
// Copy the code from a colorized code block to the clipboard.
function CopyColorizedCode(titleDiv)
{
var preTag, idx, line, block, htmlLines, lines, codeText, hasLineNos,
hasRegions, clip, trans, copyObject, clipID;
var reLineNo = /^\s*\d{1,4}/;
var reRegion = /^\s*\d{1,4}\+.*?\d{1,4}-/;
var reRegionText = /^\+.*?\-/;
// Find the <pre> tag containing the code. It should be in the next
// element or one of its children.
block = titleDiv.nextSibling;
while(block.nodeName == "#text")
block = block.nextSibling;
while(block.tagName != "PRE")
{
block = block.firstChild;
while(block.nodeName == "#text")
block = block.nextSibling;
}
if(block.innerText != undefined)
codeText = block.innerText;
else
codeText = block.textContent;
hasLineNos = block.innerHTML.indexOf("highlight-lineno");
hasRegions = block.innerHTML.indexOf("highlight-collapsebox");
htmlLines = block.innerHTML.split("\n");
lines = codeText.split("\n");
// Remove the line numbering and collapsible regions if present
if(hasLineNos != -1 || hasRegions != -1)
{
codeText = "";
for(idx = 0; idx < lines.length; idx++)
{
line = lines[idx];
if(hasRegions && reRegion.test(line))
line = line.replace(reRegion, "");
else
{
line = line.replace(reLineNo, "");
// Lines in expanded blocks have an extra space
if(htmlLines[idx].indexOf("highlight-expanded") != -1 ||
htmlLines[idx].indexOf("highlight-endblock") != -1)
line = line.substr(1);
}
if(hasRegions && reRegionText.test(line))
line = line.replace(reRegionText, "");
codeText += line;
// Not all browsers keep the line feed when split
if(line[line.length - 1] != "\n")
codeText += "\n";
}
}
// IE or FireFox/Netscape?
if(window.clipboardData)
window.clipboardData.setData("Text", codeText);
else
if(window.netscape)
{
// Give unrestricted access to browser APIs using XPConnect
try
{
netscape.security.PrivilegeManager.enablePrivilege(
"UniversalXPConnect");
}
catch(e)
{
alert("Universal Connect was refused, cannot copy to " +
"clipboard. Go to about:config and set " +
"signed.applets.codebase_principal_support to true to " +
"enable clipboard support.");
return;
}
// Creates an instance of nsIClipboard
clip = Components.classes[
"@mozilla.org/widget/clipboard;1"].createInstance(
Components.interfaces.nsIClipboard);
// Creates an instance of nsITransferable
if(clip)
trans = Components.classes[
"@mozilla.org/widget/transferable;1"].createInstance(
Components.interfaces.nsITransferable);
if(!trans)
{
alert("Copy to Clipboard is not supported by this browser");
return;
}
// Register the data flavor
trans.addDataFlavor("text/unicode");
// Create object to hold the data
copyObject = new Object();
// Creates an instance of nsISupportsString
copyObject = Components.classes[
"@mozilla.org/supports-string;1"].createInstance(
Components.interfaces.nsISupportsString);
// Assign the data to be copied
copyObject.data = codeText;
// Add data objects to transferable
trans.setTransferData("text/unicode", copyObject,
codeText.length * 2);
clipID = Components.interfaces.nsIClipboard;
if(!clipID)
{
alert("Copy to Clipboard is not supported by this browser");
return;
}
// Transfer the data to the clipboard
clip.setData(trans, null, clipID.kGlobalClipboard);
}
else
alert("Copy to Clipboard is not supported by this browser");
}
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview User visible messages for bite.
* @author michaelwill@google.com (Michael Williamson)
*/
goog.provide('bite.client.messages');
/** @desc Tests option title. */
var MSG_POPUP_OPTION_TEST_NAME = goog.getMsg('Tests');
/** @desc Tests option info. */
var MSG_POPUP_OPTION_TEST_DESC = goog.getMsg('Find and run manual tests.');
/** @desc Bugs option title. */
var MSG_POPUP_OPTION_BUGS_NAME = goog.getMsg('Bugs');
/** @desc Bugs option info. */
var MSG_POPUP_OPTION_BUGS_DESC = goog.getMsg(
'Visualize existing bugs or file new ones.');
/** @desc Report Bug option title. */
var MSG_POPUP_OPTION_REPORT_BUG_NAME = goog.getMsg('Report Bug');
/** @desc Report Bug option info. */
var MSG_POPUP_OPTION_REPORT_BUG_DESC = goog.getMsg(
'File a bug against this page (Ctrl+Alt+B)');
/** @desc Close option title. */
var MSG_POPUP_OPTION_CLOSE_NAME = goog.getMsg('Close Consoles');
/** @desc Close option info. */
var MSG_POPUP_OPTION_CLOSE_DESC = goog.getMsg(
'Close all BITE consoles in all windows.');
/** @desc Record and playback option title. */
var MSG_POPUP_OPTION_FLUX_NAME = goog.getMsg('Record/Playback');
/** @desc Record and playback option info. */
var MSG_POPUP_OPTION_FLUX_DESC = goog.getMsg(
'Record and playback UI automation.');
/** @desc Xpath finder option title. */
var MSG_POPUP_OPTION_XPATH_NAME = goog.getMsg('Xpath Finder');
/** @desc Xpath finder option info. */
var MSG_POPUP_OPTION_XPATH_DESC = goog.getMsg(
'Help to get a custom Xpath.');
/** @desc Layers option title. */
var MSG_POPUP_OPTION_LAYERS_NAME = goog.getMsg('Layers');
/** @desc Layers option info. */
var MSG_POPUP_OPTION_LAYERS_DESC = goog.getMsg(
'Create or use custom tools and scripts.');
/** @desc Sets option title. */
var MSG_POPUP_OPTION_SETS_NAME = goog.getMsg('Sets');
/** @desc Sets option info. */
var MSG_POPUP_OPTION_SETS_DESC = goog.getMsg(
'Manage and analyze collections of tests.');
/** @desc Risk option title. */
var MSG_POPUP_OPTION_RISK_NAME = goog.getMsg('Risk');
/** @desc Risk option info. */
var MSG_POPUP_OPTION_RISK_DESC = goog.getMsg(
'Track risk and test analytics.');
/** @desc Admin option title. */
var MSG_POPUP_OPTION_ADMIN_NAME = goog.getMsg('Admin');
/** @desc Admin option info. */
var MSG_POPUP_OPTION_ADMIN_DESC = goog.getMsg(
'Manage projects, layers and security.');
/** @desc Help option title. */
var MSG_POPUP_OPTION_HELP_NAME = goog.getMsg('Help');
/** @desc Help option info. */
var MSG_POPUP_OPTION_HELP_DESC = goog.getMsg('Learn how to use RPF.');
/** @desc Settings option title. */
var MSG_POPUP_OPTION_SETTINGS_NAME = goog.getMsg('Settings');
/** @desc Settings option info. */
var MSG_POPUP_OPTION_SETTINGS_DESC = goog.getMsg('Configure BITE.');
/**
* @param {string} uri The url that will help the user in
* the event of an error.
* @return {string} The message.
*/
function CALL_MSG_POPUP_LOGIN_ERROR(uri) {
/** @desc A login error string. */
var MSG_POPUP_LOGIN_ERROR = goog.getMsg(
'There was a problem logging in.<br>' +
'<a href="{$uri}" target="_blank">Try logging in here</a>.',
{uri: uri});
return MSG_POPUP_LOGIN_ERROR;
}
| JavaScript |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Background script containing code to handle tasks
* invoked elsewhere in the extension code.
*
* @author alexto@google.com (Alexis O. Torres)
* @author phu@google.com (Po Hu)
*/
goog.provide('bite.client.Background');
goog.require('Bite.Constants');
goog.require('bite.LoginManager');
goog.require('goog.Timer');
goog.require('goog.Uri');
goog.require('goog.json');
goog.require('goog.userAgent');
goog.require('rpf.Constants');
goog.require('rpf.Rpf');
/**
* The Background Class is a singleton that manages all of BITE's background
* operations and data.
* @constructor
* @export
*/
bite.client.Background = function() {
/**
* @type {string}
* @private
*/
this.currentUser_ = '';
/**
* @type {bite.LoginManager}
* @private
*/
this.loginManager_ = bite.LoginManager.getInstance();
/**
* @type {rpf.Rpf}
* @private
*/
this.rpf_ = rpf.Rpf.getInstance();
// If this is the first time a user opens BITE, log an event.
var firstRun = (
goog.global.localStorage.getItem(bite.client.Background.PREVIOUS_USE_KEY)
!= 'true');
if (firstRun) {
// Analytics may not be loaded, so delay the logging until after the
// next batch of browser event processing.
goog.Timer.callOnce(goog.partial(bite.client.Background.logEvent,
'Background', 'FirstUse', ''), 0);
goog.global.localStorage.setItem(bite.client.Background.PREVIOUS_USE_KEY,
'true');
}
};
goog.addSingletonGetter(bite.client.Background);
/**
* Key used to keep track of first time use of BITE. The value of this key in
* localStorage will be set to 'true' once the application is loaded for the
* first time.
* @type {string}
*/
bite.client.Background.PREVIOUS_USE_KEY = 'bite-client-background-previous-use';
/**
* @return {rpf.Rpf} The RPF object.
* @export
*/
bite.client.Background.prototype.getRpfObj = function() {
return this.rpf_;
};
/**
* Sets a new RPF object.
* @param {rpf.Rpf} rpfObj The new RPF obj.
* @export
*/
bite.client.Background.prototype.setRpfObj = function(rpfObj) {
this.rpf_ = rpfObj;
};
/**
* Gets a value from localStorage, or 'null' if no value is stored.
* @param {string} key The localStorage key of the item.
* @param {function(?string)} callback The function to call with the value
* from localStorage.
* @private
*/
bite.client.Background.prototype.getLocalStorage_ = function(key, callback) {
var data = /** @type {?string} */ (goog.global.localStorage.getItem(key));
callback(data);
};
/**
* Sets a value in localStorage.
* @param {string} key The localStorage key to set.
* @param {string} value The value to set into localStorage.
* @param {function()} callback A function to callback.
* @private
*/
bite.client.Background.prototype.setLocalStorage_ =
function(key, value, callback) {
goog.global.localStorage.setItem(key, value);
callback();
};
/**
* Removes a value in localStorage.
* @param {string} key The localStorage key to remove.
* @param {function()} callback A function to callback.
* @private
*/
bite.client.Background.prototype.removeLocalStorage_ = function(key, callback) {
goog.global.localStorage.removeItem(key);
callback();
};
/**
* Logs an instrumentation event. NOTE(alexto): This method assumes that
* Google Analytics code is already loaded.
* @param {string} category Main of the main feture serving the event.
* @param {string} action Action that trigger the event.
* @param {string} label Additional information to log about the action.
* @export
*/
bite.client.Background.logEvent = function(category, action, label) {
var gaq = goog.global['_gaq'];
if (gaq) {
gaq.push(['_trackEvent', category, action, label]);
} else {
console.warn('Google Analytics is not ready.');
}
};
/**
* Handles request sent via chrome.extension.sendRequest().
* @param {!Object} request Object data sent in the request.
* @param {MessageSender} sender An object containing information about the
* script context that sent the request.
* @param {function(!*): void} callback Function to call when the request
* completes.
* @export
*/
bite.client.Background.prototype.onRequest =
function(request, sender, callback) {
// If the request contains a command or the request does not handle requests
// from the specified request's owner then do nothing (i.e. don't process
// this request).
if (request['command']) {
return;
}
switch (request['action']) {
case Bite.Constants.HUD_ACTION.GET_LOCAL_STORAGE:
this.getLocalStorage_(request['key'], callback);
break;
case Bite.Constants.HUD_ACTION.SET_LOCAL_STORAGE:
this.setLocalStorage_(request['key'], request['value'], callback);
break;
case Bite.Constants.HUD_ACTION.REMOVE_LOCAL_STORAGE:
this.removeLocalStorage_(request['key'], callback);
break;
case Bite.Constants.HUD_ACTION.LOG_EVENT:
bite.client.Background.logEvent(
request['category'], request['event_action'], request['label']);
break;
case Bite.Constants.HUD_ACTION.CREATE_RPF_WINDOW:
this.rpf_.setUserId(request['userId']);
this.rpf_.createWindow();
break;
case Bite.Constants.HUD_ACTION.CHANGE_RECORD_TAB:
this.rpf_.focusRpf();
break;
case Bite.Constants.HUD_ACTION.GET_CURRENT_USER:
var server = rpf.Constants.DEFAULT_SERVER;
this.loginManager_.getCurrentUser(callback, server);
break;
default:
throw new Error('The specified action is not valid: ' +
request['action']);
}
};
// Wire up the listener.
chrome.extension.onRequest.addListener(
goog.bind(bite.client.Background.getInstance().onRequest,
bite.client.Background.getInstance()));
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.