language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class UserService { constructor(client, utils) { this._user = client.userService(); this._utils = utils; } addLocalSetting(param, cb) { return new Promise((resolve, reject)=>{ this._user.addLocalSetting(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } addLocalSettingSync(param) { return this._user.addLocalSettingSync(param); } addOrDeleteApplication(param, cb) { return new Promise((resolve, reject)=>{ this._user.addOrDeleteApplication(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } addOrDeleteCustomEmoticon(param, cb) { return new Promise((resolve, reject)=>{ this._user.addOrDeleteCustomEmoticon(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } changeHiddenPasswd(param, cb) { return new Promise((resolve, reject)=>{ this._user.changeHiddenPasswd(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } circleOfFriend(param, cb) { return new Promise((resolve, reject)=>{ this._user.circleOfFriend(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } createAppRoom(param, cb) { return new Promise((resolve, reject)=>{ this._user.createAppRoom(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } deleteLocalSetting(param, cb) { return new Promise((resolve, reject)=>{ this._user.deleteLocalSetting(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } deleteLocalSettingSync(param) { return this._user.deleteLocalSettingSync(param); } delHiddenTarget(param, cb) { return new Promise((resolve, reject)=>{ this._user.delHiddenTarget(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } deleteDeviceLoginRecord(param, cb) { return new Promise((resolve, reject)=>{ this._user.deleteDeviceLoginRecord(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } transLocalData(param, cb) { return new Promise((resolve, reject)=>{ this._user.transLocalData(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } wakeUp(param, cb) { return new Promise((resolve, reject)=>{ this._user.wakeUp(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getAccountInfo(param, cb) { return new Promise((resolve, reject)=>{ this._user.getAccountInfo(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getAppInfo(param, cb) { return new Promise((resolve, reject)=>{ this._user.getAppInfo(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getGlobalNoDisturbMode(param, cb) { return new Promise((resolve, reject)=>{ this._user.getGlobalNoDisturbMode(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getHiddenTarget(param, cb) { return new Promise((resolve, reject)=>{ this._user.getHiddenTarget(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getIdByAccount(param, cb) { return new Promise((resolve, reject)=>{ this._user.getIdByAccount(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getEntAppInfo(param, cb) { return new Promise((resolve, reject)=>{ this._user.getEntAppInfo(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getInstalledApplication(param, cb) { return new Promise((resolve, reject)=>{ this._user.getInstalledApplication(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getInstalledApplicationSorted(param, cb) { return new Promise((resolve, reject)=>{ this._user.getInstalledApplicationSorted(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getLocalSetting(param, cb) { return new Promise((resolve, reject)=>{ this._user.getLocalSetting(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getLocalSettingSync(param) { return this._user.getLocalSettingSync(param); } getMsgNotifyMode(param, cb) { return new Promise((resolve, reject)=>{ this._user.getMsgNotifyMode(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getOauthCode(param, cb) { return new Promise((resolve, reject)=>{ this._user.getOauthCode(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getPersonalData(param, cb) { return new Promise((resolve, reject)=>{ this._user.getPersonalData(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getDeviceLoginRecord(param, cb) { return new Promise((resolve, reject)=>{ this._user.getDeviceLoginRecord(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getServerTime(param, cb) { return new Promise((resolve, reject)=>{ this._user.getServerTime(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getServerTimeSync(param) { return this._user.getServerTimeSync(param) } getSetting(param, cb) { return new Promise((resolve, reject)=>{ this._user.getSetting(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getUserDefineVoice(param, cb) { return new Promise((resolve, reject)=>{ this._user.getUserDefineVoice(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getUserNoDisturbMode(param, cb) { return new Promise((resolve, reject)=>{ this._user.getUserNoDisturbMode(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } getGlobalNoDisturbListMode(param, cb) { return new Promise((resolve, reject)=>{ this._user.getGlobalNoDisturbListMode(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } pageQueryEmoticon(param, cb) { return new Promise((resolve, reject)=>{ this._user.pageQueryEmoticon(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } queryEmoticon(param, cb) { return new Promise((resolve, reject)=>{ this._user.queryEmoticon(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } QueryEmoticonPackageByLabel(param, cb) { return new Promise((resolve, reject)=>{ this._user.QueryEmoticonPackageByLabel(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } queryEmotionInPackage(param, cb) { return new Promise((resolve, reject)=>{ this._user.queryEmotionInPackage(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } queryMarketApplication(param, cb) { return new Promise((resolve, reject)=>{ this._user.queryMarketApplication(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } singleQueryEmoticonPackage(param, cb) { return new Promise((resolve, reject)=>{ this._user.singleQueryEmoticonPackage(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } regCircleOfFriendNotifyCb(param, cb) { this._user.regCircleOfFriendNotifyCb(param, resp => { this._utils.makeCallBack(resp, cb); }); } regGetMyselfCb(param, cb) { this._user.regGetMyselfCb(param, resp => { this._utils.makeCallBack(resp, cb); }); } regOperateUserCb(param, cb) { this._user.regOperateUserCb(param, resp => { this._utils.makeCallBack(resp, cb); }); } regUpdateFinished(param, cb) { this._user.regUpdateFinished(param, resp => { this._utils.makeCallBack(resp, cb); }); } regUserHeadImgUpdateCb(param, cb) { this._user.regUserHeadImgUpdateCb(param, resp => { this._utils.makeCallBack(resp, cb); }); } setAppOrder(param, cb) { return new Promise((resolve, reject)=>{ this._user.setAppOrder(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } setGolbalNoDisturbMode(param, cb) { return new Promise((resolve, reject)=>{ this._user.setGolbalNoDisturbMode(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } setGolbalNoDisturbListMode(param, cb) { return new Promise((resolve, reject)=>{ this._user.setGolbalNoDisturbListMode(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } setHiddenTarget(param, cb) { return new Promise((resolve, reject)=>{ this._user.setHiddenTarget(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } setMsgNotifyMode(param, cb) { return new Promise((resolve, reject)=>{ this._user.setMsgNotifyMode(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } setOnlineState(param, cb) { return new Promise((resolve, reject)=>{ this._user.setOnlineState(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } setPersonalData(param, cb) { return new Promise((resolve, reject)=>{ this._user.setPersonalData(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } setSetting(param, cb) { return new Promise((resolve, reject)=>{ this._user.setSetting(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } setUserDefineVoice(param, cb) { return new Promise((resolve, reject)=>{ this._user.setUserDefineVoice(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } setUserNoDisturbMode(param, cb) { return new Promise((resolve, reject)=>{ this._user.setUserNoDisturbMode(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } updateAccountInfo(param, cb) { return new Promise((resolve, reject)=>{ this._user.updateAccountInfo(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } updateAppRoomInfo(param, cb) { return new Promise((resolve, reject)=>{ this._user.updateAppRoomInfo(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } updateAppRoomMem(param, cb) { return new Promise((resolve, reject)=>{ this._user.updateAppRoomMem(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } updateExtendInfo(param, cb) { return new Promise((resolve, reject)=>{ this._user.updateExtendInfo(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } updateLocalSetting(param, cb) { return new Promise((resolve, reject)=>{ this._user.updateLocalSetting(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }); } }
JavaScript
class RpWorkPreview extends Mixin(LitElement) .with(LitCorkUtils) { static get properties() { return { data: {type: Object}, showSnippet: {type: Boolean, attribute: 'show-snippet'}, authorCt: {type: Number}, snippet : {type: String}, title : {type: String}, textWidth: {type: String, attribute: 'text-width'}, }; } constructor() { super(); this.data = {}; this.authorCt = 0; this.showSnippet = false; this.textWidth = (window.innerWidth.toString() - 70) + "px"; this._injectModel('WorkModel'); this.render = render.bind(this); } /** * @method updated * @description lit-element updated method * * @param {Object} props */ updated(props) { if( props.has('data') ) { let result = previewUtils.getSnippetTitle( this.WorkModel.getLabel(this.data), this.WorkModel.getSnippet(this.data) ); this.title = result.title; if( result.showSnippet === false ) { this.showSnippet = false; } } } getTitle(){ return this.WorkModel.getLabel(this.data); } getLink(){ return this.WorkModel.getLandingPage(this.data); } getAuthors(){ let authors = this.WorkModel.getAuthors(this.data); this.authorCt = authors.ranked.length; return authors.ranked; } getWorkType(){ return this.WorkModel.getWorkType(this.data); } getSnippet(){ return this.WorkModel.getSnippet(this.data); } }
JavaScript
class b2Vec2 { constructor(x = 0, y = 0) { this.x = x; this.y = y; } Clone() { return new b2Vec2(this.x, this.y); } SetZero() { this.x = 0; this.y = 0; return this; } Set(x, y) { this.x = x; this.y = y; return this; } Copy(other) { this.x = other.x; this.y = other.y; return this; } SelfAdd(v) { this.x += v.x; this.y += v.y; return this; } SelfAddXY(x, y) { this.x += x; this.y += y; return this; } SelfSub(v) { this.x -= v.x; this.y -= v.y; return this; } SelfSubXY(x, y) { this.x -= x; this.y -= y; return this; } SelfMul(s) { this.x *= s; this.y *= s; return this; } SelfMulAdd(s, v) { this.x += s * v.x; this.y += s * v.y; return this; } SelfMulSub(s, v) { this.x -= s * v.x; this.y -= s * v.y; return this; } Dot(v) { return this.x * v.x + this.y * v.y; } Cross(v) { return this.x * v.y - this.y * v.x; } Length() { const x = this.x, y = this.y; return Math.sqrt(x * x + y * y); } LengthSquared() { const x = this.x, y = this.y; return (x * x + y * y); } Normalize() { const length = this.Length(); if (length >= b2_epsilon) { const inv_length = 1 / length; this.x *= inv_length; this.y *= inv_length; } return length; } SelfNormalize() { const length = this.Length(); if (length >= b2_epsilon) { const inv_length = 1 / length; this.x *= inv_length; this.y *= inv_length; } return this; } SelfRotate(radians) { const c = Math.cos(radians); const s = Math.sin(radians); const x = this.x; this.x = c * x - s * this.y; this.y = s * x + c * this.y; return this; } SelfRotateCosSin(c, s) { const x = this.x; this.x = c * x - s * this.y; this.y = s * x + c * this.y; return this; } IsValid() { return isFinite(this.x) && isFinite(this.y); } SelfCrossVS(s) { const x = this.x; this.x = s * this.y; this.y = -s * x; return this; } SelfCrossSV(s) { const x = this.x; this.x = -s * this.y; this.y = s * x; return this; } SelfMinV(v) { this.x = b2Min(this.x, v.x); this.y = b2Min(this.y, v.y); return this; } SelfMaxV(v) { this.x = b2Max(this.x, v.x); this.y = b2Max(this.y, v.y); return this; } SelfAbs() { this.x = b2Abs(this.x); this.y = b2Abs(this.y); return this; } SelfNeg() { this.x = (-this.x); this.y = (-this.y); return this; } SelfSkew() { const x = this.x; this.x = -this.y; this.y = x; return this; } static MakeArray(length) { return b2MakeArray(length, (i) => new b2Vec2()); } static AbsV(v, out) { out.x = b2Abs(v.x); out.y = b2Abs(v.y); return out; } static MinV(a, b, out) { out.x = b2Min(a.x, b.x); out.y = b2Min(a.y, b.y); return out; } static MaxV(a, b, out) { out.x = b2Max(a.x, b.x); out.y = b2Max(a.y, b.y); return out; } static ClampV(v, lo, hi, out) { out.x = b2Clamp(v.x, lo.x, hi.x); out.y = b2Clamp(v.y, lo.y, hi.y); return out; } static RotateV(v, radians, out) { const v_x = v.x, v_y = v.y; const c = Math.cos(radians); const s = Math.sin(radians); out.x = c * v_x - s * v_y; out.y = s * v_x + c * v_y; return out; } static DotVV(a, b) { return a.x * b.x + a.y * b.y; } static CrossVV(a, b) { return a.x * b.y - a.y * b.x; } static CrossVS(v, s, out) { const v_x = v.x; out.x = s * v.y; out.y = -s * v_x; return out; } static CrossVOne(v, out) { const v_x = v.x; out.x = v.y; out.y = -v_x; return out; } static CrossSV(s, v, out) { const v_x = v.x; out.x = -s * v.y; out.y = s * v_x; return out; } static CrossOneV(v, out) { const v_x = v.x; out.x = -v.y; out.y = v_x; return out; } static AddVV(a, b, out) { out.x = a.x + b.x; out.y = a.y + b.y; return out; } static SubVV(a, b, out) { out.x = a.x - b.x; out.y = a.y - b.y; return out; } static MulSV(s, v, out) { out.x = v.x * s; out.y = v.y * s; return out; } static MulVS(v, s, out) { out.x = v.x * s; out.y = v.y * s; return out; } static AddVMulSV(a, s, b, out) { out.x = a.x + (s * b.x); out.y = a.y + (s * b.y); return out; } static SubVMulSV(a, s, b, out) { out.x = a.x - (s * b.x); out.y = a.y - (s * b.y); return out; } static AddVCrossSV(a, s, v, out) { const v_x = v.x; out.x = a.x - (s * v.y); out.y = a.y + (s * v_x); return out; } static MidVV(a, b, out) { out.x = (a.x + b.x) * 0.5; out.y = (a.y + b.y) * 0.5; return out; } static ExtVV(a, b, out) { out.x = (b.x - a.x) * 0.5; out.y = (b.y - a.y) * 0.5; return out; } static IsEqualToV(a, b) { return a.x === b.x && a.y === b.y; } static DistanceVV(a, b) { const c_x = a.x - b.x; const c_y = a.y - b.y; return Math.sqrt(c_x * c_x + c_y * c_y); } static DistanceSquaredVV(a, b) { const c_x = a.x - b.x; const c_y = a.y - b.y; return (c_x * c_x + c_y * c_y); } static NegV(v, out) { out.x = -v.x; out.y = -v.y; return out; } }
JavaScript
class b2Vec3 { constructor(x = 0, y = 0, z = 0) { this.x = x; this.y = y; this.z = z; } Clone() { return new b2Vec3(this.x, this.y, this.z); } SetZero() { this.x = 0; this.y = 0; this.z = 0; return this; } SetXYZ(x, y, z) { this.x = x; this.y = y; this.z = z; return this; } Copy(other) { this.x = other.x; this.y = other.y; this.z = other.z; return this; } SelfNeg() { this.x = (-this.x); this.y = (-this.y); this.z = (-this.z); return this; } SelfAdd(v) { this.x += v.x; this.y += v.y; this.z += v.z; return this; } SelfAddXYZ(x, y, z) { this.x += x; this.y += y; this.z += z; return this; } SelfSub(v) { this.x -= v.x; this.y -= v.y; this.z -= v.z; return this; } SelfSubXYZ(x, y, z) { this.x -= x; this.y -= y; this.z -= z; return this; } SelfMul(s) { this.x *= s; this.y *= s; this.z *= s; return this; } static DotV3V3(a, b) { return a.x * b.x + a.y * b.y + a.z * b.z; } static CrossV3V3(a, b, out) { const a_x = a.x, a_y = a.y, a_z = a.z; const b_x = b.x, b_y = b.y, b_z = b.z; out.x = a_y * b_z - a_z * b_y; out.y = a_z * b_x - a_x * b_z; out.z = a_x * b_y - a_y * b_x; return out; } }
JavaScript
class b2Mat22 { constructor() { this.ex = new b2Vec2(1, 0); this.ey = new b2Vec2(0, 1); } Clone() { return new b2Mat22().Copy(this); } static FromVV(c1, c2) { return new b2Mat22().SetVV(c1, c2); } static FromSSSS(r1c1, r1c2, r2c1, r2c2) { return new b2Mat22().SetSSSS(r1c1, r1c2, r2c1, r2c2); } static FromAngle(radians) { return new b2Mat22().SetAngle(radians); } SetSSSS(r1c1, r1c2, r2c1, r2c2) { this.ex.Set(r1c1, r2c1); this.ey.Set(r1c2, r2c2); return this; } SetVV(c1, c2) { this.ex.Copy(c1); this.ey.Copy(c2); return this; } SetAngle(radians) { const c = Math.cos(radians); const s = Math.sin(radians); this.ex.Set(c, s); this.ey.Set(-s, c); return this; } Copy(other) { this.ex.Copy(other.ex); this.ey.Copy(other.ey); return this; } SetIdentity() { this.ex.Set(1, 0); this.ey.Set(0, 1); return this; } SetZero() { this.ex.SetZero(); this.ey.SetZero(); return this; } GetAngle() { return Math.atan2(this.ex.y, this.ex.x); } GetInverse(out) { const a = this.ex.x; const b = this.ey.x; const c = this.ex.y; const d = this.ey.y; let det = a * d - b * c; if (det !== 0) { det = 1 / det; } out.ex.x = det * d; out.ey.x = (-det * b); out.ex.y = (-det * c); out.ey.y = det * a; return out; } Solve(b_x, b_y, out) { const a11 = this.ex.x, a12 = this.ey.x; const a21 = this.ex.y, a22 = this.ey.y; let det = a11 * a22 - a12 * a21; if (det !== 0) { det = 1 / det; } out.x = det * (a22 * b_x - a12 * b_y); out.y = det * (a11 * b_y - a21 * b_x); return out; } SelfAbs() { this.ex.SelfAbs(); this.ey.SelfAbs(); return this; } SelfInv() { this.GetInverse(this); return this; } SelfAddM(M) { this.ex.SelfAdd(M.ex); this.ey.SelfAdd(M.ey); return this; } SelfSubM(M) { this.ex.SelfSub(M.ex); this.ey.SelfSub(M.ey); return this; } static AbsM(M, out) { const M_ex = M.ex, M_ey = M.ey; out.ex.x = b2Abs(M_ex.x); out.ex.y = b2Abs(M_ex.y); out.ey.x = b2Abs(M_ey.x); out.ey.y = b2Abs(M_ey.y); return out; } static MulMV(M, v, out) { const M_ex = M.ex, M_ey = M.ey; const v_x = v.x, v_y = v.y; out.x = M_ex.x * v_x + M_ey.x * v_y; out.y = M_ex.y * v_x + M_ey.y * v_y; return out; } static MulTMV(M, v, out) { const M_ex = M.ex, M_ey = M.ey; const v_x = v.x, v_y = v.y; out.x = M_ex.x * v_x + M_ex.y * v_y; out.y = M_ey.x * v_x + M_ey.y * v_y; return out; } static AddMM(A, B, out) { const A_ex = A.ex, A_ey = A.ey; const B_ex = B.ex, B_ey = B.ey; out.ex.x = A_ex.x + B_ex.x; out.ex.y = A_ex.y + B_ex.y; out.ey.x = A_ey.x + B_ey.x; out.ey.y = A_ey.y + B_ey.y; return out; } static MulMM(A, B, out) { const A_ex_x = A.ex.x, A_ex_y = A.ex.y; const A_ey_x = A.ey.x, A_ey_y = A.ey.y; const B_ex_x = B.ex.x, B_ex_y = B.ex.y; const B_ey_x = B.ey.x, B_ey_y = B.ey.y; out.ex.x = A_ex_x * B_ex_x + A_ey_x * B_ex_y; out.ex.y = A_ex_y * B_ex_x + A_ey_y * B_ex_y; out.ey.x = A_ex_x * B_ey_x + A_ey_x * B_ey_y; out.ey.y = A_ex_y * B_ey_x + A_ey_y * B_ey_y; return out; } static MulTMM(A, B, out) { const A_ex_x = A.ex.x, A_ex_y = A.ex.y; const A_ey_x = A.ey.x, A_ey_y = A.ey.y; const B_ex_x = B.ex.x, B_ex_y = B.ex.y; const B_ey_x = B.ey.x, B_ey_y = B.ey.y; out.ex.x = A_ex_x * B_ex_x + A_ex_y * B_ex_y; out.ex.y = A_ey_x * B_ex_x + A_ey_y * B_ex_y; out.ey.x = A_ex_x * B_ey_x + A_ex_y * B_ey_y; out.ey.y = A_ey_x * B_ey_x + A_ey_y * B_ey_y; return out; } }
JavaScript
class b2Mat33 { constructor() { this.ex = new b2Vec3(1, 0, 0); this.ey = new b2Vec3(0, 1, 0); this.ez = new b2Vec3(0, 0, 1); } Clone() { return new b2Mat33().Copy(this); } SetVVV(c1, c2, c3) { this.ex.Copy(c1); this.ey.Copy(c2); this.ez.Copy(c3); return this; } Copy(other) { this.ex.Copy(other.ex); this.ey.Copy(other.ey); this.ez.Copy(other.ez); return this; } SetIdentity() { this.ex.SetXYZ(1, 0, 0); this.ey.SetXYZ(0, 1, 0); this.ez.SetXYZ(0, 0, 1); return this; } SetZero() { this.ex.SetZero(); this.ey.SetZero(); this.ez.SetZero(); return this; } SelfAddM(M) { this.ex.SelfAdd(M.ex); this.ey.SelfAdd(M.ey); this.ez.SelfAdd(M.ez); return this; } Solve33(b_x, b_y, b_z, out) { const a11 = this.ex.x, a21 = this.ex.y, a31 = this.ex.z; const a12 = this.ey.x, a22 = this.ey.y, a32 = this.ey.z; const a13 = this.ez.x, a23 = this.ez.y, a33 = this.ez.z; let det = a11 * (a22 * a33 - a32 * a23) + a21 * (a32 * a13 - a12 * a33) + a31 * (a12 * a23 - a22 * a13); if (det !== 0) { det = 1 / det; } out.x = det * (b_x * (a22 * a33 - a32 * a23) + b_y * (a32 * a13 - a12 * a33) + b_z * (a12 * a23 - a22 * a13)); out.y = det * (a11 * (b_y * a33 - b_z * a23) + a21 * (b_z * a13 - b_x * a33) + a31 * (b_x * a23 - b_y * a13)); out.z = det * (a11 * (a22 * b_z - a32 * b_y) + a21 * (a32 * b_x - a12 * b_z) + a31 * (a12 * b_y - a22 * b_x)); return out; } Solve22(b_x, b_y, out) { const a11 = this.ex.x, a12 = this.ey.x; const a21 = this.ex.y, a22 = this.ey.y; let det = a11 * a22 - a12 * a21; if (det !== 0) { det = 1 / det; } out.x = det * (a22 * b_x - a12 * b_y); out.y = det * (a11 * b_y - a21 * b_x); return out; } GetInverse22(M) { const a = this.ex.x, b = this.ey.x, c = this.ex.y, d = this.ey.y; let det = a * d - b * c; if (det !== 0) { det = 1 / det; } M.ex.x = det * d; M.ey.x = -det * b; M.ex.z = 0; M.ex.y = -det * c; M.ey.y = det * a; M.ey.z = 0; M.ez.x = 0; M.ez.y = 0; M.ez.z = 0; } GetSymInverse33(M) { let det = b2Vec3.DotV3V3(this.ex, b2Vec3.CrossV3V3(this.ey, this.ez, b2Vec3.s_t0)); if (det !== 0) { det = 1 / det; } const a11 = this.ex.x, a12 = this.ey.x, a13 = this.ez.x; const a22 = this.ey.y, a23 = this.ez.y; const a33 = this.ez.z; M.ex.x = det * (a22 * a33 - a23 * a23); M.ex.y = det * (a13 * a23 - a12 * a33); M.ex.z = det * (a12 * a23 - a13 * a22); M.ey.x = M.ex.y; M.ey.y = det * (a11 * a33 - a13 * a13); M.ey.z = det * (a13 * a12 - a11 * a23); M.ez.x = M.ex.z; M.ez.y = M.ey.z; M.ez.z = det * (a11 * a22 - a12 * a12); } static MulM33V3(A, v, out) { const v_x = v.x, v_y = v.y, v_z = v.z; out.x = A.ex.x * v_x + A.ey.x * v_y + A.ez.x * v_z; out.y = A.ex.y * v_x + A.ey.y * v_y + A.ez.y * v_z; out.z = A.ex.z * v_x + A.ey.z * v_y + A.ez.z * v_z; return out; } static MulM33XYZ(A, x, y, z, out) { out.x = A.ex.x * x + A.ey.x * y + A.ez.x * z; out.y = A.ex.y * x + A.ey.y * y + A.ez.y * z; out.z = A.ex.z * x + A.ey.z * y + A.ez.z * z; return out; } static MulM33V2(A, v, out) { const v_x = v.x, v_y = v.y; out.x = A.ex.x * v_x + A.ey.x * v_y; out.y = A.ex.y * v_x + A.ey.y * v_y; return out; } static MulM33XY(A, x, y, out) { out.x = A.ex.x * x + A.ey.x * y; out.y = A.ex.y * x + A.ey.y * y; return out; } }
JavaScript
class b2Transform { constructor() { this.p = new b2Vec2(); this.q = new b2Rot(); } Clone() { return new b2Transform().Copy(this); } Copy(other) { this.p.Copy(other.p); this.q.Copy(other.q); return this; } SetIdentity() { this.p.SetZero(); this.q.SetIdentity(); return this; } SetPositionRotation(position, q) { this.p.Copy(position); this.q.Copy(q); return this; } SetPositionAngle(pos, a) { this.p.Copy(pos); this.q.SetAngle(a); return this; } SetPosition(position) { this.p.Copy(position); return this; } SetPositionXY(x, y) { this.p.Set(x, y); return this; } SetRotation(rotation) { this.q.Copy(rotation); return this; } SetRotationAngle(radians) { this.q.SetAngle(radians); return this; } GetPosition() { return this.p; } GetRotation() { return this.q; } GetRotationAngle() { return this.q.GetAngle(); } GetAngle() { return this.q.GetAngle(); } static MulXV(T, v, out) { // float32 x = (T.q.c * v.x - T.q.s * v.y) + T.p.x; // float32 y = (T.q.s * v.x + T.q.c * v.y) + T.p.y; // return b2Vec2(x, y); const T_q_c = T.q.c, T_q_s = T.q.s; const v_x = v.x, v_y = v.y; out.x = (T_q_c * v_x - T_q_s * v_y) + T.p.x; out.y = (T_q_s * v_x + T_q_c * v_y) + T.p.y; return out; } static MulTXV(T, v, out) { // float32 px = v.x - T.p.x; // float32 py = v.y - T.p.y; // float32 x = (T.q.c * px + T.q.s * py); // float32 y = (-T.q.s * px + T.q.c * py); // return b2Vec2(x, y); const T_q_c = T.q.c, T_q_s = T.q.s; const p_x = v.x - T.p.x; const p_y = v.y - T.p.y; out.x = (T_q_c * p_x + T_q_s * p_y); out.y = (-T_q_s * p_x + T_q_c * p_y); return out; } static MulXX(A, B, out) { b2Rot.MulRR(A.q, B.q, out.q); b2Vec2.AddVV(b2Rot.MulRV(A.q, B.p, out.p), A.p, out.p); return out; } static MulTXX(A, B, out) { b2Rot.MulTRR(A.q, B.q, out.q); b2Rot.MulTRV(A.q, b2Vec2.SubVV(B.p, A.p, out.p), out.p); return out; } }
JavaScript
class b2Sweep { constructor() { this.localCenter = new b2Vec2(); this.c0 = new b2Vec2(); this.c = new b2Vec2(); this.a0 = 0; this.a = 0; this.alpha0 = 0; } Clone() { return new b2Sweep().Copy(this); } Copy(other) { this.localCenter.Copy(other.localCenter); this.c0.Copy(other.c0); this.c.Copy(other.c); this.a0 = other.a0; this.a = other.a; this.alpha0 = other.alpha0; return this; } GetTransform(xf, beta) { const one_minus_beta = (1 - beta); xf.p.x = one_minus_beta * this.c0.x + beta * this.c.x; xf.p.y = one_minus_beta * this.c0.y + beta * this.c.y; const angle = one_minus_beta * this.a0 + beta * this.a; xf.q.SetAngle(angle); xf.p.SelfSub(b2Rot.MulRV(xf.q, this.localCenter, b2Vec2.s_t0)); return xf; } Advance(alpha) { // DEBUG: b2Assert(this.alpha0 < 1); const beta = (alpha - this.alpha0) / (1 - this.alpha0); const one_minus_beta = (1 - beta); this.c0.x = one_minus_beta * this.c0.x + beta * this.c.x; this.c0.y = one_minus_beta * this.c0.y + beta * this.c.y; this.a0 = one_minus_beta * this.a0 + beta * this.a; this.alpha0 = alpha; } Normalize() { const d = b2_two_pi * Math.floor(this.a0 / b2_two_pi); this.a0 -= d; this.a -= d; } }
JavaScript
class b2Color { constructor(rr = 0.5, gg = 0.5, bb = 0.5, aa = 1.0) { this.r = rr; this.g = gg; this.b = bb; this.a = aa; } Clone() { return new b2Color().Copy(this); } Copy(other) { this.r = other.r; this.g = other.g; this.b = other.b; this.a = other.a; return this; } IsEqual(color) { return (this.r === color.r) && (this.g === color.g) && (this.b === color.b) && (this.a === color.a); } IsZero() { return (this.r === 0) && (this.g === 0) && (this.b === 0) && (this.a === 0); } Set(r, g, b, a = this.a) { this.SetRGBA(r, g, b, a); } SetByteRGB(r, g, b) { this.r = r / 0xff; this.g = g / 0xff; this.b = b / 0xff; return this; } SetByteRGBA(r, g, b, a) { this.r = r / 0xff; this.g = g / 0xff; this.b = b / 0xff; this.a = a / 0xff; return this; } SetRGB(rr, gg, bb) { this.r = rr; this.g = gg; this.b = bb; return this; } SetRGBA(rr, gg, bb, aa) { this.r = rr; this.g = gg; this.b = bb; this.a = aa; return this; } SelfAdd(color) { this.r += color.r; this.g += color.g; this.b += color.b; this.a += color.a; return this; } Add(color, out) { out.r = this.r + color.r; out.g = this.g + color.g; out.b = this.b + color.b; out.a = this.a + color.a; return out; } SelfSub(color) { this.r -= color.r; this.g -= color.g; this.b -= color.b; this.a -= color.a; return this; } Sub(color, out) { out.r = this.r - color.r; out.g = this.g - color.g; out.b = this.b - color.b; out.a = this.a - color.a; return out; } SelfMul(s) { this.r *= s; this.g *= s; this.b *= s; this.a *= s; return this; } Mul(s, out) { out.r = this.r * s; out.g = this.g * s; out.b = this.b * s; out.a = this.a * s; return out; } Mix(mixColor, strength) { b2Color.MixColors(this, mixColor, strength); } static MixColors(colorA, colorB, strength) { const dr = (strength * (colorB.r - colorA.r)); const dg = (strength * (colorB.g - colorA.g)); const db = (strength * (colorB.b - colorA.b)); const da = (strength * (colorB.a - colorA.a)); colorA.r += dr; colorA.g += dg; colorA.b += db; colorA.a += da; colorB.r -= dr; colorB.g -= dg; colorB.b -= db; colorB.a -= da; } MakeStyleString(alpha = this.a) { return b2Color.MakeStyleString(this.r, this.g, this.b, alpha); } static MakeStyleString(r, g, b, a = 1.0) { // function clamp(x: number, lo: number, hi: number) { return x < lo ? lo : hi < x ? hi : x; } r *= 255; // r = clamp(r, 0, 255); g *= 255; // g = clamp(g, 0, 255); b *= 255; // b = clamp(b, 0, 255); // a = clamp(a, 0, 1); if (a < 1) { return `rgba(${r},${g},${b},${a})`; } else { return `rgb(${r},${g},${b})`; } } }
JavaScript
class b2Timer { constructor() { this.m_start = Date.now(); } /// Reset the timer. Reset() { this.m_start = Date.now(); return this; } /// Get the time since construction or the last reset. GetMilliseconds() { return Date.now() - this.m_start; } }
JavaScript
class b2GrowableStack { constructor(N) { this.m_stack = []; this.m_count = 0; this.m_stack = b2MakeArray(N, (index) => null); this.m_count = 0; } Reset() { this.m_count = 0; return this; } Push(element) { this.m_stack[this.m_count] = element; this.m_count++; } Pop() { // DEBUG: b2Assert(this.m_count > 0); this.m_count--; const element = this.m_stack[this.m_count]; this.m_stack[this.m_count] = null; if (element === null) { throw new Error(); } return element; } GetCount() { return this.m_count; } }
JavaScript
class b2DistanceProxy { constructor() { this.m_buffer = b2Vec2.MakeArray(2); this.m_vertices = this.m_buffer; this.m_count = 0; this.m_radius = 0; } Copy(other) { if (other.m_vertices === other.m_buffer) { this.m_vertices = this.m_buffer; this.m_buffer[0].Copy(other.m_buffer[0]); this.m_buffer[1].Copy(other.m_buffer[1]); } else { this.m_vertices = other.m_vertices; } this.m_count = other.m_count; this.m_radius = other.m_radius; return this; } Reset() { this.m_vertices = this.m_buffer; this.m_count = 0; this.m_radius = 0; return this; } SetShape(shape, index) { shape.SetupDistanceProxy(this, index); } SetVerticesRadius(vertices, count, radius) { this.m_vertices = vertices; this.m_count = count; this.m_radius = radius; } GetSupport(d) { let bestIndex = 0; let bestValue = b2Vec2.DotVV(this.m_vertices[0], d); for (let i = 1; i < this.m_count; ++i) { const value = b2Vec2.DotVV(this.m_vertices[i], d); if (value > bestValue) { bestIndex = i; bestValue = value; } } return bestIndex; } GetSupportVertex(d) { let bestIndex = 0; let bestValue = b2Vec2.DotVV(this.m_vertices[0], d); for (let i = 1; i < this.m_count; ++i) { const value = b2Vec2.DotVV(this.m_vertices[i], d); if (value > bestValue) { bestIndex = i; bestValue = value; } } return this.m_vertices[bestIndex]; } GetVertexCount() { return this.m_count; } GetVertex(index) { // DEBUG: b2Assert(0 <= index && index < this.m_count); return this.m_vertices[index]; } }
JavaScript
class b2ContactFeature { constructor() { this._key = 0; this._key_invalid = false; this._indexA = 0; this._indexB = 0; this._typeA = 0; this._typeB = 0; } get key() { if (this._key_invalid) { this._key_invalid = false; this._key = this._indexA | (this._indexB << 8) | (this._typeA << 16) | (this._typeB << 24); } return this._key; } set key(value) { this._key = value; this._key_invalid = false; this._indexA = this._key & 0xff; this._indexB = (this._key >> 8) & 0xff; this._typeA = (this._key >> 16) & 0xff; this._typeB = (this._key >> 24) & 0xff; } get indexA() { return this._indexA; } set indexA(value) { this._indexA = value; this._key_invalid = true; } get indexB() { return this._indexB; } set indexB(value) { this._indexB = value; this._key_invalid = true; } get typeA() { return this._typeA; } set typeA(value) { this._typeA = value; this._key_invalid = true; } get typeB() { return this._typeB; } set typeB(value) { this._typeB = value; this._key_invalid = true; } }
JavaScript
class b2ContactID { constructor() { this.cf = new b2ContactFeature(); } Copy(o) { this.key = o.key; return this; } Clone() { return new b2ContactID().Copy(this); } get key() { return this.cf.key; } set key(value) { this.cf.key = value; } }
JavaScript
class b2ManifoldPoint { constructor() { this.localPoint = new b2Vec2(); ///< usage depends on manifold type this.normalImpulse = 0; ///< the non-penetration impulse this.tangentImpulse = 0; ///< the friction impulse this.id = new b2ContactID(); // TODO: readonly ///< uniquely identifies a contact point between two shapes } static MakeArray(length) { return b2MakeArray(length, (i) => new b2ManifoldPoint()); } Reset() { this.localPoint.SetZero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.id.key = 0; } Copy(o) { this.localPoint.Copy(o.localPoint); this.normalImpulse = o.normalImpulse; this.tangentImpulse = o.tangentImpulse; this.id.Copy(o.id); return this; } }
JavaScript
class b2Manifold { constructor() { this.points = b2ManifoldPoint.MakeArray(b2_maxManifoldPoints); this.localNormal = new b2Vec2(); this.localPoint = new b2Vec2(); this.type = b2ManifoldType.e_unknown; this.pointCount = 0; } Reset() { for (let i = 0; i < b2_maxManifoldPoints; ++i) { // DEBUG: b2Assert(this.points[i] instanceof b2ManifoldPoint); this.points[i].Reset(); } this.localNormal.SetZero(); this.localPoint.SetZero(); this.type = b2ManifoldType.e_unknown; this.pointCount = 0; } Copy(o) { this.pointCount = o.pointCount; for (let i = 0; i < b2_maxManifoldPoints; ++i) { // DEBUG: b2Assert(this.points[i] instanceof b2ManifoldPoint); this.points[i].Copy(o.points[i]); } this.localNormal.Copy(o.localNormal); this.localPoint.Copy(o.localPoint); this.type = o.type; return this; } Clone() { return new b2Manifold().Copy(this); } }
JavaScript
class b2ClipVertex { constructor() { this.v = new b2Vec2(); this.id = new b2ContactID(); } static MakeArray(length) { return b2MakeArray(length, (i) => new b2ClipVertex()); } Copy(other) { this.v.Copy(other.v); this.id.Copy(other.id); return this; } }
JavaScript
class b2RayCastInput { constructor() { this.p1 = new b2Vec2(); this.p2 = new b2Vec2(); this.maxFraction = 1; } Copy(o) { this.p1.Copy(o.p1); this.p2.Copy(o.p2); this.maxFraction = o.maxFraction; return this; } }
JavaScript
class b2AABB { constructor() { this.lowerBound = new b2Vec2(); ///< the lower vertex this.upperBound = new b2Vec2(); ///< the upper vertex this.m_cache_center = new b2Vec2(); // access using GetCenter() this.m_cache_extent = new b2Vec2(); // access using GetExtents() } Copy(o) { this.lowerBound.Copy(o.lowerBound); this.upperBound.Copy(o.upperBound); return this; } /// Verify that the bounds are sorted. IsValid() { const d_x = this.upperBound.x - this.lowerBound.x; const d_y = this.upperBound.y - this.lowerBound.y; let valid = d_x >= 0 && d_y >= 0; valid = valid && this.lowerBound.IsValid() && this.upperBound.IsValid(); return valid; } /// Get the center of the AABB. GetCenter() { return b2Vec2.MidVV(this.lowerBound, this.upperBound, this.m_cache_center); } /// Get the extents of the AABB (half-widths). GetExtents() { return b2Vec2.ExtVV(this.lowerBound, this.upperBound, this.m_cache_extent); } /// Get the perimeter length GetPerimeter() { const wx = this.upperBound.x - this.lowerBound.x; const wy = this.upperBound.y - this.lowerBound.y; return 2 * (wx + wy); } /// Combine an AABB into this one. Combine1(aabb) { this.lowerBound.x = b2Min(this.lowerBound.x, aabb.lowerBound.x); this.lowerBound.y = b2Min(this.lowerBound.y, aabb.lowerBound.y); this.upperBound.x = b2Max(this.upperBound.x, aabb.upperBound.x); this.upperBound.y = b2Max(this.upperBound.y, aabb.upperBound.y); return this; } /// Combine two AABBs into this one. Combine2(aabb1, aabb2) { this.lowerBound.x = b2Min(aabb1.lowerBound.x, aabb2.lowerBound.x); this.lowerBound.y = b2Min(aabb1.lowerBound.y, aabb2.lowerBound.y); this.upperBound.x = b2Max(aabb1.upperBound.x, aabb2.upperBound.x); this.upperBound.y = b2Max(aabb1.upperBound.y, aabb2.upperBound.y); return this; } static Combine(aabb1, aabb2, out) { out.Combine2(aabb1, aabb2); return out; } /// Does this aabb contain the provided AABB. Contains(aabb) { let 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; } // From Real-time Collision Detection, p179. RayCast(output, input) { let tmin = (-b2_maxFloat); let tmax = b2_maxFloat; const p_x = input.p1.x; const p_y = input.p1.y; const d_x = input.p2.x - input.p1.x; const d_y = input.p2.y - input.p1.y; const absD_x = b2Abs(d_x); const absD_y = b2Abs(d_y); const normal = output.normal; if (absD_x < b2_epsilon) { // Parallel. if (p_x < this.lowerBound.x || this.upperBound.x < p_x) { return false; } } else { const inv_d = 1 / d_x; let t1 = (this.lowerBound.x - p_x) * inv_d; let t2 = (this.upperBound.x - p_x) * inv_d; // Sign of the normal vector. let s = (-1); if (t1 > t2) { const t3 = t1; t1 = t2; t2 = t3; s = 1; } // Push the min up if (t1 > tmin) { normal.x = s; normal.y = 0; tmin = t1; } // Pull the max down tmax = b2Min(tmax, t2); if (tmin > tmax) { return false; } } if (absD_y < b2_epsilon) { // Parallel. if (p_y < this.lowerBound.y || this.upperBound.y < p_y) { return false; } } else { const inv_d = 1 / d_y; let t1 = (this.lowerBound.y - p_y) * inv_d; let t2 = (this.upperBound.y - p_y) * inv_d; // Sign of the normal vector. let s = (-1); if (t1 > t2) { const t3 = t1; t1 = t2; t2 = t3; s = 1; } // Push the min up if (t1 > tmin) { normal.x = 0; normal.y = s; tmin = t1; } // Pull the max down tmax = b2Min(tmax, t2); if (tmin > tmax) { return false; } } // Does the ray start inside the box? // Does the ray intersect beyond the max fraction? if (tmin < 0 || input.maxFraction < tmin) { return false; } // Intersection. output.fraction = tmin; return true; } TestContain(point) { if (point.x < this.lowerBound.x || this.upperBound.x < point.x) { return false; } if (point.y < this.lowerBound.y || this.upperBound.y < point.y) { return false; } return true; } TestOverlap(other) { const d1_x = other.lowerBound.x - this.upperBound.x; const d1_y = other.lowerBound.y - this.upperBound.y; const d2_x = this.lowerBound.x - other.upperBound.x; const d2_y = this.lowerBound.y - other.upperBound.y; if (d1_x > 0 || d1_y > 0) { return false; } if (d2_x > 0 || d2_y > 0) { return false; } return true; } }
JavaScript
class b2TreeNode { constructor(id = 0) { this.m_id = 0; this.aabb = new b2AABB(); this.parent = null; // or next this.child1 = null; this.child2 = null; this.height = 0; // leaf = 0, free node = -1 this.m_id = id; } IsLeaf() { return this.child1 === null; } }
JavaScript
class b2Pair { constructor(proxyA, proxyB) { this.proxyA = proxyA; this.proxyB = proxyB; } }
JavaScript
class b2BroadPhase { constructor() { this.m_tree = new b2DynamicTree(); this.m_proxyCount = 0; // public m_moveCapacity: number = 16; this.m_moveCount = 0; this.m_moveBuffer = []; // public m_pairCapacity: number = 16; this.m_pairCount = 0; this.m_pairBuffer = []; } // public m_queryProxyId: number = 0; /// Create a proxy with an initial AABB. Pairs are not reported until /// UpdatePairs is called. CreateProxy(aabb, userData) { const proxy = this.m_tree.CreateProxy(aabb, userData); ++this.m_proxyCount; this.BufferMove(proxy); return proxy; } /// Destroy a proxy. It is up to the client to remove any pairs. DestroyProxy(proxy) { this.UnBufferMove(proxy); --this.m_proxyCount; this.m_tree.DestroyProxy(proxy); } /// Call MoveProxy as many times as you like, then when you are done /// call UpdatePairs to finalized the proxy pairs (for your time step). MoveProxy(proxy, aabb, displacement) { const buffer = this.m_tree.MoveProxy(proxy, aabb, displacement); if (buffer) { this.BufferMove(proxy); } } /// Call to trigger a re-processing of it's pairs on the next call to UpdatePairs. TouchProxy(proxy) { this.BufferMove(proxy); } /// Get the fat AABB for a proxy. // public GetFatAABB(proxy: b2TreeNode<T>): b2AABB { // return this.m_tree.GetFatAABB(proxy); // } /// Get user data from a proxy. Returns NULL if the id is invalid. // public GetUserData(proxy: b2TreeNode<T>): T { // return this.m_tree.GetUserData(proxy); // } /// Test overlap of fat AABBs. // public TestOverlap(proxyA: b2TreeNode<T>, proxyB: b2TreeNode<T>): boolean { // const aabbA: b2AABB = this.m_tree.GetFatAABB(proxyA); // const aabbB: b2AABB = this.m_tree.GetFatAABB(proxyB); // return b2TestOverlapAABB(aabbA, aabbB); // } /// Get the number of proxies. GetProxyCount() { return this.m_proxyCount; } /// Update the pairs. This results in pair callbacks. This can only add pairs. UpdatePairs(callback) { // Reset pair buffer this.m_pairCount = 0; // Perform tree queries for all moving proxies. for (let i = 0; i < this.m_moveCount; ++i) { const queryProxy = this.m_moveBuffer[i]; if (queryProxy === null) { continue; } // This is called from box2d.b2DynamicTree::Query when we are gathering pairs. // boolean b2BroadPhase::QueryCallback(int32 proxyId); // We have to query the tree with the fat AABB so that // we don't fail to create a pair that may touch later. const fatAABB = queryProxy.aabb; // this.m_tree.GetFatAABB(queryProxy); // Query tree, create pairs and add them pair buffer. this.m_tree.Query(fatAABB, (proxy) => { // A proxy cannot form a pair with itself. if (proxy.m_id === queryProxy.m_id) { return true; } // const proxyA = proxy < queryProxy ? proxy : queryProxy; // const proxyB = proxy >= queryProxy ? proxy : queryProxy; let proxyA; let proxyB; if (proxy.m_id < queryProxy.m_id) { proxyA = proxy; proxyB = queryProxy; } else { proxyA = queryProxy; proxyB = proxy; } // Grow the pair buffer as needed. if (this.m_pairCount === this.m_pairBuffer.length) { this.m_pairBuffer[this.m_pairCount] = new b2Pair(proxyA, proxyB); } else { const pair = this.m_pairBuffer[this.m_pairCount]; pair.proxyA = proxyA; pair.proxyB = proxyB; } ++this.m_pairCount; return true; }); } // Reset move buffer this.m_moveCount = 0; // Sort the pair buffer to expose duplicates. this.m_pairBuffer.length = this.m_pairCount; this.m_pairBuffer.sort(b2PairLessThan); // Send the pairs back to the client. let i = 0; while (i < this.m_pairCount) { const primaryPair = this.m_pairBuffer[i]; const userDataA = primaryPair.proxyA.userData; // this.m_tree.GetUserData(primaryPair.proxyA); const userDataB = primaryPair.proxyB.userData; // this.m_tree.GetUserData(primaryPair.proxyB); callback(userDataA, userDataB); ++i; // Skip any duplicate pairs. while (i < this.m_pairCount) { const pair = this.m_pairBuffer[i]; if (pair.proxyA.m_id !== primaryPair.proxyA.m_id || pair.proxyB.m_id !== primaryPair.proxyB.m_id) { break; } ++i; } } // Try to keep the tree balanced. // this.m_tree.Rebalance(4); } /// Query an AABB for overlapping proxies. The callback class /// is called for each proxy that overlaps the supplied AABB. Query(aabb, callback) { this.m_tree.Query(aabb, callback); } QueryPoint(point, callback) { this.m_tree.QueryPoint(point, callback); } /// Ray-cast against the proxies in the tree. This relies on the callback /// to perform a exact ray-cast in the case were the proxy contains a shape. /// The callback also performs the any collision filtering. This has performance /// roughly equal to k * log(n), where k is the number of collisions and n is the /// number of proxies in the tree. /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). /// @param callback a callback class that is called for each proxy that is hit by the ray. RayCast(input, callback) { this.m_tree.RayCast(input, callback); } /// Get the height of the embedded tree. GetTreeHeight() { return this.m_tree.GetHeight(); } /// Get the balance of the embedded tree. GetTreeBalance() { return this.m_tree.GetMaxBalance(); } /// Get the quality metric of the embedded tree. GetTreeQuality() { return this.m_tree.GetAreaRatio(); } /// Shift the world origin. Useful for large worlds. /// The shift formula is: position -= newOrigin /// @param newOrigin the new origin with respect to the old origin ShiftOrigin(newOrigin) { this.m_tree.ShiftOrigin(newOrigin); } BufferMove(proxy) { this.m_moveBuffer[this.m_moveCount] = proxy; ++this.m_moveCount; } UnBufferMove(proxy) { const i = this.m_moveBuffer.indexOf(proxy); this.m_moveBuffer[i] = null; } }
JavaScript
class b2TOIInput { constructor() { this.proxyA = new b2DistanceProxy(); this.proxyB = new b2DistanceProxy(); this.sweepA = new b2Sweep(); this.sweepB = new b2Sweep(); this.tMax = 0; // defines sweep interval [0, tMax] } }
JavaScript
class b2MassData { constructor() { /// The mass of the shape, usually in kilograms. this.mass = 0; /// The position of the shape's centroid relative to the shape's origin. this.center = new b2Vec2(0, 0); /// The rotational inertia of the shape about the local origin. this.I = 0; } }
JavaScript
class b2PolygonShape extends b2Shape { constructor() { super(b2ShapeType.e_polygonShape, b2_polygonRadius); this.m_centroid = new b2Vec2(0, 0); this.m_vertices = []; this.m_normals = []; this.m_count = 0; } /// Implement b2Shape. Clone() { return new b2PolygonShape().Copy(this); } Copy(other) { super.Copy(other); // DEBUG: b2Assert(other instanceof b2PolygonShape); this.m_centroid.Copy(other.m_centroid); this.m_count = other.m_count; this.m_vertices = b2Vec2.MakeArray(this.m_count); this.m_normals = b2Vec2.MakeArray(this.m_count); for (let i = 0; i < this.m_count; ++i) { this.m_vertices[i].Copy(other.m_vertices[i]); this.m_normals[i].Copy(other.m_normals[i]); } return this; } /// @see b2Shape::GetChildCount GetChildCount() { return 1; } Set(vertices, count = vertices.length, start = 0) { // DEBUG: b2Assert(3 <= count); if (count < 3) { return this.SetAsBox(1, 1); } let n = count; // Perform welding and copy vertices into local buffer. const ps = []; for (let i = 0; i < n; ++i) { const /*b2Vec2*/ v = vertices[start + i]; let /*bool*/ unique = true; for (let /*int32*/ j = 0; j < ps.length; ++j) { if (b2Vec2.DistanceSquaredVV(v, ps[j]) < ((0.5 * b2_linearSlop) * (0.5 * b2_linearSlop))) { unique = false; break; } } if (unique) { ps.push(v); } } n = ps.length; if (n < 3) { // Polygon is degenerate. // DEBUG: b2Assert(false); return this.SetAsBox(1.0, 1.0); } // Create the convex hull using the Gift wrapping algorithm // http://en.wikipedia.org/wiki/Gift_wrapping_algorithm // Find the right most point on the hull let i0 = 0; let x0 = ps[0].x; for (let i = 1; i < n; ++i) { const x = ps[i].x; if (x > x0 || (x === x0 && ps[i].y < ps[i0].y)) { i0 = i; x0 = x; } } const hull = []; let m = 0; let ih = i0; for (;;) { hull[m] = ih; let ie = 0; for (let j = 1; j < n; ++j) { if (ie === ih) { ie = j; continue; } const r = b2Vec2.SubVV(ps[ie], ps[hull[m]], b2PolygonShape.Set_s_r); const v = b2Vec2.SubVV(ps[j], ps[hull[m]], b2PolygonShape.Set_s_v); const c = b2Vec2.CrossVV(r, v); if (c < 0) { ie = j; } // Collinearity check if (c === 0 && v.LengthSquared() > r.LengthSquared()) { ie = j; } } ++m; ih = ie; if (ie === i0) { break; } } this.m_count = m; this.m_vertices = b2Vec2.MakeArray(this.m_count); this.m_normals = b2Vec2.MakeArray(this.m_count); // Copy vertices. for (let i = 0; i < m; ++i) { this.m_vertices[i].Copy(ps[hull[i]]); } // Compute normals. Ensure the edges have non-zero length. for (let i = 0; i < m; ++i) { const vertexi1 = this.m_vertices[i]; const vertexi2 = this.m_vertices[(i + 1) % m]; const edge = b2Vec2.SubVV(vertexi2, vertexi1, b2Vec2.s_t0); // edge uses s_t0 // DEBUG: b2Assert(edge.LengthSquared() > b2_epsilon_sq); b2Vec2.CrossVOne(edge, this.m_normals[i]).SelfNormalize(); } // Compute the polygon centroid. b2PolygonShape.ComputeCentroid(this.m_vertices, m, this.m_centroid); return this; } SetAsArray(vertices, count = vertices.length) { return this.Set(vertices, count); } /// Build vertices to represent an axis-aligned box or an oriented box. /// @param hx the half-width. /// @param hy the half-height. /// @param center the center of the box in local coordinates. /// @param angle the rotation of the box in local coordinates. SetAsBox(hx, hy, center, angle = 0) { this.m_count = 4; this.m_vertices = b2Vec2.MakeArray(this.m_count); this.m_normals = b2Vec2.MakeArray(this.m_count); 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, (-1)); this.m_normals[1].Set(1, 0); this.m_normals[2].Set(0, 1); this.m_normals[3].Set((-1), 0); this.m_centroid.SetZero(); if (center) { this.m_centroid.Copy(center); const xf = new b2Transform(); xf.SetPosition(center); xf.SetRotationAngle(angle); // Transform vertices and normals. for (let i = 0; i < this.m_count; ++i) { b2Transform.MulXV(xf, this.m_vertices[i], this.m_vertices[i]); b2Rot.MulRV(xf.q, this.m_normals[i], this.m_normals[i]); } } return this; } TestPoint(xf, p) { const pLocal = b2Transform.MulTXV(xf, p, b2PolygonShape.TestPoint_s_pLocal); for (let i = 0; i < this.m_count; ++i) { const dot = b2Vec2.DotVV(this.m_normals[i], b2Vec2.SubVV(pLocal, this.m_vertices[i], b2Vec2.s_t0)); if (dot > 0) { return false; } } return true; } ComputeDistance(xf, p, normal, childIndex) { const pLocal = b2Transform.MulTXV(xf, p, b2PolygonShape.ComputeDistance_s_pLocal); let maxDistance = -b2_maxFloat; const normalForMaxDistance = b2PolygonShape.ComputeDistance_s_normalForMaxDistance.Copy(pLocal); for (let i = 0; i < this.m_count; ++i) { const dot = b2Vec2.DotVV(this.m_normals[i], b2Vec2.SubVV(pLocal, this.m_vertices[i], b2Vec2.s_t0)); if (dot > maxDistance) { maxDistance = dot; normalForMaxDistance.Copy(this.m_normals[i]); } } if (maxDistance > 0) { const minDistance = b2PolygonShape.ComputeDistance_s_minDistance.Copy(normalForMaxDistance); let minDistance2 = maxDistance * maxDistance; for (let i = 0; i < this.m_count; ++i) { const distance = b2Vec2.SubVV(pLocal, this.m_vertices[i], b2PolygonShape.ComputeDistance_s_distance); const distance2 = distance.LengthSquared(); if (minDistance2 > distance2) { minDistance.Copy(distance); minDistance2 = distance2; } } b2Rot.MulRV(xf.q, minDistance, normal); normal.Normalize(); return Math.sqrt(minDistance2); } else { b2Rot.MulRV(xf.q, normalForMaxDistance, normal); return maxDistance; } } RayCast(output, input, xf, childIndex) { // Put the ray into the polygon's frame of reference. const p1 = b2Transform.MulTXV(xf, input.p1, b2PolygonShape.RayCast_s_p1); const p2 = b2Transform.MulTXV(xf, input.p2, b2PolygonShape.RayCast_s_p2); const d = b2Vec2.SubVV(p2, p1, b2PolygonShape.RayCast_s_d); let lower = 0, upper = input.maxFraction; let index = -1; for (let i = 0; i < this.m_count; ++i) { // p = p1 + a * d // dot(normal, p - v) = 0 // dot(normal, p1 - v) + a * dot(normal, d) = 0 const numerator = b2Vec2.DotVV(this.m_normals[i], b2Vec2.SubVV(this.m_vertices[i], p1, b2Vec2.s_t0)); const denominator = b2Vec2.DotVV(this.m_normals[i], d); if (denominator === 0) { if (numerator < 0) { return false; } } else { // Note: we want this predicate without division: // lower < numerator / denominator, where denominator < 0 // Since denominator < 0, we have to flip the inequality: // lower < numerator / denominator <==> denominator * lower > numerator. if (denominator < 0 && numerator < lower * denominator) { // Increase lower. // The segment enters this half-space. lower = numerator / denominator; index = i; } else if (denominator > 0 && numerator < upper * denominator) { // Decrease upper. // The segment exits this half-space. upper = numerator / denominator; } } // The use of epsilon here causes the assert on lower to trip // in some cases. Apparently the use of epsilon was to make edge // shapes work, but now those are handled separately. // if (upper < lower - b2_epsilon) if (upper < lower) { return false; } } // DEBUG: b2Assert(0 <= lower && lower <= input.maxFraction); if (index >= 0) { output.fraction = lower; b2Rot.MulRV(xf.q, this.m_normals[index], output.normal); return true; } return false; } ComputeAABB(aabb, xf, childIndex) { const lower = b2Transform.MulXV(xf, this.m_vertices[0], aabb.lowerBound); const upper = aabb.upperBound.Copy(lower); for (let i = 0; i < this.m_count; ++i) { const v = b2Transform.MulXV(xf, this.m_vertices[i], b2PolygonShape.ComputeAABB_s_v); b2Vec2.MinV(v, lower, lower); b2Vec2.MaxV(v, upper, upper); } const r = this.m_radius; lower.SelfSubXY(r, r); upper.SelfAddXY(r, r); } ComputeMass(massData, density) { // Polygon mass, centroid, and inertia. // Let rho be the polygon density in mass per unit area. // Then: // mass = rho * int(dA) // centroid.x = (1/mass) * rho * int(x * dA) // centroid.y = (1/mass) * rho * int(y * dA) // I = rho * int((x*x + y*y) * dA) // // We can compute these integrals by summing all the integrals // for each triangle of the polygon. To evaluate the integral // for a single triangle, we make a change of variables to // the (u,v) coordinates of the triangle: // x = x0 + e1x * u + e2x * v // y = y0 + e1y * u + e2y * v // where 0 <= u && 0 <= v && u + v <= 1. // // We integrate u from [0,1-v] and then v from [0,1]. // We also need to use the Jacobian of the transformation: // D = cross(e1, e2) // // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) // // The rest of the derivation is handled by computer algebra. // DEBUG: b2Assert(this.m_count >= 3); const center = b2PolygonShape.ComputeMass_s_center.SetZero(); let area = 0; let I = 0; // s is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). const s = b2PolygonShape.ComputeMass_s_s.SetZero(); // This code would put the reference point inside the polygon. for (let i = 0; i < this.m_count; ++i) { s.SelfAdd(this.m_vertices[i]); } s.SelfMul(1 / this.m_count); const k_inv3 = 1 / 3; for (let i = 0; i < this.m_count; ++i) { // Triangle vertices. const e1 = b2Vec2.SubVV(this.m_vertices[i], s, b2PolygonShape.ComputeMass_s_e1); const e2 = b2Vec2.SubVV(this.m_vertices[(i + 1) % this.m_count], s, b2PolygonShape.ComputeMass_s_e2); const D = b2Vec2.CrossVV(e1, e2); const triangleArea = 0.5 * D; area += triangleArea; // Area weighted centroid center.SelfAdd(b2Vec2.MulSV(triangleArea * k_inv3, b2Vec2.AddVV(e1, e2, b2Vec2.s_t0), b2Vec2.s_t1)); const ex1 = e1.x; const ey1 = e1.y; const ex2 = e2.x; const ey2 = e2.y; const intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2; const inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2; I += (0.25 * k_inv3 * D) * (intx2 + inty2); } // Total mass massData.mass = density * area; // Center of mass // DEBUG: b2Assert(area > b2_epsilon); center.SelfMul(1 / area); b2Vec2.AddVV(center, s, massData.center); // Inertia tensor relative to the local origin (point s). massData.I = density * I; // Shift to center of mass then to original body origin. massData.I += massData.mass * (b2Vec2.DotVV(massData.center, massData.center) - b2Vec2.DotVV(center, center)); } Validate() { for (let i = 0; i < this.m_count; ++i) { const i1 = i; const i2 = (i + 1) % this.m_count; const p = this.m_vertices[i1]; const e = b2Vec2.SubVV(this.m_vertices[i2], p, b2PolygonShape.Validate_s_e); for (let j = 0; j < this.m_count; ++j) { if (j === i1 || j === i2) { continue; } const v = b2Vec2.SubVV(this.m_vertices[j], p, b2PolygonShape.Validate_s_v); const c = b2Vec2.CrossVV(e, v); if (c < 0) { return false; } } } return true; } SetupDistanceProxy(proxy, index) { proxy.m_vertices = this.m_vertices; proxy.m_count = this.m_count; proxy.m_radius = this.m_radius; } ComputeSubmergedArea(normal, offset, xf, c) { // Transform plane into shape co-ordinates const normalL = b2Rot.MulTRV(xf.q, normal, b2PolygonShape.ComputeSubmergedArea_s_normalL); const offsetL = offset - b2Vec2.DotVV(normal, xf.p); const depths = []; let diveCount = 0; let intoIndex = -1; let outoIndex = -1; let lastSubmerged = false; for (let i = 0; i < this.m_count; ++i) { depths[i] = b2Vec2.DotVV(normalL, this.m_vertices[i]) - offsetL; const isSubmerged = depths[i] < (-b2_epsilon); 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) { // Completely submerged const md = b2PolygonShape.ComputeSubmergedArea_s_md; this.ComputeMass(md, 1); b2Transform.MulXV(xf, md.center, c); return md.mass; } else { // Completely dry return 0; } case 1: if (intoIndex === (-1)) { intoIndex = this.m_count - 1; } else { outoIndex = this.m_count - 1; } break; } const intoIndex2 = ((intoIndex + 1) % this.m_count); const outoIndex2 = ((outoIndex + 1) % this.m_count); const intoLamdda = (0 - depths[intoIndex]) / (depths[intoIndex2] - depths[intoIndex]); const outoLamdda = (0 - depths[outoIndex]) / (depths[outoIndex2] - depths[outoIndex]); const intoVec = b2PolygonShape.ComputeSubmergedArea_s_intoVec.Set(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); const outoVec = b2PolygonShape.ComputeSubmergedArea_s_outoVec.Set(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); // Initialize accumulator let area = 0; const center = b2PolygonShape.ComputeSubmergedArea_s_center.SetZero(); let p2 = this.m_vertices[intoIndex2]; let p3; // An awkward loop from intoIndex2+1 to outIndex2 let i = intoIndex2; while (i !== outoIndex2) { i = (i + 1) % this.m_count; if (i === outoIndex2) { p3 = outoVec; } else { p3 = this.m_vertices[i]; } const triangleArea = 0.5 * ((p2.x - intoVec.x) * (p3.y - intoVec.y) - (p2.y - intoVec.y) * (p3.x - intoVec.x)); area += triangleArea; // Area weighted centroid center.x += triangleArea * (intoVec.x + p2.x + p3.x) / 3; center.y += triangleArea * (intoVec.y + p2.y + p3.y) / 3; p2 = p3; } // Normalize and transform centroid center.SelfMul(1 / area); b2Transform.MulXV(xf, center, c); return area; } Dump(log) { log(" const shape: b2PolygonShape = new b2PolygonShape();\n"); log(" const vs: b2Vec2[] = [];\n"); for (let i = 0; i < this.m_count; ++i) { log(" vs[%d] = new b2Vec2(%.15f, %.15f);\n", i, this.m_vertices[i].x, this.m_vertices[i].y); } log(" shape.Set(vs, %d);\n", this.m_count); } static ComputeCentroid(vs, count, out) { // DEBUG: b2Assert(count >= 3); const c = out; c.SetZero(); let area = 0; // s is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). const pRef = b2PolygonShape.ComputeCentroid_s_pRef.SetZero(); /* #if 0 // This code would put the reference point inside the polygon. for (let i: number = 0; i < count; ++i) { pRef.SelfAdd(vs[i]); } pRef.SelfMul(1 / count); #endif */ const inv3 = 1 / 3; for (let i = 0; i < count; ++i) { // Triangle vertices. const p1 = pRef; const p2 = vs[i]; const p3 = vs[(i + 1) % count]; const e1 = b2Vec2.SubVV(p2, p1, b2PolygonShape.ComputeCentroid_s_e1); const e2 = b2Vec2.SubVV(p3, p1, b2PolygonShape.ComputeCentroid_s_e2); const D = b2Vec2.CrossVV(e1, e2); const triangleArea = 0.5 * D; area += triangleArea; // Area weighted centroid c.x += triangleArea * inv3 * (p1.x + p2.x + p3.x); c.y += triangleArea * inv3 * (p1.y + p2.y + p3.y); } // Centroid // DEBUG: b2Assert(area > b2_epsilon); c.SelfMul(1 / area); return c; } }
JavaScript
class b2EdgeShape extends b2Shape { constructor() { super(b2ShapeType.e_edgeShape, b2_polygonRadius); this.m_vertex1 = new b2Vec2(); this.m_vertex2 = new b2Vec2(); this.m_vertex0 = new b2Vec2(); this.m_vertex3 = new b2Vec2(); this.m_hasVertex0 = false; this.m_hasVertex3 = false; } /// Set this as an isolated edge. Set(v1, v2) { this.m_vertex1.Copy(v1); this.m_vertex2.Copy(v2); this.m_hasVertex0 = false; this.m_hasVertex3 = false; return this; } /// Implement b2Shape. Clone() { return new b2EdgeShape().Copy(this); } Copy(other) { super.Copy(other); // DEBUG: b2Assert(other instanceof b2EdgeShape); this.m_vertex1.Copy(other.m_vertex1); this.m_vertex2.Copy(other.m_vertex2); this.m_vertex0.Copy(other.m_vertex0); this.m_vertex3.Copy(other.m_vertex3); this.m_hasVertex0 = other.m_hasVertex0; this.m_hasVertex3 = other.m_hasVertex3; return this; } /// @see b2Shape::GetChildCount GetChildCount() { return 1; } /// @see b2Shape::TestPoint TestPoint(xf, p) { return false; } ComputeDistance(xf, p, normal, childIndex) { const v1 = b2Transform.MulXV(xf, this.m_vertex1, b2EdgeShape.ComputeDistance_s_v1); const v2 = b2Transform.MulXV(xf, this.m_vertex2, b2EdgeShape.ComputeDistance_s_v2); const d = b2Vec2.SubVV(p, v1, b2EdgeShape.ComputeDistance_s_d); const s = b2Vec2.SubVV(v2, v1, b2EdgeShape.ComputeDistance_s_s); const ds = b2Vec2.DotVV(d, s); if (ds > 0) { const s2 = b2Vec2.DotVV(s, s); if (ds > s2) { b2Vec2.SubVV(p, v2, d); } else { d.SelfMulSub(ds / s2, s); } } normal.Copy(d); return normal.Normalize(); } RayCast(output, input, xf, childIndex) { // Put the ray into the edge's frame of reference. const p1 = b2Transform.MulTXV(xf, input.p1, b2EdgeShape.RayCast_s_p1); const p2 = b2Transform.MulTXV(xf, input.p2, b2EdgeShape.RayCast_s_p2); const d = b2Vec2.SubVV(p2, p1, b2EdgeShape.RayCast_s_d); const v1 = this.m_vertex1; const v2 = this.m_vertex2; const e = b2Vec2.SubVV(v2, v1, b2EdgeShape.RayCast_s_e); const normal = output.normal.Set(e.y, -e.x).SelfNormalize(); // q = p1 + t * d // dot(normal, q - v1) = 0 // dot(normal, p1 - v1) + t * dot(normal, d) = 0 const numerator = b2Vec2.DotVV(normal, b2Vec2.SubVV(v1, p1, b2Vec2.s_t0)); const denominator = b2Vec2.DotVV(normal, d); if (denominator === 0) { return false; } const t = numerator / denominator; if (t < 0 || input.maxFraction < t) { return false; } const q = b2Vec2.AddVMulSV(p1, t, d, b2EdgeShape.RayCast_s_q); // q = v1 + s * r // s = dot(q - v1, r) / dot(r, r) const r = b2Vec2.SubVV(v2, v1, b2EdgeShape.RayCast_s_r); const rr = b2Vec2.DotVV(r, r); if (rr === 0) { return false; } const s = b2Vec2.DotVV(b2Vec2.SubVV(q, v1, b2Vec2.s_t0), r) / rr; if (s < 0 || 1 < s) { return false; } output.fraction = t; b2Rot.MulRV(xf.q, output.normal, output.normal); if (numerator > 0) { output.normal.SelfNeg(); } return true; } ComputeAABB(aabb, xf, childIndex) { const v1 = b2Transform.MulXV(xf, this.m_vertex1, b2EdgeShape.ComputeAABB_s_v1); const v2 = b2Transform.MulXV(xf, this.m_vertex2, b2EdgeShape.ComputeAABB_s_v2); b2Vec2.MinV(v1, v2, aabb.lowerBound); b2Vec2.MaxV(v1, v2, aabb.upperBound); const r = this.m_radius; aabb.lowerBound.SelfSubXY(r, r); aabb.upperBound.SelfAddXY(r, r); } /// @see b2Shape::ComputeMass ComputeMass(massData, density) { massData.mass = 0; b2Vec2.MidVV(this.m_vertex1, this.m_vertex2, massData.center); massData.I = 0; } SetupDistanceProxy(proxy, index) { proxy.m_vertices = proxy.m_buffer; proxy.m_vertices[0].Copy(this.m_vertex1); proxy.m_vertices[1].Copy(this.m_vertex2); proxy.m_count = 2; proxy.m_radius = this.m_radius; } ComputeSubmergedArea(normal, offset, xf, c) { c.SetZero(); return 0; } Dump(log) { log(" const shape: b2EdgeShape = new b2EdgeShape();\n"); log(" shape.m_radius = %.15f;\n", this.m_radius); log(" shape.m_vertex0.Set(%.15f, %.15f);\n", this.m_vertex0.x, this.m_vertex0.y); log(" shape.m_vertex1.Set(%.15f, %.15f);\n", this.m_vertex1.x, this.m_vertex1.y); log(" shape.m_vertex2.Set(%.15f, %.15f);\n", this.m_vertex2.x, this.m_vertex2.y); log(" shape.m_vertex3.Set(%.15f, %.15f);\n", this.m_vertex3.x, this.m_vertex3.y); log(" shape.m_hasVertex0 = %s;\n", this.m_hasVertex0); log(" shape.m_hasVertex3 = %s;\n", this.m_hasVertex3); } }
JavaScript
class b2ChainShape extends b2Shape { constructor() { super(b2ShapeType.e_chainShape, b2_polygonRadius); this.m_vertices = []; this.m_count = 0; this.m_prevVertex = new b2Vec2(); this.m_nextVertex = new b2Vec2(); this.m_hasPrevVertex = false; this.m_hasNextVertex = false; } /// Create a loop. This automatically adjusts connectivity. /// @param vertices an array of vertices, these are copied /// @param count the vertex count CreateLoop(vertices, count = vertices.length, start = 0) { // DEBUG: b2Assert(count >= 3); if (count < 3) { return this; } // DEBUG: for (let i: number = 1; i < count; ++i) { // DEBUG: const v1 = vertices[start + i - 1]; // DEBUG: const v2 = vertices[start + i]; // DEBUG: // If the code crashes here, it means your vertices are too close together. // DEBUG: b2Assert(b2Vec2.DistanceSquaredVV(v1, v2) > b2_linearSlop * b2_linearSlop); // DEBUG: } this.m_count = count + 1; this.m_vertices = b2Vec2.MakeArray(this.m_count); for (let i = 0; i < count; ++i) { this.m_vertices[i].Copy(vertices[start + i]); } this.m_vertices[count].Copy(this.m_vertices[0]); this.m_prevVertex.Copy(this.m_vertices[this.m_count - 2]); this.m_nextVertex.Copy(this.m_vertices[1]); this.m_hasPrevVertex = true; this.m_hasNextVertex = true; return this; } /// Create a chain with isolated end vertices. /// @param vertices an array of vertices, these are copied /// @param count the vertex count CreateChain(vertices, count = vertices.length, start = 0) { // DEBUG: b2Assert(count >= 2); // DEBUG: for (let i: number = 1; i < count; ++i) { // DEBUG: const v1 = vertices[start + i - 1]; // DEBUG: const v2 = vertices[start + i]; // DEBUG: // If the code crashes here, it means your vertices are too close together. // DEBUG: b2Assert(b2Vec2.DistanceSquaredVV(v1, v2) > b2_linearSlop * b2_linearSlop); // DEBUG: } this.m_count = count; this.m_vertices = b2Vec2.MakeArray(count); for (let i = 0; i < count; ++i) { this.m_vertices[i].Copy(vertices[start + i]); } this.m_hasPrevVertex = false; this.m_hasNextVertex = false; this.m_prevVertex.SetZero(); this.m_nextVertex.SetZero(); return this; } /// Establish connectivity to a vertex that precedes the first vertex. /// Don't call this for loops. SetPrevVertex(prevVertex) { this.m_prevVertex.Copy(prevVertex); this.m_hasPrevVertex = true; return this; } /// Establish connectivity to a vertex that follows the last vertex. /// Don't call this for loops. SetNextVertex(nextVertex) { this.m_nextVertex.Copy(nextVertex); this.m_hasNextVertex = true; return this; } /// Implement b2Shape. Vertices are cloned using b2Alloc. Clone() { return new b2ChainShape().Copy(this); } Copy(other) { super.Copy(other); // DEBUG: b2Assert(other instanceof b2ChainShape); this.CreateChain(other.m_vertices, other.m_count); this.m_prevVertex.Copy(other.m_prevVertex); this.m_nextVertex.Copy(other.m_nextVertex); this.m_hasPrevVertex = other.m_hasPrevVertex; this.m_hasNextVertex = other.m_hasNextVertex; return this; } /// @see b2Shape::GetChildCount GetChildCount() { // edge count = vertex count - 1 return this.m_count - 1; } /// Get a child edge. GetChildEdge(edge, index) { // DEBUG: b2Assert(0 <= index && index < this.m_count - 1); edge.m_type = b2ShapeType.e_edgeShape; edge.m_radius = this.m_radius; edge.m_vertex1.Copy(this.m_vertices[index]); edge.m_vertex2.Copy(this.m_vertices[index + 1]); if (index > 0) { edge.m_vertex0.Copy(this.m_vertices[index - 1]); edge.m_hasVertex0 = true; } else { edge.m_vertex0.Copy(this.m_prevVertex); edge.m_hasVertex0 = this.m_hasPrevVertex; } if (index < this.m_count - 2) { edge.m_vertex3.Copy(this.m_vertices[index + 2]); edge.m_hasVertex3 = true; } else { edge.m_vertex3.Copy(this.m_nextVertex); edge.m_hasVertex3 = this.m_hasNextVertex; } } /// This always return false. /// @see b2Shape::TestPoint TestPoint(xf, p) { return false; } ComputeDistance(xf, p, normal, childIndex) { const edge = b2ChainShape.ComputeDistance_s_edgeShape; this.GetChildEdge(edge, childIndex); return edge.ComputeDistance(xf, p, normal, 0); } RayCast(output, input, xf, childIndex) { // DEBUG: b2Assert(childIndex < this.m_count); const edgeShape = b2ChainShape.RayCast_s_edgeShape; edgeShape.m_vertex1.Copy(this.m_vertices[childIndex]); edgeShape.m_vertex2.Copy(this.m_vertices[(childIndex + 1) % this.m_count]); return edgeShape.RayCast(output, input, xf, 0); } ComputeAABB(aabb, xf, childIndex) { // DEBUG: b2Assert(childIndex < this.m_count); const vertexi1 = this.m_vertices[childIndex]; const vertexi2 = this.m_vertices[(childIndex + 1) % this.m_count]; const v1 = b2Transform.MulXV(xf, vertexi1, b2ChainShape.ComputeAABB_s_v1); const v2 = b2Transform.MulXV(xf, vertexi2, b2ChainShape.ComputeAABB_s_v2); b2Vec2.MinV(v1, v2, aabb.lowerBound); b2Vec2.MaxV(v1, v2, aabb.upperBound); } /// Chains have zero mass. /// @see b2Shape::ComputeMass ComputeMass(massData, density) { massData.mass = 0; massData.center.SetZero(); massData.I = 0; } SetupDistanceProxy(proxy, index) { // DEBUG: b2Assert(0 <= index && index < this.m_count); proxy.m_vertices = proxy.m_buffer; proxy.m_vertices[0].Copy(this.m_vertices[index]); if (index + 1 < this.m_count) { proxy.m_vertices[1].Copy(this.m_vertices[index + 1]); } else { proxy.m_vertices[1].Copy(this.m_vertices[0]); } proxy.m_count = 2; proxy.m_radius = this.m_radius; } ComputeSubmergedArea(normal, offset, xf, c) { c.SetZero(); return 0; } Dump(log) { log(" const shape: b2ChainShape = new b2ChainShape();\n"); log(" const vs: b2Vec2[] = [];\n"); for (let i = 0; i < this.m_count; ++i) { log(" vs[%d] = new bVec2(%.15f, %.15f);\n", i, this.m_vertices[i].x, this.m_vertices[i].y); } log(" shape.CreateChain(vs, %d);\n", this.m_count); log(" shape.m_prevVertex.Set(%.15f, %.15f);\n", this.m_prevVertex.x, this.m_prevVertex.y); log(" shape.m_nextVertex.Set(%.15f, %.15f);\n", this.m_nextVertex.x, this.m_nextVertex.y); log(" shape.m_hasPrevVertex = %s;\n", (this.m_hasPrevVertex) ? ("true") : ("false")); log(" shape.m_hasNextVertex = %s;\n", (this.m_hasNextVertex) ? ("true") : ("false")); } }
JavaScript
class b2Filter { constructor() { /// The collision category bits. Normally you would just set one bit. this.categoryBits = 0x0001; /// The collision mask bits. This states the categories that this /// shape would accept for collision. this.maskBits = 0xFFFF; /// Collision groups allow a certain group of objects to never collide (negative) /// or always collide (positive). Zero means no collision group. Non-zero group /// filtering always wins against the mask bits. this.groupIndex = 0; } Clone() { return new b2Filter().Copy(this); } Copy(other) { // DEBUG: b2Assert(this !== other); this.categoryBits = other.categoryBits; this.maskBits = other.maskBits; this.groupIndex = other.groupIndex || 0; return this; } }
JavaScript
class b2FixtureDef { constructor() { /// Use this to store application specific fixture data. this.userData = null; /// The friction coefficient, usually in the range [0,1]. this.friction = 0.2; /// The restitution (elasticity) usually in the range [0,1]. this.restitution = 0; /// The density, usually in kg/m^2. this.density = 0; /// A sensor shape collects contact information but never generates a collision /// response. this.isSensor = false; /// Contact filtering data. this.filter = new b2Filter(); } }
JavaScript
class b2FixtureProxy { constructor(fixture) { this.aabb = new b2AABB(); this.childIndex = 0; this.fixture = fixture; } }
JavaScript
class b2BodyDef { constructor() { /// The body type: static, kinematic, or dynamic. /// Note: if a dynamic body would have zero mass, the mass is set to one. this.type = b2BodyType.b2_staticBody; /// The world position of the body. Avoid creating bodies at the origin /// since this can lead to many overlapping shapes. this.position = new b2Vec2(0, 0); /// The world angle of the body in radians. this.angle = 0; /// The linear velocity of the body's origin in world co-ordinates. this.linearVelocity = new b2Vec2(0, 0); /// The angular velocity of the body. this.angularVelocity = 0; /// Linear damping is use to reduce the linear velocity. The damping parameter /// can be larger than 1.0f but the damping effect becomes sensitive to the /// time step when the damping parameter is large. this.linearDamping = 0; /// Angular damping is use to reduce the angular velocity. The damping parameter /// can be larger than 1.0f but the damping effect becomes sensitive to the /// time step when the damping parameter is large. this.angularDamping = 0; /// Set this flag to false if this body should never fall asleep. Note that /// this increases CPU usage. this.allowSleep = true; /// Is this body initially awake or sleeping? this.awake = true; /// Should this body be prevented from rotating? Useful for characters. this.fixedRotation = false; /// Is this a fast moving body that should be prevented from tunneling through /// other moving bodies? Note that all bodies are prevented from tunneling through /// kinematic and static bodies. This setting is only considered on dynamic bodies. /// @warning You should use this flag sparingly since it increases processing time. this.bullet = false; /// Does this body start out active? this.active = true; /// Use this to store application specific body data. this.userData = null; /// Scale the gravity applied to this body. this.gravityScale = 1; } }
JavaScript
class b2Body { // #endif constructor(bd, world) { this.m_type = b2BodyType.b2_staticBody; this.m_islandFlag = false; this.m_awakeFlag = false; this.m_autoSleepFlag = false; this.m_bulletFlag = false; this.m_fixedRotationFlag = false; this.m_activeFlag = false; this.m_toiFlag = false; this.m_islandIndex = 0; this.m_xf = new b2Transform(); // the body origin transform // #if B2_ENABLE_PARTICLE this.m_xf0 = new b2Transform(); // #endif this.m_sweep = new b2Sweep(); // the swept motion for CCD this.m_linearVelocity = new b2Vec2(); this.m_angularVelocity = 0; this.m_force = new b2Vec2(); this.m_torque = 0; this.m_prev = null; this.m_next = null; this.m_fixtureList = null; this.m_fixtureCount = 0; this.m_jointList = null; this.m_contactList = null; this.m_mass = 1; this.m_invMass = 1; // Rotational inertia about the center of mass. this.m_I = 0; this.m_invI = 0; this.m_linearDamping = 0; this.m_angularDamping = 0; this.m_gravityScale = 1; this.m_sleepTime = 0; this.m_userData = null; // #if B2_ENABLE_CONTROLLER this.m_controllerList = null; this.m_controllerCount = 0; this.m_bulletFlag = b2Maybe(bd.bullet, false); this.m_fixedRotationFlag = b2Maybe(bd.fixedRotation, false); this.m_autoSleepFlag = b2Maybe(bd.allowSleep, true); this.m_awakeFlag = b2Maybe(bd.awake, true); this.m_activeFlag = b2Maybe(bd.active, true); this.m_world = world; this.m_xf.p.Copy(b2Maybe(bd.position, b2Vec2.ZERO)); // DEBUG: b2Assert(this.m_xf.p.IsValid()); this.m_xf.q.SetAngle(b2Maybe(bd.angle, 0)); // DEBUG: b2Assert(b2IsValid(this.m_xf.q.GetAngle())); // #if B2_ENABLE_PARTICLE this.m_xf0.Copy(this.m_xf); // #endif this.m_sweep.localCenter.SetZero(); this.m_sweep.c0.Copy(this.m_xf.p); this.m_sweep.c.Copy(this.m_xf.p); this.m_sweep.a0 = this.m_sweep.a = this.m_xf.q.GetAngle(); this.m_sweep.alpha0 = 0; this.m_linearVelocity.Copy(b2Maybe(bd.linearVelocity, b2Vec2.ZERO)); // DEBUG: b2Assert(this.m_linearVelocity.IsValid()); this.m_angularVelocity = b2Maybe(bd.angularVelocity, 0); // DEBUG: b2Assert(b2IsValid(this.m_angularVelocity)); this.m_linearDamping = b2Maybe(bd.linearDamping, 0); this.m_angularDamping = b2Maybe(bd.angularDamping, 0); this.m_gravityScale = b2Maybe(bd.gravityScale, 1); // DEBUG: b2Assert(b2IsValid(this.m_gravityScale) && this.m_gravityScale >= 0); // DEBUG: b2Assert(b2IsValid(this.m_angularDamping) && this.m_angularDamping >= 0); // DEBUG: b2Assert(b2IsValid(this.m_linearDamping) && this.m_linearDamping >= 0); this.m_force.SetZero(); this.m_torque = 0; this.m_sleepTime = 0; this.m_type = b2Maybe(bd.type, b2BodyType.b2_staticBody); if (bd.type === b2BodyType.b2_dynamicBody) { this.m_mass = 1; this.m_invMass = 1; } else { this.m_mass = 0; this.m_invMass = 0; } this.m_I = 0; this.m_invI = 0; this.m_userData = bd.userData; this.m_fixtureList = null; this.m_fixtureCount = 0; // #if B2_ENABLE_CONTROLLER this.m_controllerList = null; this.m_controllerCount = 0; // #endif } CreateFixture(a, b = 0) { if (a instanceof b2Shape) { return this.CreateFixtureShapeDensity(a, b); } else { return this.CreateFixtureDef(a); } } /// Creates a fixture and attach it to this body. Use this function if you need /// to set some fixture parameters, like friction. Otherwise you can create the /// fixture directly from a shape. /// If the density is non-zero, this function automatically updates the mass of the body. /// Contacts are not created until the next time step. /// @param def the fixture definition. /// @warning This function is locked during callbacks. CreateFixtureDef(def) { if (this.m_world.IsLocked()) { throw new Error(); } const fixture = new b2Fixture(def, this); fixture.Create(def); if (this.m_activeFlag) { fixture.CreateProxies(this.m_xf); } fixture.m_next = this.m_fixtureList; this.m_fixtureList = fixture; ++this.m_fixtureCount; // fixture.m_body = this; // Adjust mass properties if needed. if (fixture.m_density > 0) { this.ResetMassData(); } // Let the world know we have a new fixture. This will cause new contacts // to be created at the beginning of the next time step. this.m_world.m_newFixture = true; return fixture; } CreateFixtureShapeDensity(shape, density = 0) { const def = b2Body.CreateFixtureShapeDensity_s_def; def.shape = shape; def.density = density; return this.CreateFixtureDef(def); } /// Destroy a fixture. This removes the fixture from the broad-phase and /// destroys all contacts associated with this fixture. This will /// automatically adjust the mass of the body if the body is dynamic and the /// fixture has positive density. /// All fixtures attached to a body are implicitly destroyed when the body is destroyed. /// @param fixture the fixture to be removed. /// @warning This function is locked during callbacks. DestroyFixture(fixture) { if (this.m_world.IsLocked()) { throw new Error(); } // DEBUG: b2Assert(fixture.m_body === this); // Remove the fixture from this body's singly linked list. // DEBUG: b2Assert(this.m_fixtureCount > 0); let node = this.m_fixtureList; let ppF = null; // DEBUG: let found: boolean = false; while (node !== null) { if (node === fixture) { if (ppF) { ppF.m_next = fixture.m_next; } else { this.m_fixtureList = fixture.m_next; } // DEBUG: found = true; break; } ppF = node; node = node.m_next; } // You tried to remove a shape that is not attached to this body. // DEBUG: b2Assert(found); // Destroy any contacts associated with the fixture. let edge = this.m_contactList; while (edge) { const c = edge.contact; edge = edge.next; const fixtureA = c.GetFixtureA(); const fixtureB = c.GetFixtureB(); if (fixture === fixtureA || fixture === fixtureB) { // This destroys the contact and removes it from // this body's contact list. this.m_world.m_contactManager.Destroy(c); } } if (this.m_activeFlag) { fixture.DestroyProxies(); } // fixture.m_body = null; fixture.m_next = null; fixture.Destroy(); --this.m_fixtureCount; // Reset the mass data. this.ResetMassData(); } /// Set the position of the body's origin and rotation. /// This breaks any contacts and wakes the other bodies. /// Manipulating a body's transform may cause non-physical behavior. /// @param position the world position of the body's local origin. /// @param angle the world rotation in radians. SetTransformVec(position, angle) { this.SetTransformXY(position.x, position.y, angle); } SetTransformXY(x, y, angle) { if (this.m_world.IsLocked()) { throw new Error(); } this.m_xf.q.SetAngle(angle); this.m_xf.p.Set(x, y); // #if B2_ENABLE_PARTICLE this.m_xf0.Copy(this.m_xf); // #endif b2Transform.MulXV(this.m_xf, this.m_sweep.localCenter, this.m_sweep.c); this.m_sweep.a = angle; this.m_sweep.c0.Copy(this.m_sweep.c); this.m_sweep.a0 = angle; for (let f = this.m_fixtureList; f; f = f.m_next) { f.Synchronize(this.m_xf, this.m_xf); } this.m_world.m_contactManager.FindNewContacts(); } SetTransform(xf) { this.SetTransformVec(xf.p, xf.GetAngle()); } /// Get the body transform for the body's origin. /// @return the world transform of the body's origin. GetTransform() { return this.m_xf; } /// Get the world body origin position. /// @return the world position of the body's origin. GetPosition() { return this.m_xf.p; } SetPosition(position) { this.SetTransformVec(position, this.GetAngle()); } SetPositionXY(x, y) { this.SetTransformXY(x, y, this.GetAngle()); } /// Get the angle in radians. /// @return the current world rotation angle in radians. GetAngle() { return this.m_sweep.a; } SetAngle(angle) { this.SetTransformVec(this.GetPosition(), angle); } /// Get the world position of the center of mass. GetWorldCenter() { return this.m_sweep.c; } /// Get the local position of the center of mass. GetLocalCenter() { return this.m_sweep.localCenter; } /// Set the linear velocity of the center of mass. /// @param v the new linear velocity of the center of mass. SetLinearVelocity(v) { if (this.m_type === b2BodyType.b2_staticBody) { return; } if (b2Vec2.DotVV(v, v) > 0) { this.SetAwake(true); } this.m_linearVelocity.Copy(v); } /// Get the linear velocity of the center of mass. /// @return the linear velocity of the center of mass. GetLinearVelocity() { return this.m_linearVelocity; } /// Set the angular velocity. /// @param omega the new angular velocity in radians/second. SetAngularVelocity(w) { if (this.m_type === b2BodyType.b2_staticBody) { return; } if (w * w > 0) { this.SetAwake(true); } this.m_angularVelocity = w; } /// Get the angular velocity. /// @return the angular velocity in radians/second. GetAngularVelocity() { return this.m_angularVelocity; } GetDefinition(bd) { bd.type = this.GetType(); bd.allowSleep = this.m_autoSleepFlag; bd.angle = this.GetAngle(); bd.angularDamping = this.m_angularDamping; bd.gravityScale = this.m_gravityScale; bd.angularVelocity = this.m_angularVelocity; bd.fixedRotation = this.m_fixedRotationFlag; bd.bullet = this.m_bulletFlag; bd.awake = this.m_awakeFlag; bd.linearDamping = this.m_linearDamping; bd.linearVelocity.Copy(this.GetLinearVelocity()); bd.position.Copy(this.GetPosition()); bd.userData = this.GetUserData(); return bd; } /// Apply a force at a world point. If the force is not /// applied at the center of mass, it will generate a torque and /// affect the angular velocity. This wakes up the body. /// @param force the world force vector, usually in Newtons (N). /// @param point the world position of the point of application. /// @param wake also wake up the body ApplyForce(force, point, wake = true) { if (this.m_type !== b2BodyType.b2_dynamicBody) { return; } if (wake && !this.m_awakeFlag) { this.SetAwake(true); } // Don't accumulate a force if the body is sleeping. if (this.m_awakeFlag) { 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); } } /// Apply a force to the center of mass. This wakes up the body. /// @param force the world force vector, usually in Newtons (N). /// @param wake also wake up the body ApplyForceToCenter(force, wake = true) { if (this.m_type !== b2BodyType.b2_dynamicBody) { return; } if (wake && !this.m_awakeFlag) { this.SetAwake(true); } // Don't accumulate a force if the body is sleeping. if (this.m_awakeFlag) { this.m_force.x += force.x; this.m_force.y += force.y; } } /// Apply a torque. This affects the angular velocity /// without affecting the linear velocity of the center of mass. /// @param torque about the z-axis (out of the screen), usually in N-m. /// @param wake also wake up the body ApplyTorque(torque, wake = true) { if (this.m_type !== b2BodyType.b2_dynamicBody) { return; } if (wake && !this.m_awakeFlag) { this.SetAwake(true); } // Don't accumulate a force if the body is sleeping. if (this.m_awakeFlag) { this.m_torque += torque; } } /// Apply an impulse at a point. This immediately modifies the velocity. /// It also modifies the angular velocity if the point of application /// is not at the center of mass. This wakes up the body. /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s. /// @param point the world position of the point of application. /// @param wake also wake up the body ApplyLinearImpulse(impulse, point, wake = true) { if (this.m_type !== b2BodyType.b2_dynamicBody) { return; } if (wake && !this.m_awakeFlag) { this.SetAwake(true); } // Don't accumulate a force if the body is sleeping. if (this.m_awakeFlag) { 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); } } /// Apply an impulse at the center of gravity. This immediately modifies the velocity. /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s. /// @param wake also wake up the body ApplyLinearImpulseToCenter(impulse, wake = true) { if (this.m_type !== b2BodyType.b2_dynamicBody) { return; } if (wake && !this.m_awakeFlag) { this.SetAwake(true); } // Don't accumulate a force if the body is sleeping. if (this.m_awakeFlag) { this.m_linearVelocity.x += this.m_invMass * impulse.x; this.m_linearVelocity.y += this.m_invMass * impulse.y; } } /// Apply an angular impulse. /// @param impulse the angular impulse in units of kg*m*m/s /// @param wake also wake up the body ApplyAngularImpulse(impulse, wake = true) { if (this.m_type !== b2BodyType.b2_dynamicBody) { return; } if (wake && !this.m_awakeFlag) { this.SetAwake(true); } // Don't accumulate a force if the body is sleeping. if (this.m_awakeFlag) { this.m_angularVelocity += this.m_invI * impulse; } } /// Get the total mass of the body. /// @return the mass, usually in kilograms (kg). GetMass() { return this.m_mass; } /// Get the rotational inertia of the body about the local origin. /// @return the rotational inertia, usually in kg-m^2. GetInertia() { return this.m_I + this.m_mass * b2Vec2.DotVV(this.m_sweep.localCenter, this.m_sweep.localCenter); } /// Get the mass data of the body. /// @return a struct containing the mass, inertia and center of the body. GetMassData(data) { data.mass = this.m_mass; data.I = this.m_I + this.m_mass * b2Vec2.DotVV(this.m_sweep.localCenter, this.m_sweep.localCenter); data.center.Copy(this.m_sweep.localCenter); return data; } SetMassData(massData) { if (this.m_world.IsLocked()) { throw new Error(); } if (this.m_type !== b2BodyType.b2_dynamicBody) { return; } this.m_invMass = 0; this.m_I = 0; this.m_invI = 0; this.m_mass = massData.mass; if (this.m_mass <= 0) { this.m_mass = 1; } this.m_invMass = 1 / this.m_mass; if (massData.I > 0 && !this.m_fixedRotationFlag) { this.m_I = massData.I - this.m_mass * b2Vec2.DotVV(massData.center, massData.center); // DEBUG: b2Assert(this.m_I > 0); this.m_invI = 1 / this.m_I; } // Move center of mass. const oldCenter = b2Body.SetMassData_s_oldCenter.Copy(this.m_sweep.c); this.m_sweep.localCenter.Copy(massData.center); b2Transform.MulXV(this.m_xf, this.m_sweep.localCenter, this.m_sweep.c); this.m_sweep.c0.Copy(this.m_sweep.c); // Update center of mass velocity. b2Vec2.AddVCrossSV(this.m_linearVelocity, this.m_angularVelocity, b2Vec2.SubVV(this.m_sweep.c, oldCenter, b2Vec2.s_t0), this.m_linearVelocity); } ResetMassData() { // Compute mass data from shapes. Each shape has its own density. this.m_mass = 0; this.m_invMass = 0; this.m_I = 0; this.m_invI = 0; this.m_sweep.localCenter.SetZero(); // Static and kinematic bodies have zero mass. if (this.m_type === b2BodyType.b2_staticBody || this.m_type === b2BodyType.b2_kinematicBody) { this.m_sweep.c0.Copy(this.m_xf.p); this.m_sweep.c.Copy(this.m_xf.p); this.m_sweep.a0 = this.m_sweep.a; return; } // DEBUG: b2Assert(this.m_type === b2BodyType.b2_dynamicBody); // Accumulate mass over all fixtures. const localCenter = b2Body.ResetMassData_s_localCenter.SetZero(); for (let f = this.m_fixtureList; f; f = f.m_next) { if (f.m_density === 0) { continue; } const massData = f.GetMassData(b2Body.ResetMassData_s_massData); this.m_mass += massData.mass; localCenter.x += massData.center.x * massData.mass; localCenter.y += massData.center.y * massData.mass; this.m_I += massData.I; } // Compute center of mass. if (this.m_mass > 0) { this.m_invMass = 1 / this.m_mass; localCenter.x *= this.m_invMass; localCenter.y *= this.m_invMass; } else { // Force all dynamic bodies to have a positive mass. this.m_mass = 1; this.m_invMass = 1; } if (this.m_I > 0 && !this.m_fixedRotationFlag) { // Center the inertia about the center of mass. this.m_I -= this.m_mass * b2Vec2.DotVV(localCenter, localCenter); // DEBUG: b2Assert(this.m_I > 0); this.m_invI = 1 / this.m_I; } else { this.m_I = 0; this.m_invI = 0; } // Move center of mass. const oldCenter = b2Body.ResetMassData_s_oldCenter.Copy(this.m_sweep.c); this.m_sweep.localCenter.Copy(localCenter); b2Transform.MulXV(this.m_xf, this.m_sweep.localCenter, this.m_sweep.c); this.m_sweep.c0.Copy(this.m_sweep.c); // Update center of mass velocity. b2Vec2.AddVCrossSV(this.m_linearVelocity, this.m_angularVelocity, b2Vec2.SubVV(this.m_sweep.c, oldCenter, b2Vec2.s_t0), this.m_linearVelocity); } /// Get the world coordinates of a point given the local coordinates. /// @param localPoint a point on the body measured relative the the body's origin. /// @return the same point expressed in world coordinates. GetWorldPoint(localPoint, out) { return b2Transform.MulXV(this.m_xf, localPoint, out); } /// Get the world coordinates of a vector given the local coordinates. /// @param localVector a vector fixed in the body. /// @return the same vector expressed in world coordinates. GetWorldVector(localVector, out) { return b2Rot.MulRV(this.m_xf.q, localVector, out); } /// Gets a local point relative to the body's origin given a world point. /// @param a point in world coordinates. /// @return the corresponding local point relative to the body's origin. GetLocalPoint(worldPoint, out) { return b2Transform.MulTXV(this.m_xf, worldPoint, out); } /// Gets a local vector given a world vector. /// @param a vector in world coordinates. /// @return the corresponding local vector. GetLocalVector(worldVector, out) { return b2Rot.MulTRV(this.m_xf.q, worldVector, out); } /// Get the world linear velocity of a world point attached to this body. /// @param a point in world coordinates. /// @return the world velocity of a point. GetLinearVelocityFromWorldPoint(worldPoint, out) { return b2Vec2.AddVCrossSV(this.m_linearVelocity, this.m_angularVelocity, b2Vec2.SubVV(worldPoint, this.m_sweep.c, b2Vec2.s_t0), out); } /// Get the world velocity of a local point. /// @param a point in local coordinates. /// @return the world velocity of a point. GetLinearVelocityFromLocalPoint(localPoint, out) { return this.GetLinearVelocityFromWorldPoint(this.GetWorldPoint(localPoint, out), out); } /// Get the linear damping of the body. GetLinearDamping() { return this.m_linearDamping; } /// Set the linear damping of the body. SetLinearDamping(linearDamping) { this.m_linearDamping = linearDamping; } /// Get the angular damping of the body. GetAngularDamping() { return this.m_angularDamping; } /// Set the angular damping of the body. SetAngularDamping(angularDamping) { this.m_angularDamping = angularDamping; } /// Get the gravity scale of the body. GetGravityScale() { return this.m_gravityScale; } /// Set the gravity scale of the body. SetGravityScale(scale) { this.m_gravityScale = scale; } /// Set the type of this body. This may alter the mass and velocity. SetType(type) { if (this.m_world.IsLocked()) { throw new Error(); } if (this.m_type === type) { return; } this.m_type = type; this.ResetMassData(); if (this.m_type === b2BodyType.b2_staticBody) { this.m_linearVelocity.SetZero(); this.m_angularVelocity = 0; this.m_sweep.a0 = this.m_sweep.a; this.m_sweep.c0.Copy(this.m_sweep.c); this.SynchronizeFixtures(); } this.SetAwake(true); this.m_force.SetZero(); this.m_torque = 0; // Delete the attached contacts. let ce = this.m_contactList; while (ce) { const ce0 = ce; ce = ce.next; this.m_world.m_contactManager.Destroy(ce0.contact); } this.m_contactList = null; // Touch the proxies so that new contacts will be created (when appropriate) for (let f = this.m_fixtureList; f; f = f.m_next) { f.TouchProxies(); } } /// Get the type of this body. GetType() { return this.m_type; } /// Should this body be treated like a bullet for continuous collision detection? SetBullet(flag) { this.m_bulletFlag = flag; } /// Is this body treated like a bullet for continuous collision detection? IsBullet() { return this.m_bulletFlag; } /// You can disable sleeping on this body. If you disable sleeping, the /// body will be woken. SetSleepingAllowed(flag) { this.m_autoSleepFlag = flag; if (!flag) { this.SetAwake(true); } } /// Is this body allowed to sleep IsSleepingAllowed() { return this.m_autoSleepFlag; } /// Set the sleep state of the body. A sleeping body has very /// low CPU cost. /// @param flag set to true to wake the body, false to put it to sleep. SetAwake(flag) { if (flag) { this.m_awakeFlag = true; this.m_sleepTime = 0; } else { this.m_awakeFlag = false; this.m_sleepTime = 0; this.m_linearVelocity.SetZero(); this.m_angularVelocity = 0; this.m_force.SetZero(); this.m_torque = 0; } } /// Get the sleeping state of this body. /// @return true if the body is sleeping. IsAwake() { return this.m_awakeFlag; } /// Set the active state of the body. An inactive body is not /// simulated and cannot be collided with or woken up. /// If you pass a flag of true, all fixtures will be added to the /// broad-phase. /// If you pass a flag of false, all fixtures will be removed from /// the broad-phase and all contacts will be destroyed. /// Fixtures and joints are otherwise unaffected. You may continue /// to create/destroy fixtures and joints on inactive bodies. /// Fixtures on an inactive body are implicitly inactive and will /// not participate in collisions, ray-casts, or queries. /// Joints connected to an inactive body are implicitly inactive. /// An inactive body is still owned by a b2World object and remains /// in the body list. SetActive(flag) { if (this.m_world.IsLocked()) { throw new Error(); } if (flag === this.IsActive()) { return; } this.m_activeFlag = flag; if (flag) { // Create all proxies. for (let f = this.m_fixtureList; f; f = f.m_next) { f.CreateProxies(this.m_xf); } // Contacts are created the next time step. } else { // Destroy all proxies. for (let f = this.m_fixtureList; f; f = f.m_next) { f.DestroyProxies(); } // Destroy the attached contacts. let ce = this.m_contactList; while (ce) { const ce0 = ce; ce = ce.next; this.m_world.m_contactManager.Destroy(ce0.contact); } this.m_contactList = null; } } /// Get the active state of the body. IsActive() { return this.m_activeFlag; } /// Set this body to have fixed rotation. This causes the mass /// to be reset. SetFixedRotation(flag) { if (this.m_fixedRotationFlag === flag) { return; } this.m_fixedRotationFlag = flag; this.m_angularVelocity = 0; this.ResetMassData(); } /// Does this body have fixed rotation? IsFixedRotation() { return this.m_fixedRotationFlag; } /// Get the list of all fixtures attached to this body. GetFixtureList() { return this.m_fixtureList; } /// Get the list of all joints attached to this body. GetJointList() { return this.m_jointList; } /// Get the list of all contacts attached to this body. /// @warning this list changes during the time step and you may /// miss some collisions if you don't use b2ContactListener. GetContactList() { return this.m_contactList; } /// Get the next body in the world's body list. GetNext() { return this.m_next; } /// Get the user data pointer that was provided in the body definition. GetUserData() { return this.m_userData; } /// Set the user data. Use this to store your application specific data. SetUserData(data) { this.m_userData = data; } /// Get the parent world of this body. GetWorld() { return this.m_world; } /// Dump this body to a log file Dump(log) { const bodyIndex = this.m_islandIndex; log("{\n"); log(" const bd: b2BodyDef = new b2BodyDef();\n"); let type_str = ""; switch (this.m_type) { case b2BodyType.b2_staticBody: type_str = "b2BodyType.b2_staticBody"; break; case b2BodyType.b2_kinematicBody: type_str = "b2BodyType.b2_kinematicBody"; break; case b2BodyType.b2_dynamicBody: type_str = "b2BodyType.b2_dynamicBody"; break; default: // DEBUG: b2Assert(false); break; } log(" bd.type = %s;\n", type_str); log(" bd.position.Set(%.15f, %.15f);\n", this.m_xf.p.x, this.m_xf.p.y); log(" bd.angle = %.15f;\n", this.m_sweep.a); log(" bd.linearVelocity.Set(%.15f, %.15f);\n", this.m_linearVelocity.x, this.m_linearVelocity.y); log(" bd.angularVelocity = %.15f;\n", this.m_angularVelocity); log(" bd.linearDamping = %.15f;\n", this.m_linearDamping); log(" bd.angularDamping = %.15f;\n", this.m_angularDamping); log(" bd.allowSleep = %s;\n", (this.m_autoSleepFlag) ? ("true") : ("false")); log(" bd.awake = %s;\n", (this.m_awakeFlag) ? ("true") : ("false")); log(" bd.fixedRotation = %s;\n", (this.m_fixedRotationFlag) ? ("true") : ("false")); log(" bd.bullet = %s;\n", (this.m_bulletFlag) ? ("true") : ("false")); log(" bd.active = %s;\n", (this.m_activeFlag) ? ("true") : ("false")); log(" bd.gravityScale = %.15f;\n", this.m_gravityScale); log("\n"); log(" bodies[%d] = this.m_world.CreateBody(bd);\n", this.m_islandIndex); log("\n"); for (let f = this.m_fixtureList; f; f = f.m_next) { log(" {\n"); f.Dump(log, bodyIndex); log(" }\n"); } log("}\n"); } SynchronizeFixtures() { const xf1 = b2Body.SynchronizeFixtures_s_xf1; xf1.q.SetAngle(this.m_sweep.a0); b2Rot.MulRV(xf1.q, this.m_sweep.localCenter, xf1.p); b2Vec2.SubVV(this.m_sweep.c0, xf1.p, xf1.p); for (let f = this.m_fixtureList; f; f = f.m_next) { f.Synchronize(xf1, this.m_xf); } } SynchronizeTransform() { this.m_xf.q.SetAngle(this.m_sweep.a); b2Rot.MulRV(this.m_xf.q, this.m_sweep.localCenter, this.m_xf.p); b2Vec2.SubVV(this.m_sweep.c, this.m_xf.p, this.m_xf.p); } // This is used to prevent connected bodies from colliding. // It may lie, depending on the collideConnected flag. ShouldCollide(other) { // At least one body should be dynamic or kinematic. if (this.m_type === b2BodyType.b2_staticBody && other.m_type === b2BodyType.b2_staticBody) { return false; } return this.ShouldCollideConnected(other); } ShouldCollideConnected(other) { // Does a joint prevent collision? for (let jn = this.m_jointList; jn; jn = jn.next) { if (jn.other === other) { if (!jn.joint.m_collideConnected) { return false; } } } return true; } Advance(alpha) { // Advance to the new safe time. This doesn't sync the broad-phase. this.m_sweep.Advance(alpha); this.m_sweep.c.Copy(this.m_sweep.c0); this.m_sweep.a = this.m_sweep.a0; this.m_xf.q.SetAngle(this.m_sweep.a); b2Rot.MulRV(this.m_xf.q, this.m_sweep.localCenter, this.m_xf.p); b2Vec2.SubVV(this.m_sweep.c, this.m_xf.p, this.m_xf.p); } // #if B2_ENABLE_CONTROLLER GetControllerList() { return this.m_controllerList; } GetControllerCount() { return this.m_controllerCount; } }
JavaScript
class b2JointEdge { constructor(joint, other) { this.prev = null; ///< the previous joint edge in the body's joint list this.next = null; ///< the next joint edge in the body's joint list this.joint = joint; this.other = other; } }
JavaScript
class b2JointDef { constructor(type) { /// The joint type is set automatically for concrete joint types. this.type = b2JointType.e_unknownJoint; /// Use this to attach application specific data to your joints. this.userData = null; /// Set this flag to true if the attached bodies should collide. this.collideConnected = false; this.type = type; } }
JavaScript
class b2Joint { constructor(def) { // DEBUG: b2Assert(def.bodyA !== def.bodyB); this.m_type = b2JointType.e_unknownJoint; this.m_prev = null; this.m_next = null; this.m_index = 0; this.m_islandFlag = false; this.m_collideConnected = false; this.m_userData = null; this.m_type = def.type; this.m_edgeA = new b2JointEdge(this, def.bodyB); this.m_edgeB = new b2JointEdge(this, def.bodyA); this.m_bodyA = def.bodyA; this.m_bodyB = def.bodyB; this.m_collideConnected = b2Maybe(def.collideConnected, false); this.m_userData = def.userData; } /// Get the type of the concrete joint. GetType() { return this.m_type; } /// Get the first body attached to this joint. GetBodyA() { return this.m_bodyA; } /// Get the second body attached to this joint. GetBodyB() { return this.m_bodyB; } /// Get the next joint the world joint list. GetNext() { return this.m_next; } /// Get the user data pointer. GetUserData() { return this.m_userData; } /// Set the user data pointer. SetUserData(data) { this.m_userData = data; } /// Short-cut function to determine if either body is inactive. IsActive() { return this.m_bodyA.IsActive() && this.m_bodyB.IsActive(); } /// Get collide connected. /// Note: modifying the collide connect flag won't work correctly because /// the flag is only checked when fixture AABBs begin to overlap. GetCollideConnected() { return this.m_collideConnected; } /// Dump this joint to the log file. Dump(log) { log("// Dump is not supported for this joint type.\n"); } /// Shift the origin for any points stored in world coordinates. ShiftOrigin(newOrigin) { } }
JavaScript
class b2AreaJoint extends b2Joint { constructor(def) { super(def); this.m_frequencyHz = 0; this.m_dampingRatio = 0; // Solver shared this.m_impulse = 0; this.m_targetArea = 0; // DEBUG: b2Assert(def.bodies.length >= 3, "You cannot create an area joint with less than three bodies."); this.m_bodies = def.bodies; this.m_frequencyHz = b2Maybe(def.frequencyHz, 0); this.m_dampingRatio = b2Maybe(def.dampingRatio, 0); this.m_targetLengths = b2MakeNumberArray(def.bodies.length); this.m_normals = b2Vec2.MakeArray(def.bodies.length); this.m_joints = []; // b2MakeNullArray(def.bodies.length); this.m_deltas = b2Vec2.MakeArray(def.bodies.length); this.m_delta = new b2Vec2(); const djd = new b2DistanceJointDef(); djd.frequencyHz = this.m_frequencyHz; djd.dampingRatio = this.m_dampingRatio; this.m_targetArea = 0; for (let i = 0; i < this.m_bodies.length; ++i) { const body = this.m_bodies[i]; const next = this.m_bodies[(i + 1) % this.m_bodies.length]; const body_c = body.GetWorldCenter(); const next_c = next.GetWorldCenter(); this.m_targetLengths[i] = b2Vec2.DistanceVV(body_c, next_c); this.m_targetArea += b2Vec2.CrossVV(body_c, next_c); djd.Initialize(body, next, body_c, next_c); this.m_joints[i] = body.GetWorld().CreateJoint(djd); } this.m_targetArea *= 0.5; } GetAnchorA(out) { return out; } GetAnchorB(out) { return out; } GetReactionForce(inv_dt, out) { return out; } GetReactionTorque(inv_dt) { return 0; } SetFrequency(hz) { this.m_frequencyHz = hz; for (let i = 0; i < this.m_joints.length; ++i) { this.m_joints[i].SetFrequency(hz); } } GetFrequency() { return this.m_frequencyHz; } SetDampingRatio(ratio) { this.m_dampingRatio = ratio; for (let i = 0; i < this.m_joints.length; ++i) { this.m_joints[i].SetDampingRatio(ratio); } } GetDampingRatio() { return this.m_dampingRatio; } Dump(log) { log("Area joint dumping is not supported.\n"); } InitVelocityConstraints(data) { for (let i = 0; i < this.m_bodies.length; ++i) { const prev = this.m_bodies[(i + this.m_bodies.length - 1) % this.m_bodies.length]; const next = this.m_bodies[(i + 1) % this.m_bodies.length]; const prev_c = data.positions[prev.m_islandIndex].c; const next_c = data.positions[next.m_islandIndex].c; const delta = this.m_deltas[i]; b2Vec2.SubVV(next_c, prev_c, delta); } if (data.step.warmStarting) { this.m_impulse *= data.step.dtRatio; for (let i = 0; i < this.m_bodies.length; ++i) { const body = this.m_bodies[i]; const body_v = data.velocities[body.m_islandIndex].v; const delta = this.m_deltas[i]; body_v.x += body.m_invMass * delta.y * 0.5 * this.m_impulse; body_v.y += body.m_invMass * -delta.x * 0.5 * this.m_impulse; } } else { this.m_impulse = 0; } } SolveVelocityConstraints(data) { let dotMassSum = 0; let crossMassSum = 0; for (let i = 0; i < this.m_bodies.length; ++i) { const body = this.m_bodies[i]; const body_v = data.velocities[body.m_islandIndex].v; const delta = this.m_deltas[i]; dotMassSum += delta.LengthSquared() / body.GetMass(); crossMassSum += b2Vec2.CrossVV(body_v, delta); } const lambda = -2 * crossMassSum / dotMassSum; // lambda = b2Clamp(lambda, -b2_maxLinearCorrection, b2_maxLinearCorrection); this.m_impulse += lambda; for (let i = 0; i < this.m_bodies.length; ++i) { const body = this.m_bodies[i]; const body_v = data.velocities[body.m_islandIndex].v; const delta = this.m_deltas[i]; body_v.x += body.m_invMass * delta.y * 0.5 * lambda; body_v.y += body.m_invMass * -delta.x * 0.5 * lambda; } } SolvePositionConstraints(data) { let perimeter = 0; let area = 0; for (let i = 0; i < this.m_bodies.length; ++i) { const body = this.m_bodies[i]; const next = this.m_bodies[(i + 1) % this.m_bodies.length]; const body_c = data.positions[body.m_islandIndex].c; const next_c = data.positions[next.m_islandIndex].c; const delta = b2Vec2.SubVV(next_c, body_c, this.m_delta); let dist = delta.Length(); if (dist < b2_epsilon) { dist = 1; } this.m_normals[i].x = delta.y / dist; this.m_normals[i].y = -delta.x / dist; perimeter += dist; area += b2Vec2.CrossVV(body_c, next_c); } area *= 0.5; const deltaArea = this.m_targetArea - area; const toExtrude = 0.5 * deltaArea / perimeter; let done = true; for (let i = 0; i < this.m_bodies.length; ++i) { const body = this.m_bodies[i]; const body_c = data.positions[body.m_islandIndex].c; const next_i = (i + 1) % this.m_bodies.length; const delta = b2Vec2.AddVV(this.m_normals[i], this.m_normals[next_i], this.m_delta); delta.SelfMul(toExtrude); const norm_sq = delta.LengthSquared(); if (norm_sq > b2Sq(b2_maxLinearCorrection)) { delta.SelfMul(b2_maxLinearCorrection / b2Sqrt(norm_sq)); } if (norm_sq > b2Sq(b2_linearSlop)) { done = false; } body_c.x += delta.x; body_c.y += delta.y; } return done; } }
JavaScript
class b2FrictionJoint extends b2Joint { constructor(def) { super(def); this.m_localAnchorA = new b2Vec2(); this.m_localAnchorB = new b2Vec2(); // Solver shared this.m_linearImpulse = new b2Vec2(); this.m_angularImpulse = 0; this.m_maxForce = 0; this.m_maxTorque = 0; // Solver temp this.m_indexA = 0; this.m_indexB = 0; this.m_rA = new b2Vec2(); this.m_rB = new b2Vec2(); this.m_localCenterA = new b2Vec2(); this.m_localCenterB = new b2Vec2(); this.m_invMassA = 0; this.m_invMassB = 0; this.m_invIA = 0; this.m_invIB = 0; this.m_linearMass = new b2Mat22(); this.m_angularMass = 0; this.m_qA = new b2Rot(); this.m_qB = new b2Rot(); this.m_lalcA = new b2Vec2(); this.m_lalcB = new b2Vec2(); this.m_K = new b2Mat22(); this.m_localAnchorA.Copy(def.localAnchorA); this.m_localAnchorB.Copy(def.localAnchorB); this.m_linearImpulse.SetZero(); this.m_maxForce = b2Maybe(def.maxForce, 0); this.m_maxTorque = b2Maybe(def.maxTorque, 0); this.m_linearMass.SetZero(); } InitVelocityConstraints(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; // const cA: b2Vec2 = data.positions[this.m_indexA].c; const aA = data.positions[this.m_indexA].a; const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; // const cB: b2Vec2 = data.positions[this.m_indexB].c; const aB = data.positions[this.m_indexB].a; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; // const qA: b2Rot = new b2Rot(aA), qB: b2Rot = new b2Rot(aB); const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); // Compute the effective mass matrix. // m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); const rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); // m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); const rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] const mA = this.m_invMassA, mB = this.m_invMassB; const iA = this.m_invIA, iB = this.m_invIB; const K = this.m_K; // new b2Mat22(); K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; K.GetInverse(this.m_linearMass); this.m_angularMass = iA + iB; if (this.m_angularMass > 0) { this.m_angularMass = 1 / this.m_angularMass; } if (data.step.warmStarting) { // Scale impulses to support a variable time step. // m_linearImpulse *= data.step.dtRatio; this.m_linearImpulse.SelfMul(data.step.dtRatio); this.m_angularImpulse *= data.step.dtRatio; // const P: b2Vec2(m_linearImpulse.x, m_linearImpulse.y); const P = this.m_linearImpulse; // vA -= mA * P; vA.SelfMulSub(mA, P); // wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse); wA -= iA * (b2Vec2.CrossVV(this.m_rA, P) + this.m_angularImpulse); // vB += mB * P; vB.SelfMulAdd(mB, P); // wB += iB * (b2Cross(m_rB, P) + m_angularImpulse); wB += iB * (b2Vec2.CrossVV(this.m_rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.SetZero(); this.m_angularImpulse = 0; } // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolveVelocityConstraints(data) { const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; const mA = this.m_invMassA, mB = this.m_invMassB; const iA = this.m_invIA, iB = this.m_invIB; const h = data.step.dt; // Solve angular friction { const Cdot = wB - wA; let impulse = (-this.m_angularMass * Cdot); const oldImpulse = this.m_angularImpulse; const maxImpulse = h * this.m_maxTorque; this.m_angularImpulse = b2Clamp(this.m_angularImpulse + impulse, (-maxImpulse), maxImpulse); impulse = this.m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve linear friction { // b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); const Cdot_v2 = b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2Vec2.s_t1), b2FrictionJoint.SolveVelocityConstraints_s_Cdot_v2); // b2Vec2 impulse = -b2Mul(m_linearMass, Cdot); const impulseV = b2Mat22.MulMV(this.m_linearMass, Cdot_v2, b2FrictionJoint.SolveVelocityConstraints_s_impulseV).SelfNeg(); // b2Vec2 oldImpulse = m_linearImpulse; const oldImpulseV = b2FrictionJoint.SolveVelocityConstraints_s_oldImpulseV.Copy(this.m_linearImpulse); // m_linearImpulse += impulse; this.m_linearImpulse.SelfAdd(impulseV); const maxImpulse = h * this.m_maxForce; if (this.m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) { this.m_linearImpulse.Normalize(); this.m_linearImpulse.SelfMul(maxImpulse); } // impulse = m_linearImpulse - oldImpulse; b2Vec2.SubVV(this.m_linearImpulse, oldImpulseV, impulseV); // vA -= mA * impulse; vA.SelfMulSub(mA, impulseV); // wA -= iA * b2Cross(m_rA, impulse); wA -= iA * b2Vec2.CrossVV(this.m_rA, impulseV); // vB += mB * impulse; vB.SelfMulAdd(mB, impulseV); // wB += iB * b2Cross(m_rB, impulse); wB += iB * b2Vec2.CrossVV(this.m_rB, impulseV); } // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolvePositionConstraints(data) { return true; } GetAnchorA(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); } GetAnchorB(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); } GetReactionForce(inv_dt, out) { out.x = inv_dt * this.m_linearImpulse.x; out.y = inv_dt * this.m_linearImpulse.y; return out; } GetReactionTorque(inv_dt) { return inv_dt * this.m_angularImpulse; } GetLocalAnchorA() { return this.m_localAnchorA; } GetLocalAnchorB() { return this.m_localAnchorB; } SetMaxForce(force) { this.m_maxForce = force; } GetMaxForce() { return this.m_maxForce; } SetMaxTorque(torque) { this.m_maxTorque = torque; } GetMaxTorque() { return this.m_maxTorque; } Dump(log) { const indexA = this.m_bodyA.m_islandIndex; const indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2FrictionJointDef = new b2FrictionJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", (this.m_collideConnected) ? ("true") : ("false")); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.maxForce = %.15f;\n", this.m_maxForce); log(" jd.maxTorque = %.15f;\n", this.m_maxTorque); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); } }
JavaScript
class b2GearJoint extends b2Joint { constructor(def) { super(def); this.m_typeA = b2JointType.e_unknownJoint; this.m_typeB = b2JointType.e_unknownJoint; // Solver shared this.m_localAnchorA = new b2Vec2(); this.m_localAnchorB = new b2Vec2(); this.m_localAnchorC = new b2Vec2(); this.m_localAnchorD = new b2Vec2(); this.m_localAxisC = new b2Vec2(); this.m_localAxisD = new b2Vec2(); this.m_referenceAngleA = 0; this.m_referenceAngleB = 0; this.m_constant = 0; this.m_ratio = 0; this.m_impulse = 0; // Solver temp this.m_indexA = 0; this.m_indexB = 0; this.m_indexC = 0; this.m_indexD = 0; this.m_lcA = new b2Vec2(); this.m_lcB = new b2Vec2(); this.m_lcC = new b2Vec2(); this.m_lcD = new b2Vec2(); this.m_mA = 0; this.m_mB = 0; this.m_mC = 0; this.m_mD = 0; this.m_iA = 0; this.m_iB = 0; this.m_iC = 0; this.m_iD = 0; this.m_JvAC = new b2Vec2(); this.m_JvBD = new b2Vec2(); this.m_JwA = 0; this.m_JwB = 0; this.m_JwC = 0; this.m_JwD = 0; this.m_mass = 0; this.m_qA = new b2Rot(); this.m_qB = new b2Rot(); this.m_qC = new b2Rot(); this.m_qD = new b2Rot(); this.m_lalcA = new b2Vec2(); this.m_lalcB = new b2Vec2(); this.m_lalcC = new b2Vec2(); this.m_lalcD = new b2Vec2(); this.m_joint1 = def.joint1; this.m_joint2 = def.joint2; this.m_typeA = this.m_joint1.GetType(); this.m_typeB = this.m_joint2.GetType(); // DEBUG: b2Assert(this.m_typeA === b2JointType.e_revoluteJoint || this.m_typeA === b2JointType.e_prismaticJoint); // DEBUG: b2Assert(this.m_typeB === b2JointType.e_revoluteJoint || this.m_typeB === b2JointType.e_prismaticJoint); let coordinateA, coordinateB; // TODO_ERIN there might be some problem with the joint edges in b2Joint. this.m_bodyC = this.m_joint1.GetBodyA(); this.m_bodyA = this.m_joint1.GetBodyB(); // Get geometry of joint1 const xfA = this.m_bodyA.m_xf; const aA = this.m_bodyA.m_sweep.a; const xfC = this.m_bodyC.m_xf; const aC = this.m_bodyC.m_sweep.a; if (this.m_typeA === b2JointType.e_revoluteJoint) { const revolute = def.joint1; this.m_localAnchorC.Copy(revolute.m_localAnchorA); this.m_localAnchorA.Copy(revolute.m_localAnchorB); this.m_referenceAngleA = revolute.m_referenceAngle; this.m_localAxisC.SetZero(); coordinateA = aA - aC - this.m_referenceAngleA; } else { const prismatic = def.joint1; this.m_localAnchorC.Copy(prismatic.m_localAnchorA); this.m_localAnchorA.Copy(prismatic.m_localAnchorB); this.m_referenceAngleA = prismatic.m_referenceAngle; this.m_localAxisC.Copy(prismatic.m_localXAxisA); // b2Vec2 pC = m_localAnchorC; const pC = this.m_localAnchorC; // b2Vec2 pA = b2MulT(xfC.q, b2Mul(xfA.q, m_localAnchorA) + (xfA.p - xfC.p)); const pA = b2Rot.MulTRV(xfC.q, b2Vec2.AddVV(b2Rot.MulRV(xfA.q, this.m_localAnchorA, b2Vec2.s_t0), b2Vec2.SubVV(xfA.p, xfC.p, b2Vec2.s_t1), b2Vec2.s_t0), b2Vec2.s_t0); // pA uses s_t0 // coordinateA = b2Dot(pA - pC, m_localAxisC); coordinateA = b2Vec2.DotVV(b2Vec2.SubVV(pA, pC, b2Vec2.s_t0), this.m_localAxisC); } this.m_bodyD = this.m_joint2.GetBodyA(); this.m_bodyB = this.m_joint2.GetBodyB(); // Get geometry of joint2 const xfB = this.m_bodyB.m_xf; const aB = this.m_bodyB.m_sweep.a; const xfD = this.m_bodyD.m_xf; const aD = this.m_bodyD.m_sweep.a; if (this.m_typeB === b2JointType.e_revoluteJoint) { const revolute = def.joint2; this.m_localAnchorD.Copy(revolute.m_localAnchorA); this.m_localAnchorB.Copy(revolute.m_localAnchorB); this.m_referenceAngleB = revolute.m_referenceAngle; this.m_localAxisD.SetZero(); coordinateB = aB - aD - this.m_referenceAngleB; } else { const prismatic = def.joint2; this.m_localAnchorD.Copy(prismatic.m_localAnchorA); this.m_localAnchorB.Copy(prismatic.m_localAnchorB); this.m_referenceAngleB = prismatic.m_referenceAngle; this.m_localAxisD.Copy(prismatic.m_localXAxisA); // b2Vec2 pD = m_localAnchorD; const pD = this.m_localAnchorD; // b2Vec2 pB = b2MulT(xfD.q, b2Mul(xfB.q, m_localAnchorB) + (xfB.p - xfD.p)); const pB = b2Rot.MulTRV(xfD.q, b2Vec2.AddVV(b2Rot.MulRV(xfB.q, this.m_localAnchorB, b2Vec2.s_t0), b2Vec2.SubVV(xfB.p, xfD.p, b2Vec2.s_t1), b2Vec2.s_t0), b2Vec2.s_t0); // pB uses s_t0 // coordinateB = b2Dot(pB - pD, m_localAxisD); coordinateB = b2Vec2.DotVV(b2Vec2.SubVV(pB, pD, b2Vec2.s_t0), this.m_localAxisD); } this.m_ratio = b2Maybe(def.ratio, 1); this.m_constant = coordinateA + this.m_ratio * coordinateB; this.m_impulse = 0; } InitVelocityConstraints(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_indexC = this.m_bodyC.m_islandIndex; this.m_indexD = this.m_bodyD.m_islandIndex; this.m_lcA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_lcB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_lcC.Copy(this.m_bodyC.m_sweep.localCenter); this.m_lcD.Copy(this.m_bodyD.m_sweep.localCenter); this.m_mA = this.m_bodyA.m_invMass; this.m_mB = this.m_bodyB.m_invMass; this.m_mC = this.m_bodyC.m_invMass; this.m_mD = this.m_bodyD.m_invMass; this.m_iA = this.m_bodyA.m_invI; this.m_iB = this.m_bodyB.m_invI; this.m_iC = this.m_bodyC.m_invI; this.m_iD = this.m_bodyD.m_invI; const aA = data.positions[this.m_indexA].a; const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const aB = data.positions[this.m_indexB].a; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; const aC = data.positions[this.m_indexC].a; const vC = data.velocities[this.m_indexC].v; let wC = data.velocities[this.m_indexC].w; const aD = data.positions[this.m_indexD].a; const vD = data.velocities[this.m_indexD].v; let wD = data.velocities[this.m_indexD].w; // b2Rot qA(aA), qB(aB), qC(aC), qD(aD); const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB), qC = this.m_qC.SetAngle(aC), qD = this.m_qD.SetAngle(aD); this.m_mass = 0; if (this.m_typeA === b2JointType.e_revoluteJoint) { this.m_JvAC.SetZero(); this.m_JwA = 1; this.m_JwC = 1; this.m_mass += this.m_iA + this.m_iC; } else { // b2Vec2 u = b2Mul(qC, m_localAxisC); const u = b2Rot.MulRV(qC, this.m_localAxisC, b2GearJoint.InitVelocityConstraints_s_u); // b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); b2Vec2.SubVV(this.m_localAnchorC, this.m_lcC, this.m_lalcC); const rC = b2Rot.MulRV(qC, this.m_lalcC, b2GearJoint.InitVelocityConstraints_s_rC); // b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); b2Vec2.SubVV(this.m_localAnchorA, this.m_lcA, this.m_lalcA); const rA = b2Rot.MulRV(qA, this.m_lalcA, b2GearJoint.InitVelocityConstraints_s_rA); // m_JvAC = u; this.m_JvAC.Copy(u); // m_JwC = b2Cross(rC, u); this.m_JwC = b2Vec2.CrossVV(rC, u); // m_JwA = b2Cross(rA, u); this.m_JwA = b2Vec2.CrossVV(rA, u); this.m_mass += this.m_mC + this.m_mA + this.m_iC * this.m_JwC * this.m_JwC + this.m_iA * this.m_JwA * this.m_JwA; } if (this.m_typeB === b2JointType.e_revoluteJoint) { this.m_JvBD.SetZero(); this.m_JwB = this.m_ratio; this.m_JwD = this.m_ratio; this.m_mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); } else { // b2Vec2 u = b2Mul(qD, m_localAxisD); const u = b2Rot.MulRV(qD, this.m_localAxisD, b2GearJoint.InitVelocityConstraints_s_u); // b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); b2Vec2.SubVV(this.m_localAnchorD, this.m_lcD, this.m_lalcD); const rD = b2Rot.MulRV(qD, this.m_lalcD, b2GearJoint.InitVelocityConstraints_s_rD); // b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); b2Vec2.SubVV(this.m_localAnchorB, this.m_lcB, this.m_lalcB); const rB = b2Rot.MulRV(qB, this.m_lalcB, b2GearJoint.InitVelocityConstraints_s_rB); // m_JvBD = m_ratio * u; b2Vec2.MulSV(this.m_ratio, u, this.m_JvBD); // m_JwD = m_ratio * b2Cross(rD, u); this.m_JwD = this.m_ratio * b2Vec2.CrossVV(rD, u); // m_JwB = m_ratio * b2Cross(rB, u); this.m_JwB = this.m_ratio * b2Vec2.CrossVV(rB, u); this.m_mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * this.m_JwD * this.m_JwD + this.m_iB * this.m_JwB * this.m_JwB; } // Compute effective mass. this.m_mass = this.m_mass > 0 ? 1 / this.m_mass : 0; if (data.step.warmStarting) { // vA += (m_mA * m_impulse) * m_JvAC; vA.SelfMulAdd(this.m_mA * this.m_impulse, this.m_JvAC); wA += this.m_iA * this.m_impulse * this.m_JwA; // vB += (m_mB * m_impulse) * m_JvBD; vB.SelfMulAdd(this.m_mB * this.m_impulse, this.m_JvBD); wB += this.m_iB * this.m_impulse * this.m_JwB; // vC -= (m_mC * m_impulse) * m_JvAC; vC.SelfMulSub(this.m_mC * this.m_impulse, this.m_JvAC); wC -= this.m_iC * this.m_impulse * this.m_JwC; // vD -= (m_mD * m_impulse) * m_JvBD; vD.SelfMulSub(this.m_mD * this.m_impulse, this.m_JvBD); wD -= this.m_iD * this.m_impulse * this.m_JwD; } else { this.m_impulse = 0; } // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; // data.velocities[this.m_indexC].v = vC; data.velocities[this.m_indexC].w = wC; // data.velocities[this.m_indexD].v = vD; data.velocities[this.m_indexD].w = wD; } SolveVelocityConstraints(data) { const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; const vC = data.velocities[this.m_indexC].v; let wC = data.velocities[this.m_indexC].w; const vD = data.velocities[this.m_indexD].v; let wD = data.velocities[this.m_indexD].w; // float32 Cdot = b2Dot(m_JvAC, vA - vC) + b2Dot(m_JvBD, vB - vD); let Cdot = b2Vec2.DotVV(this.m_JvAC, b2Vec2.SubVV(vA, vC, b2Vec2.s_t0)) + b2Vec2.DotVV(this.m_JvBD, b2Vec2.SubVV(vB, vD, b2Vec2.s_t0)); Cdot += (this.m_JwA * wA - this.m_JwC * wC) + (this.m_JwB * wB - this.m_JwD * wD); const impulse = -this.m_mass * Cdot; this.m_impulse += impulse; // vA += (m_mA * impulse) * m_JvAC; vA.SelfMulAdd((this.m_mA * impulse), this.m_JvAC); wA += this.m_iA * impulse * this.m_JwA; // vB += (m_mB * impulse) * m_JvBD; vB.SelfMulAdd((this.m_mB * impulse), this.m_JvBD); wB += this.m_iB * impulse * this.m_JwB; // vC -= (m_mC * impulse) * m_JvAC; vC.SelfMulSub((this.m_mC * impulse), this.m_JvAC); wC -= this.m_iC * impulse * this.m_JwC; // vD -= (m_mD * impulse) * m_JvBD; vD.SelfMulSub((this.m_mD * impulse), this.m_JvBD); wD -= this.m_iD * impulse * this.m_JwD; // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; // data.velocities[this.m_indexC].v = vC; data.velocities[this.m_indexC].w = wC; // data.velocities[this.m_indexD].v = vD; data.velocities[this.m_indexD].w = wD; } SolvePositionConstraints(data) { const cA = data.positions[this.m_indexA].c; let aA = data.positions[this.m_indexA].a; const cB = data.positions[this.m_indexB].c; let aB = data.positions[this.m_indexB].a; const cC = data.positions[this.m_indexC].c; let aC = data.positions[this.m_indexC].a; const cD = data.positions[this.m_indexD].c; let aD = data.positions[this.m_indexD].a; // b2Rot qA(aA), qB(aB), qC(aC), qD(aD); const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB), qC = this.m_qC.SetAngle(aC), qD = this.m_qD.SetAngle(aD); const linearError = 0; let coordinateA, coordinateB; const JvAC = this.m_JvAC, JvBD = this.m_JvBD; let JwA, JwB, JwC, JwD; let mass = 0; if (this.m_typeA === b2JointType.e_revoluteJoint) { JvAC.SetZero(); JwA = 1; JwC = 1; mass += this.m_iA + this.m_iC; coordinateA = aA - aC - this.m_referenceAngleA; } else { // b2Vec2 u = b2Mul(qC, m_localAxisC); const u = b2Rot.MulRV(qC, this.m_localAxisC, b2GearJoint.SolvePositionConstraints_s_u); // b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); const rC = b2Rot.MulRV(qC, this.m_lalcC, b2GearJoint.SolvePositionConstraints_s_rC); // b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); const rA = b2Rot.MulRV(qA, this.m_lalcA, b2GearJoint.SolvePositionConstraints_s_rA); // JvAC = u; JvAC.Copy(u); // JwC = b2Cross(rC, u); JwC = b2Vec2.CrossVV(rC, u); // JwA = b2Cross(rA, u); JwA = b2Vec2.CrossVV(rA, u); mass += this.m_mC + this.m_mA + this.m_iC * JwC * JwC + this.m_iA * JwA * JwA; // b2Vec2 pC = m_localAnchorC - m_lcC; const pC = this.m_lalcC; // b2Vec2 pA = b2MulT(qC, rA + (cA - cC)); const pA = b2Rot.MulTRV(qC, b2Vec2.AddVV(rA, b2Vec2.SubVV(cA, cC, b2Vec2.s_t0), b2Vec2.s_t0), b2Vec2.s_t0); // pA uses s_t0 // coordinateA = b2Dot(pA - pC, m_localAxisC); coordinateA = b2Vec2.DotVV(b2Vec2.SubVV(pA, pC, b2Vec2.s_t0), this.m_localAxisC); } if (this.m_typeB === b2JointType.e_revoluteJoint) { JvBD.SetZero(); JwB = this.m_ratio; JwD = this.m_ratio; mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); coordinateB = aB - aD - this.m_referenceAngleB; } else { // b2Vec2 u = b2Mul(qD, m_localAxisD); const u = b2Rot.MulRV(qD, this.m_localAxisD, b2GearJoint.SolvePositionConstraints_s_u); // b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); const rD = b2Rot.MulRV(qD, this.m_lalcD, b2GearJoint.SolvePositionConstraints_s_rD); // b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); const rB = b2Rot.MulRV(qB, this.m_lalcB, b2GearJoint.SolvePositionConstraints_s_rB); // JvBD = m_ratio * u; b2Vec2.MulSV(this.m_ratio, u, JvBD); // JwD = m_ratio * b2Cross(rD, u); JwD = this.m_ratio * b2Vec2.CrossVV(rD, u); // JwB = m_ratio * b2Cross(rB, u); JwB = this.m_ratio * b2Vec2.CrossVV(rB, u); mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * JwD * JwD + this.m_iB * JwB * JwB; // b2Vec2 pD = m_localAnchorD - m_lcD; const pD = this.m_lalcD; // b2Vec2 pB = b2MulT(qD, rB + (cB - cD)); const pB = b2Rot.MulTRV(qD, b2Vec2.AddVV(rB, b2Vec2.SubVV(cB, cD, b2Vec2.s_t0), b2Vec2.s_t0), b2Vec2.s_t0); // pB uses s_t0 // coordinateB = b2Dot(pB - pD, m_localAxisD); coordinateB = b2Vec2.DotVV(b2Vec2.SubVV(pB, pD, b2Vec2.s_t0), this.m_localAxisD); } const C = (coordinateA + this.m_ratio * coordinateB) - this.m_constant; let impulse = 0; if (mass > 0) { impulse = -C / mass; } // cA += m_mA * impulse * JvAC; cA.SelfMulAdd(this.m_mA * impulse, JvAC); aA += this.m_iA * impulse * JwA; // cB += m_mB * impulse * JvBD; cB.SelfMulAdd(this.m_mB * impulse, JvBD); aB += this.m_iB * impulse * JwB; // cC -= m_mC * impulse * JvAC; cC.SelfMulSub(this.m_mC * impulse, JvAC); aC -= this.m_iC * impulse * JwC; // cD -= m_mD * impulse * JvBD; cD.SelfMulSub(this.m_mD * impulse, JvBD); aD -= this.m_iD * impulse * JwD; // data.positions[this.m_indexA].c = cA; data.positions[this.m_indexA].a = aA; // data.positions[this.m_indexB].c = cB; data.positions[this.m_indexB].a = aB; // data.positions[this.m_indexC].c = cC; data.positions[this.m_indexC].a = aC; // data.positions[this.m_indexD].c = cD; data.positions[this.m_indexD].a = aD; // TODO_ERIN not implemented return linearError < b2_linearSlop; } GetAnchorA(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); } GetAnchorB(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); } GetReactionForce(inv_dt, out) { // b2Vec2 P = m_impulse * m_JvAC; // return inv_dt * P; return b2Vec2.MulSV(inv_dt * this.m_impulse, this.m_JvAC, out); } GetReactionTorque(inv_dt) { // float32 L = m_impulse * m_JwA; // return inv_dt * L; return inv_dt * this.m_impulse * this.m_JwA; } GetJoint1() { return this.m_joint1; } GetJoint2() { return this.m_joint2; } GetRatio() { return this.m_ratio; } SetRatio(ratio) { // DEBUG: b2Assert(b2IsValid(ratio)); this.m_ratio = ratio; } Dump(log) { const indexA = this.m_bodyA.m_islandIndex; const indexB = this.m_bodyB.m_islandIndex; const index1 = this.m_joint1.m_index; const index2 = this.m_joint2.m_index; log(" const jd: b2GearJointDef = new b2GearJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", (this.m_collideConnected) ? ("true") : ("false")); log(" jd.joint1 = joints[%d];\n", index1); log(" jd.joint2 = joints[%d];\n", index2); log(" jd.ratio = %.15f;\n", this.m_ratio); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); } }
JavaScript
class b2MotorJoint extends b2Joint { constructor(def) { super(def); // Solver shared this.m_linearOffset = new b2Vec2(); this.m_angularOffset = 0; this.m_linearImpulse = new b2Vec2(); this.m_angularImpulse = 0; this.m_maxForce = 0; this.m_maxTorque = 0; this.m_correctionFactor = 0.3; // Solver temp this.m_indexA = 0; this.m_indexB = 0; this.m_rA = new b2Vec2(); this.m_rB = new b2Vec2(); this.m_localCenterA = new b2Vec2(); this.m_localCenterB = new b2Vec2(); this.m_linearError = new b2Vec2(); this.m_angularError = 0; this.m_invMassA = 0; this.m_invMassB = 0; this.m_invIA = 0; this.m_invIB = 0; this.m_linearMass = new b2Mat22(); this.m_angularMass = 0; this.m_qA = new b2Rot(); this.m_qB = new b2Rot(); this.m_K = new b2Mat22(); this.m_linearOffset.Copy(b2Maybe(def.linearOffset, b2Vec2.ZERO)); this.m_linearImpulse.SetZero(); this.m_maxForce = b2Maybe(def.maxForce, 0); this.m_maxTorque = b2Maybe(def.maxTorque, 0); this.m_correctionFactor = b2Maybe(def.correctionFactor, 0.3); } GetAnchorA(out) { const pos = this.m_bodyA.GetPosition(); out.x = pos.x; out.y = pos.y; return out; } GetAnchorB(out) { const pos = this.m_bodyB.GetPosition(); out.x = pos.x; out.y = pos.y; return out; } GetReactionForce(inv_dt, out) { // return inv_dt * m_linearImpulse; return b2Vec2.MulSV(inv_dt, this.m_linearImpulse, out); } GetReactionTorque(inv_dt) { return inv_dt * this.m_angularImpulse; } SetLinearOffset(linearOffset) { if (!b2Vec2.IsEqualToV(linearOffset, this.m_linearOffset)) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_linearOffset.Copy(linearOffset); } } GetLinearOffset() { return this.m_linearOffset; } SetAngularOffset(angularOffset) { if (angularOffset !== this.m_angularOffset) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_angularOffset = angularOffset; } } GetAngularOffset() { return this.m_angularOffset; } SetMaxForce(force) { // DEBUG: b2Assert(b2IsValid(force) && force >= 0); this.m_maxForce = force; } GetMaxForce() { return this.m_maxForce; } SetMaxTorque(torque) { // DEBUG: b2Assert(b2IsValid(torque) && torque >= 0); this.m_maxTorque = torque; } GetMaxTorque() { return this.m_maxTorque; } InitVelocityConstraints(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; const cA = data.positions[this.m_indexA].c; const aA = data.positions[this.m_indexA].a; const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const cB = data.positions[this.m_indexB].c; const aB = data.positions[this.m_indexB].a; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); // Compute the effective mass matrix. // this.m_rA = b2Mul(qA, m_linearOffset - this.m_localCenterA); const rA = b2Rot.MulRV(qA, b2Vec2.SubVV(this.m_linearOffset, this.m_localCenterA, b2Vec2.s_t0), this.m_rA); // this.m_rB = b2Mul(qB, -this.m_localCenterB); const rB = b2Rot.MulRV(qB, b2Vec2.NegV(this.m_localCenterB, b2Vec2.s_t0), this.m_rB); // J = [-I -r1_skew I r2_skew] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] const mA = this.m_invMassA, mB = this.m_invMassB; const iA = this.m_invIA, iB = this.m_invIB; // Upper 2 by 2 of K for point to point const K = this.m_K; K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; // this.m_linearMass = K.GetInverse(); K.GetInverse(this.m_linearMass); this.m_angularMass = iA + iB; if (this.m_angularMass > 0) { this.m_angularMass = 1 / this.m_angularMass; } // this.m_linearError = cB + rB - cA - rA; b2Vec2.SubVV(b2Vec2.AddVV(cB, rB, b2Vec2.s_t0), b2Vec2.AddVV(cA, rA, b2Vec2.s_t1), this.m_linearError); this.m_angularError = aB - aA - this.m_angularOffset; if (data.step.warmStarting) { // Scale impulses to support a variable time step. // this.m_linearImpulse *= data.step.dtRatio; this.m_linearImpulse.SelfMul(data.step.dtRatio); this.m_angularImpulse *= data.step.dtRatio; // b2Vec2 P(this.m_linearImpulse.x, this.m_linearImpulse.y); const P = this.m_linearImpulse; // vA -= mA * P; vA.SelfMulSub(mA, P); wA -= iA * (b2Vec2.CrossVV(rA, P) + this.m_angularImpulse); // vB += mB * P; vB.SelfMulAdd(mB, P); wB += iB * (b2Vec2.CrossVV(rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.SetZero(); this.m_angularImpulse = 0; } // data.velocities[this.m_indexA].v = vA; // vA is a reference data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; // vB is a reference data.velocities[this.m_indexB].w = wB; } SolveVelocityConstraints(data) { const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; const mA = this.m_invMassA, mB = this.m_invMassB; const iA = this.m_invIA, iB = this.m_invIB; const h = data.step.dt; const inv_h = data.step.inv_dt; // Solve angular friction { const Cdot = wB - wA + inv_h * this.m_correctionFactor * this.m_angularError; let impulse = -this.m_angularMass * Cdot; const oldImpulse = this.m_angularImpulse; const maxImpulse = h * this.m_maxTorque; this.m_angularImpulse = b2Clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve linear friction { const rA = this.m_rA; const rB = this.m_rB; // b2Vec2 Cdot = vB + b2Vec2.CrossSV(wB, rB) - vA - b2Vec2.CrossSV(wA, rA) + inv_h * this.m_correctionFactor * this.m_linearError; const Cdot_v2 = b2Vec2.AddVV(b2Vec2.SubVV(b2Vec2.AddVV(vB, b2Vec2.CrossSV(wB, rB, b2Vec2.s_t0), b2Vec2.s_t0), b2Vec2.AddVV(vA, b2Vec2.CrossSV(wA, rA, b2Vec2.s_t1), b2Vec2.s_t1), b2Vec2.s_t2), b2Vec2.MulSV(inv_h * this.m_correctionFactor, this.m_linearError, b2Vec2.s_t3), b2MotorJoint.SolveVelocityConstraints_s_Cdot_v2); // b2Vec2 impulse = -b2Mul(this.m_linearMass, Cdot); const impulse_v2 = b2Mat22.MulMV(this.m_linearMass, Cdot_v2, b2MotorJoint.SolveVelocityConstraints_s_impulse_v2).SelfNeg(); // b2Vec2 oldImpulse = this.m_linearImpulse; const oldImpulse_v2 = b2MotorJoint.SolveVelocityConstraints_s_oldImpulse_v2.Copy(this.m_linearImpulse); // this.m_linearImpulse += impulse; this.m_linearImpulse.SelfAdd(impulse_v2); const maxImpulse = h * this.m_maxForce; if (this.m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) { this.m_linearImpulse.Normalize(); // this.m_linearImpulse *= maxImpulse; this.m_linearImpulse.SelfMul(maxImpulse); } // impulse = this.m_linearImpulse - oldImpulse; b2Vec2.SubVV(this.m_linearImpulse, oldImpulse_v2, impulse_v2); // vA -= mA * impulse; vA.SelfMulSub(mA, impulse_v2); // wA -= iA * b2Vec2.CrossVV(rA, impulse); wA -= iA * b2Vec2.CrossVV(rA, impulse_v2); // vB += mB * impulse; vB.SelfMulAdd(mB, impulse_v2); // wB += iB * b2Vec2.CrossVV(rB, impulse); wB += iB * b2Vec2.CrossVV(rB, impulse_v2); } // data.velocities[this.m_indexA].v = vA; // vA is a reference data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; // vB is a reference data.velocities[this.m_indexB].w = wB; } SolvePositionConstraints(data) { return true; } Dump(log) { const indexA = this.m_bodyA.m_islandIndex; const indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2MotorJointDef = new b2MotorJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", (this.m_collideConnected) ? ("true") : ("false")); log(" jd.linearOffset.Set(%.15f, %.15f);\n", this.m_linearOffset.x, this.m_linearOffset.y); log(" jd.angularOffset = %.15f;\n", this.m_angularOffset); log(" jd.maxForce = %.15f;\n", this.m_maxForce); log(" jd.maxTorque = %.15f;\n", this.m_maxTorque); log(" jd.correctionFactor = %.15f;\n", this.m_correctionFactor); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); } }
JavaScript
class b2MouseJoint extends b2Joint { constructor(def) { super(def); this.m_localAnchorB = new b2Vec2(); this.m_targetA = new b2Vec2(); this.m_frequencyHz = 0; this.m_dampingRatio = 0; this.m_beta = 0; // Solver shared this.m_impulse = new b2Vec2(); this.m_maxForce = 0; this.m_gamma = 0; // Solver temp this.m_indexA = 0; this.m_indexB = 0; this.m_rB = new b2Vec2(); this.m_localCenterB = new b2Vec2(); this.m_invMassB = 0; this.m_invIB = 0; this.m_mass = new b2Mat22(); this.m_C = new b2Vec2(); this.m_qB = new b2Rot(); this.m_lalcB = new b2Vec2(); this.m_K = new b2Mat22(); this.m_targetA.Copy(b2Maybe(def.target, b2Vec2.ZERO)); // DEBUG: b2Assert(this.m_targetA.IsValid()); b2Transform.MulTXV(this.m_bodyB.GetTransform(), this.m_targetA, this.m_localAnchorB); this.m_maxForce = b2Maybe(def.maxForce, 0); // DEBUG: b2Assert(b2IsValid(this.m_maxForce) && this.m_maxForce >= 0); this.m_impulse.SetZero(); this.m_frequencyHz = b2Maybe(def.frequencyHz, 0); // DEBUG: b2Assert(b2IsValid(this.m_frequencyHz) && this.m_frequencyHz >= 0); this.m_dampingRatio = b2Maybe(def.dampingRatio, 0); // DEBUG: b2Assert(b2IsValid(this.m_dampingRatio) && this.m_dampingRatio >= 0); this.m_beta = 0; this.m_gamma = 0; } SetTarget(target) { if (!this.m_bodyB.IsAwake()) { this.m_bodyB.SetAwake(true); } this.m_targetA.Copy(target); } GetTarget() { return this.m_targetA; } SetMaxForce(maxForce) { this.m_maxForce = maxForce; } GetMaxForce() { return this.m_maxForce; } SetFrequency(hz) { this.m_frequencyHz = hz; } GetFrequency() { return this.m_frequencyHz; } SetDampingRatio(ratio) { this.m_dampingRatio = ratio; } GetDampingRatio() { return this.m_dampingRatio; } InitVelocityConstraints(data) { this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIB = this.m_bodyB.m_invI; const cB = data.positions[this.m_indexB].c; const aB = data.positions[this.m_indexB].a; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; const qB = this.m_qB.SetAngle(aB); const mass = this.m_bodyB.GetMass(); // Frequency const omega = 2 * b2_pi * this.m_frequencyHz; // Damping coefficient const d = 2 * mass * this.m_dampingRatio * omega; // Spring stiffness const k = mass * (omega * omega); // magic formulas // gamma has units of inverse mass. // beta has units of inverse time. const h = data.step.dt; // DEBUG: b2Assert(d + h * k > b2_epsilon); this.m_gamma = h * (d + h * k); if (this.m_gamma !== 0) { this.m_gamma = 1 / this.m_gamma; } this.m_beta = h * k * this.m_gamma; // Compute the effective mass matrix. b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y] // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] const K = this.m_K; K.ex.x = this.m_invMassB + this.m_invIB * this.m_rB.y * this.m_rB.y + this.m_gamma; K.ex.y = -this.m_invIB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = this.m_invMassB + this.m_invIB * this.m_rB.x * this.m_rB.x + this.m_gamma; K.GetInverse(this.m_mass); // m_C = cB + m_rB - m_targetA; this.m_C.x = cB.x + this.m_rB.x - this.m_targetA.x; this.m_C.y = cB.y + this.m_rB.y - this.m_targetA.y; // m_C *= m_beta; this.m_C.SelfMul(this.m_beta); // Cheat with some damping wB *= 0.98; if (data.step.warmStarting) { this.m_impulse.SelfMul(data.step.dtRatio); // vB += m_invMassB * m_impulse; vB.x += this.m_invMassB * this.m_impulse.x; vB.y += this.m_invMassB * this.m_impulse.y; wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, this.m_impulse); } else { this.m_impulse.SetZero(); } // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolveVelocityConstraints(data) { const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; // Cdot = v + cross(w, r) // b2Vec2 Cdot = vB + b2Cross(wB, m_rB); const Cdot = b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2MouseJoint.SolveVelocityConstraints_s_Cdot); // b2Vec2 impulse = b2Mul(m_mass, -(Cdot + m_C + m_gamma * m_impulse)); const impulse = b2Mat22.MulMV(this.m_mass, b2Vec2.AddVV(Cdot, b2Vec2.AddVV(this.m_C, b2Vec2.MulSV(this.m_gamma, this.m_impulse, b2Vec2.s_t0), b2Vec2.s_t0), b2Vec2.s_t0).SelfNeg(), b2MouseJoint.SolveVelocityConstraints_s_impulse); // b2Vec2 oldImpulse = m_impulse; const oldImpulse = b2MouseJoint.SolveVelocityConstraints_s_oldImpulse.Copy(this.m_impulse); // m_impulse += impulse; this.m_impulse.SelfAdd(impulse); const maxImpulse = data.step.dt * this.m_maxForce; if (this.m_impulse.LengthSquared() > maxImpulse * maxImpulse) { this.m_impulse.SelfMul(maxImpulse / this.m_impulse.Length()); } // impulse = m_impulse - oldImpulse; b2Vec2.SubVV(this.m_impulse, oldImpulse, impulse); // vB += m_invMassB * impulse; vB.SelfMulAdd(this.m_invMassB, impulse); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, impulse); // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolvePositionConstraints(data) { return true; } GetAnchorA(out) { out.x = this.m_targetA.x; out.y = this.m_targetA.y; return out; } GetAnchorB(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); } GetReactionForce(inv_dt, out) { return b2Vec2.MulSV(inv_dt, this.m_impulse, out); } GetReactionTorque(inv_dt) { return 0; } Dump(log) { log("Mouse joint dumping is not supported.\n"); } ShiftOrigin(newOrigin) { this.m_targetA.SelfSub(newOrigin); } }
JavaScript
class b2PrismaticJoint extends b2Joint { constructor(def) { super(def); // Solver shared this.m_localAnchorA = new b2Vec2(); this.m_localAnchorB = new b2Vec2(); this.m_localXAxisA = new b2Vec2(); this.m_localYAxisA = new b2Vec2(); this.m_referenceAngle = 0; this.m_impulse = new b2Vec3(0, 0, 0); this.m_motorImpulse = 0; this.m_lowerTranslation = 0; this.m_upperTranslation = 0; this.m_maxMotorForce = 0; this.m_motorSpeed = 0; this.m_enableLimit = false; this.m_enableMotor = false; this.m_limitState = b2LimitState.e_inactiveLimit; // Solver temp this.m_indexA = 0; this.m_indexB = 0; this.m_localCenterA = new b2Vec2(); this.m_localCenterB = new b2Vec2(); this.m_invMassA = 0; this.m_invMassB = 0; this.m_invIA = 0; this.m_invIB = 0; this.m_axis = new b2Vec2(0, 0); this.m_perp = new b2Vec2(0, 0); this.m_s1 = 0; this.m_s2 = 0; this.m_a1 = 0; this.m_a2 = 0; this.m_K = new b2Mat33(); this.m_K3 = new b2Mat33(); this.m_K2 = new b2Mat22(); this.m_motorMass = 0; this.m_qA = new b2Rot(); this.m_qB = new b2Rot(); this.m_lalcA = new b2Vec2(); this.m_lalcB = new b2Vec2(); this.m_rA = new b2Vec2(); this.m_rB = new b2Vec2(); this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA, b2Vec2.ZERO)); this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB, b2Vec2.ZERO)); this.m_localXAxisA.Copy(b2Maybe(def.localAxisA, new b2Vec2(1, 0))).SelfNormalize(); b2Vec2.CrossOneV(this.m_localXAxisA, this.m_localYAxisA); this.m_referenceAngle = b2Maybe(def.referenceAngle, 0); this.m_lowerTranslation = b2Maybe(def.lowerTranslation, 0); this.m_upperTranslation = b2Maybe(def.upperTranslation, 0); this.m_maxMotorForce = b2Maybe(def.maxMotorForce, 0); this.m_motorSpeed = b2Maybe(def.motorSpeed, 0); this.m_enableLimit = b2Maybe(def.enableLimit, false); this.m_enableMotor = b2Maybe(def.enableMotor, false); } InitVelocityConstraints(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; const cA = data.positions[this.m_indexA].c; const aA = data.positions[this.m_indexA].a; const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const cB = data.positions[this.m_indexB].c; const aB = data.positions[this.m_indexB].a; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); // Compute the effective masses. // b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); const rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); // b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); const rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); // b2Vec2 d = (cB - cA) + rB - rA; const d = b2Vec2.AddVV(b2Vec2.SubVV(cB, cA, b2Vec2.s_t0), b2Vec2.SubVV(rB, rA, b2Vec2.s_t1), b2PrismaticJoint.InitVelocityConstraints_s_d); const mA = this.m_invMassA, mB = this.m_invMassB; const iA = this.m_invIA, iB = this.m_invIB; // Compute motor Jacobian and effective mass. { // m_axis = b2Mul(qA, m_localXAxisA); b2Rot.MulRV(qA, this.m_localXAxisA, this.m_axis); // m_a1 = b2Cross(d + rA, m_axis); this.m_a1 = b2Vec2.CrossVV(b2Vec2.AddVV(d, rA, b2Vec2.s_t0), this.m_axis); // m_a2 = b2Cross(rB, m_axis); this.m_a2 = b2Vec2.CrossVV(rB, this.m_axis); this.m_motorMass = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } } // Prismatic constraint. { // m_perp = b2Mul(qA, m_localYAxisA); b2Rot.MulRV(qA, this.m_localYAxisA, this.m_perp); // m_s1 = b2Cross(d + rA, m_perp); this.m_s1 = b2Vec2.CrossVV(b2Vec2.AddVV(d, rA, b2Vec2.s_t0), this.m_perp); // m_s2 = b2Cross(rB, m_perp); this.m_s2 = b2Vec2.CrossVV(rB, this.m_perp); // float32 k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2; this.m_K.ex.x = mA + mB + iA * this.m_s1 * this.m_s1 + iB * this.m_s2 * this.m_s2; // float32 k12 = iA * m_s1 + iB * m_s2; this.m_K.ex.y = iA * this.m_s1 + iB * this.m_s2; // float32 k13 = iA * m_s1 * m_a1 + iB * m_s2 * m_a2; this.m_K.ex.z = iA * this.m_s1 * this.m_a1 + iB * this.m_s2 * this.m_a2; this.m_K.ey.x = this.m_K.ex.y; // float32 k22 = iA + iB; this.m_K.ey.y = iA + iB; if (this.m_K.ey.y === 0) { // For bodies with fixed rotation. this.m_K.ey.y = 1; } // float32 k23 = iA * m_a1 + iB * m_a2; this.m_K.ey.z = iA * this.m_a1 + iB * this.m_a2; this.m_K.ez.x = this.m_K.ex.z; this.m_K.ez.y = this.m_K.ey.z; // float32 k33 = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; this.m_K.ez.z = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2; // m_K.ex.Set(k11, k12, k13); // m_K.ey.Set(k12, k22, k23); // m_K.ez.Set(k13, k23, k33); } // Compute motor and limit terms. if (this.m_enableLimit) { // float32 jointTranslation = b2Dot(m_axis, d); const jointTranslation = b2Vec2.DotVV(this.m_axis, d); if (b2Abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * b2_linearSlop) { this.m_limitState = b2LimitState.e_equalLimits; } else if (jointTranslation <= this.m_lowerTranslation) { if (this.m_limitState !== b2LimitState.e_atLowerLimit) { this.m_limitState = b2LimitState.e_atLowerLimit; this.m_impulse.z = 0; } } else if (jointTranslation >= this.m_upperTranslation) { if (this.m_limitState !== b2LimitState.e_atUpperLimit) { this.m_limitState = b2LimitState.e_atUpperLimit; this.m_impulse.z = 0; } } else { this.m_limitState = b2LimitState.e_inactiveLimit; this.m_impulse.z = 0; } } else { this.m_limitState = b2LimitState.e_inactiveLimit; this.m_impulse.z = 0; } if (!this.m_enableMotor) { this.m_motorImpulse = 0; } if (data.step.warmStarting) { // Account for variable time step. // m_impulse *= data.step.dtRatio; this.m_impulse.SelfMul(data.step.dtRatio); this.m_motorImpulse *= data.step.dtRatio; // b2Vec2 P = m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis; const P = b2Vec2.AddVV(b2Vec2.MulSV(this.m_impulse.x, this.m_perp, b2Vec2.s_t0), b2Vec2.MulSV((this.m_motorImpulse + this.m_impulse.z), this.m_axis, b2Vec2.s_t1), b2PrismaticJoint.InitVelocityConstraints_s_P); // float32 LA = m_impulse.x * m_s1 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a1; const LA = this.m_impulse.x * this.m_s1 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a1; // float32 LB = m_impulse.x * m_s2 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a2; const LB = this.m_impulse.x * this.m_s2 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a2; // vA -= mA * P; vA.SelfMulSub(mA, P); wA -= iA * LA; // vB += mB * P; vB.SelfMulAdd(mB, P); wB += iB * LB; } else { this.m_impulse.SetZero(); this.m_motorImpulse = 0; } // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolveVelocityConstraints(data) { const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; const mA = this.m_invMassA, mB = this.m_invMassB; const iA = this.m_invIA, iB = this.m_invIB; // Solve linear motor constraint. if (this.m_enableMotor && this.m_limitState !== b2LimitState.e_equalLimits) { // float32 Cdot = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; const Cdot = b2Vec2.DotVV(this.m_axis, b2Vec2.SubVV(vB, vA, b2Vec2.s_t0)) + this.m_a2 * wB - this.m_a1 * wA; let impulse = this.m_motorMass * (this.m_motorSpeed - Cdot); const oldImpulse = this.m_motorImpulse; const maxImpulse = data.step.dt * this.m_maxMotorForce; this.m_motorImpulse = b2Clamp(this.m_motorImpulse + impulse, (-maxImpulse), maxImpulse); impulse = this.m_motorImpulse - oldImpulse; // b2Vec2 P = impulse * m_axis; const P = b2Vec2.MulSV(impulse, this.m_axis, b2PrismaticJoint.SolveVelocityConstraints_s_P); const LA = impulse * this.m_a1; const LB = impulse * this.m_a2; // vA -= mA * P; vA.SelfMulSub(mA, P); wA -= iA * LA; // vB += mB * P; vB.SelfMulAdd(mB, P); wB += iB * LB; } // b2Vec2 Cdot1; // Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA; const Cdot1_x = b2Vec2.DotVV(this.m_perp, b2Vec2.SubVV(vB, vA, b2Vec2.s_t0)) + this.m_s2 * wB - this.m_s1 * wA; // Cdot1.y = wB - wA; const Cdot1_y = wB - wA; if (this.m_enableLimit && this.m_limitState !== b2LimitState.e_inactiveLimit) { // Solve prismatic and limit constraint in block form. // float32 Cdot2; // Cdot2 = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; const Cdot2 = b2Vec2.DotVV(this.m_axis, b2Vec2.SubVV(vB, vA, b2Vec2.s_t0)) + this.m_a2 * wB - this.m_a1 * wA; // b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); // b2Vec3 f1 = m_impulse; const f1 = b2PrismaticJoint.SolveVelocityConstraints_s_f1.Copy(this.m_impulse); // b2Vec3 df = m_K.Solve33(-Cdot); const df3 = this.m_K.Solve33((-Cdot1_x), (-Cdot1_y), (-Cdot2), b2PrismaticJoint.SolveVelocityConstraints_s_df3); // m_impulse += df; this.m_impulse.SelfAdd(df3); if (this.m_limitState === b2LimitState.e_atLowerLimit) { this.m_impulse.z = b2Max(this.m_impulse.z, 0); } else if (this.m_limitState === b2LimitState.e_atUpperLimit) { this.m_impulse.z = b2Min(this.m_impulse.z, 0); } // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) // b2Vec2 b = -Cdot1 - (m_impulse.z - f1.z) * b2Vec2(m_K.ez.x, m_K.ez.y); const b_x = (-Cdot1_x) - (this.m_impulse.z - f1.z) * this.m_K.ez.x; const b_y = (-Cdot1_y) - (this.m_impulse.z - f1.z) * this.m_K.ez.y; // b2Vec2 f2r = m_K.Solve22(b) + b2Vec2(f1.x, f1.y); const f2r = this.m_K.Solve22(b_x, b_y, b2PrismaticJoint.SolveVelocityConstraints_s_f2r); f2r.x += f1.x; f2r.y += f1.y; // m_impulse.x = f2r.x; this.m_impulse.x = f2r.x; // m_impulse.y = f2r.y; this.m_impulse.y = f2r.y; // df = m_impulse - f1; df3.x = this.m_impulse.x - f1.x; df3.y = this.m_impulse.y - f1.y; df3.z = this.m_impulse.z - f1.z; // b2Vec2 P = df.x * m_perp + df.z * m_axis; const P = b2Vec2.AddVV(b2Vec2.MulSV(df3.x, this.m_perp, b2Vec2.s_t0), b2Vec2.MulSV(df3.z, this.m_axis, b2Vec2.s_t1), b2PrismaticJoint.SolveVelocityConstraints_s_P); // float32 LA = df.x * m_s1 + df.y + df.z * m_a1; const LA = df3.x * this.m_s1 + df3.y + df3.z * this.m_a1; // float32 LB = df.x * m_s2 + df.y + df.z * m_a2; const LB = df3.x * this.m_s2 + df3.y + df3.z * this.m_a2; // vA -= mA * P; vA.SelfMulSub(mA, P); wA -= iA * LA; // vB += mB * P; vB.SelfMulAdd(mB, P); wB += iB * LB; } else { // Limit is inactive, just solve the prismatic constraint in block form. // b2Vec2 df = m_K.Solve22(-Cdot1); const df2 = this.m_K.Solve22((-Cdot1_x), (-Cdot1_y), b2PrismaticJoint.SolveVelocityConstraints_s_df2); this.m_impulse.x += df2.x; this.m_impulse.y += df2.y; // b2Vec2 P = df.x * m_perp; const P = b2Vec2.MulSV(df2.x, this.m_perp, b2PrismaticJoint.SolveVelocityConstraints_s_P); // float32 LA = df.x * m_s1 + df.y; const LA = df2.x * this.m_s1 + df2.y; // float32 LB = df.x * m_s2 + df.y; const LB = df2.x * this.m_s2 + df2.y; // vA -= mA * P; vA.SelfMulSub(mA, P); wA -= iA * LA; // vB += mB * P; vB.SelfMulAdd(mB, P); wB += iB * LB; } // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolvePositionConstraints(data) { const cA = data.positions[this.m_indexA].c; let aA = data.positions[this.m_indexA].a; const cB = data.positions[this.m_indexB].c; let aB = data.positions[this.m_indexB].a; const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); const mA = this.m_invMassA, mB = this.m_invMassB; const iA = this.m_invIA, iB = this.m_invIB; // b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); const rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); // b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); const rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); // b2Vec2 d = cB + rB - cA - rA; const d = b2Vec2.SubVV(b2Vec2.AddVV(cB, rB, b2Vec2.s_t0), b2Vec2.AddVV(cA, rA, b2Vec2.s_t1), b2PrismaticJoint.SolvePositionConstraints_s_d); // b2Vec2 axis = b2Mul(qA, m_localXAxisA); const axis = b2Rot.MulRV(qA, this.m_localXAxisA, this.m_axis); // float32 a1 = b2Cross(d + rA, axis); const a1 = b2Vec2.CrossVV(b2Vec2.AddVV(d, rA, b2Vec2.s_t0), axis); // float32 a2 = b2Cross(rB, axis); const a2 = b2Vec2.CrossVV(rB, axis); // b2Vec2 perp = b2Mul(qA, m_localYAxisA); const perp = b2Rot.MulRV(qA, this.m_localYAxisA, this.m_perp); // float32 s1 = b2Cross(d + rA, perp); const s1 = b2Vec2.CrossVV(b2Vec2.AddVV(d, rA, b2Vec2.s_t0), perp); // float32 s2 = b2Cross(rB, perp); const s2 = b2Vec2.CrossVV(rB, perp); // b2Vec3 impulse; let impulse = b2PrismaticJoint.SolvePositionConstraints_s_impulse; // b2Vec2 C1; // C1.x = b2Dot(perp, d); const C1_x = b2Vec2.DotVV(perp, d); // C1.y = aB - aA - m_referenceAngle; const C1_y = aB - aA - this.m_referenceAngle; let linearError = b2Abs(C1_x); const angularError = b2Abs(C1_y); let active = false; let C2 = 0; if (this.m_enableLimit) { // float32 translation = b2Dot(axis, d); const translation = b2Vec2.DotVV(axis, d); if (b2Abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * b2_linearSlop) { // Prevent large angular corrections C2 = b2Clamp(translation, (-b2_maxLinearCorrection), b2_maxLinearCorrection); linearError = b2Max(linearError, b2Abs(translation)); active = true; } else if (translation <= this.m_lowerTranslation) { // Prevent large linear corrections and allow some slop. C2 = b2Clamp(translation - this.m_lowerTranslation + b2_linearSlop, (-b2_maxLinearCorrection), 0); linearError = b2Max(linearError, this.m_lowerTranslation - translation); active = true; } else if (translation >= this.m_upperTranslation) { // Prevent large linear corrections and allow some slop. C2 = b2Clamp(translation - this.m_upperTranslation - b2_linearSlop, 0, b2_maxLinearCorrection); linearError = b2Max(linearError, translation - this.m_upperTranslation); active = true; } } if (active) { // float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; const k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; // float32 k12 = iA * s1 + iB * s2; const k12 = iA * s1 + iB * s2; // float32 k13 = iA * s1 * a1 + iB * s2 * a2; const k13 = iA * s1 * a1 + iB * s2 * a2; // float32 k22 = iA + iB; let k22 = iA + iB; if (k22 === 0) { // For fixed rotation k22 = 1; } // float32 k23 = iA * a1 + iB * a2; const k23 = iA * a1 + iB * a2; // float32 k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; const k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; // b2Mat33 K; const K = this.m_K3; // K.ex.Set(k11, k12, k13); K.ex.SetXYZ(k11, k12, k13); // K.ey.Set(k12, k22, k23); K.ey.SetXYZ(k12, k22, k23); // K.ez.Set(k13, k23, k33); K.ez.SetXYZ(k13, k23, k33); // b2Vec3 C; // C.x = C1.x; // C.y = C1.y; // C.z = C2; // impulse = K.Solve33(-C); impulse = K.Solve33((-C1_x), (-C1_y), (-C2), impulse); } else { // float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; const k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; // float32 k12 = iA * s1 + iB * s2; const k12 = iA * s1 + iB * s2; // float32 k22 = iA + iB; let k22 = iA + iB; if (k22 === 0) { k22 = 1; } // b2Mat22 K; const K2 = this.m_K2; // K.ex.Set(k11, k12); K2.ex.Set(k11, k12); // K.ey.Set(k12, k22); K2.ey.Set(k12, k22); // b2Vec2 impulse1 = K.Solve(-C1); const impulse1 = K2.Solve((-C1_x), (-C1_y), b2PrismaticJoint.SolvePositionConstraints_s_impulse1); impulse.x = impulse1.x; impulse.y = impulse1.y; impulse.z = 0; } // b2Vec2 P = impulse.x * perp + impulse.z * axis; const P = b2Vec2.AddVV(b2Vec2.MulSV(impulse.x, perp, b2Vec2.s_t0), b2Vec2.MulSV(impulse.z, axis, b2Vec2.s_t1), b2PrismaticJoint.SolvePositionConstraints_s_P); // float32 LA = impulse.x * s1 + impulse.y + impulse.z * a1; const LA = impulse.x * s1 + impulse.y + impulse.z * a1; // float32 LB = impulse.x * s2 + impulse.y + impulse.z * a2; const LB = impulse.x * s2 + impulse.y + impulse.z * a2; // cA -= mA * P; cA.SelfMulSub(mA, P); aA -= iA * LA; // cB += mB * P; cB.SelfMulAdd(mB, P); aB += iB * LB; // data.positions[this.m_indexA].c = cA; data.positions[this.m_indexA].a = aA; // data.positions[this.m_indexB].c = cB; data.positions[this.m_indexB].a = aB; return linearError <= b2_linearSlop && angularError <= b2_angularSlop; } GetAnchorA(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); } GetAnchorB(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); } GetReactionForce(inv_dt, out) { // return inv_dt * (m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis); out.x = inv_dt * (this.m_impulse.x * this.m_perp.x + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis.x); out.y = inv_dt * (this.m_impulse.x * this.m_perp.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis.y); return out; } GetReactionTorque(inv_dt) { return inv_dt * this.m_impulse.y; } GetLocalAnchorA() { return this.m_localAnchorA; } GetLocalAnchorB() { return this.m_localAnchorB; } GetLocalAxisA() { return this.m_localXAxisA; } GetReferenceAngle() { return this.m_referenceAngle; } GetJointTranslation() { // b2Vec2 pA = m_bodyA.GetWorldPoint(m_localAnchorA); const pA = this.m_bodyA.GetWorldPoint(this.m_localAnchorA, b2PrismaticJoint.GetJointTranslation_s_pA); // b2Vec2 pB = m_bodyB.GetWorldPoint(m_localAnchorB); const pB = this.m_bodyB.GetWorldPoint(this.m_localAnchorB, b2PrismaticJoint.GetJointTranslation_s_pB); // b2Vec2 d = pB - pA; const d = b2Vec2.SubVV(pB, pA, b2PrismaticJoint.GetJointTranslation_s_d); // b2Vec2 axis = m_bodyA.GetWorldVector(m_localXAxisA); const axis = this.m_bodyA.GetWorldVector(this.m_localXAxisA, b2PrismaticJoint.GetJointTranslation_s_axis); // float32 translation = b2Dot(d, axis); const translation = b2Vec2.DotVV(d, axis); return translation; } GetJointSpeed() { const bA = this.m_bodyA; const bB = this.m_bodyB; // b2Vec2 rA = b2Mul(bA->m_xf.q, m_localAnchorA - bA->m_sweep.localCenter); b2Vec2.SubVV(this.m_localAnchorA, bA.m_sweep.localCenter, this.m_lalcA); const rA = b2Rot.MulRV(bA.m_xf.q, this.m_lalcA, this.m_rA); // b2Vec2 rB = b2Mul(bB->m_xf.q, m_localAnchorB - bB->m_sweep.localCenter); b2Vec2.SubVV(this.m_localAnchorB, bB.m_sweep.localCenter, this.m_lalcB); const rB = b2Rot.MulRV(bB.m_xf.q, this.m_lalcB, this.m_rB); // b2Vec2 pA = bA->m_sweep.c + rA; const pA = b2Vec2.AddVV(bA.m_sweep.c, rA, b2Vec2.s_t0); // pA uses s_t0 // b2Vec2 pB = bB->m_sweep.c + rB; const pB = b2Vec2.AddVV(bB.m_sweep.c, rB, b2Vec2.s_t1); // pB uses s_t1 // b2Vec2 d = pB - pA; const d = b2Vec2.SubVV(pB, pA, b2Vec2.s_t2); // d uses s_t2 // b2Vec2 axis = b2Mul(bA.m_xf.q, m_localXAxisA); const axis = bA.GetWorldVector(this.m_localXAxisA, this.m_axis); const vA = bA.m_linearVelocity; const vB = bB.m_linearVelocity; const wA = bA.m_angularVelocity; const wB = bB.m_angularVelocity; // float32 speed = b2Dot(d, b2Cross(wA, axis)) + b2Dot(axis, vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA)); const speed = b2Vec2.DotVV(d, b2Vec2.CrossSV(wA, axis, b2Vec2.s_t0)) + b2Vec2.DotVV(axis, b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, rA, b2Vec2.s_t1), b2Vec2.s_t0)); return speed; } IsLimitEnabled() { return this.m_enableLimit; } EnableLimit(flag) { if (flag !== this.m_enableLimit) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_enableLimit = flag; this.m_impulse.z = 0; } } GetLowerLimit() { return this.m_lowerTranslation; } GetUpperLimit() { return this.m_upperTranslation; } SetLimits(lower, upper) { if (lower !== this.m_lowerTranslation || upper !== this.m_upperTranslation) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_lowerTranslation = lower; this.m_upperTranslation = upper; this.m_impulse.z = 0; } } IsMotorEnabled() { return this.m_enableMotor; } EnableMotor(flag) { if (flag !== this.m_enableMotor) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_enableMotor = flag; } } SetMotorSpeed(speed) { if (speed !== this.m_motorSpeed) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_motorSpeed = speed; } } GetMotorSpeed() { return this.m_motorSpeed; } SetMaxMotorForce(force) { if (force !== this.m_maxMotorForce) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_maxMotorForce = force; } } GetMaxMotorForce() { return this.m_maxMotorForce; } GetMotorForce(inv_dt) { return inv_dt * this.m_motorImpulse; } Dump(log) { const indexA = this.m_bodyA.m_islandIndex; const indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2PrismaticJointDef = new b2PrismaticJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", (this.m_collideConnected) ? ("true") : ("false")); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.localAxisA.Set(%.15f, %.15f);\n", this.m_localXAxisA.x, this.m_localXAxisA.y); log(" jd.referenceAngle = %.15f;\n", this.m_referenceAngle); log(" jd.enableLimit = %s;\n", (this.m_enableLimit) ? ("true") : ("false")); log(" jd.lowerTranslation = %.15f;\n", this.m_lowerTranslation); log(" jd.upperTranslation = %.15f;\n", this.m_upperTranslation); log(" jd.enableMotor = %s;\n", (this.m_enableMotor) ? ("true") : ("false")); log(" jd.motorSpeed = %.15f;\n", this.m_motorSpeed); log(" jd.maxMotorForce = %.15f;\n", this.m_maxMotorForce); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); } }
JavaScript
class b2PulleyJoint extends b2Joint { constructor(def) { super(def); this.m_groundAnchorA = new b2Vec2(); this.m_groundAnchorB = new b2Vec2(); this.m_lengthA = 0; this.m_lengthB = 0; // Solver shared this.m_localAnchorA = new b2Vec2(); this.m_localAnchorB = new b2Vec2(); this.m_constant = 0; this.m_ratio = 0; this.m_impulse = 0; // Solver temp this.m_indexA = 0; this.m_indexB = 0; this.m_uA = new b2Vec2(); this.m_uB = new b2Vec2(); this.m_rA = new b2Vec2(); this.m_rB = new b2Vec2(); this.m_localCenterA = new b2Vec2(); this.m_localCenterB = new b2Vec2(); this.m_invMassA = 0; this.m_invMassB = 0; this.m_invIA = 0; this.m_invIB = 0; this.m_mass = 0; this.m_qA = new b2Rot(); this.m_qB = new b2Rot(); this.m_lalcA = new b2Vec2(); this.m_lalcB = new b2Vec2(); this.m_groundAnchorA.Copy(b2Maybe(def.groundAnchorA, new b2Vec2(-1, 1))); this.m_groundAnchorB.Copy(b2Maybe(def.groundAnchorB, new b2Vec2(1, 0))); this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA, new b2Vec2(-1, 0))); this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB, new b2Vec2(1, 0))); this.m_lengthA = b2Maybe(def.lengthA, 0); this.m_lengthB = b2Maybe(def.lengthB, 0); // DEBUG: b2Assert(b2Maybe(def.ratio, 1) !== 0); this.m_ratio = b2Maybe(def.ratio, 1); this.m_constant = b2Maybe(def.lengthA, 0) + this.m_ratio * b2Maybe(def.lengthB, 0); this.m_impulse = 0; } InitVelocityConstraints(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; const cA = data.positions[this.m_indexA].c; const aA = data.positions[this.m_indexA].a; const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const cB = data.positions[this.m_indexB].c; const aB = data.positions[this.m_indexB].a; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; // b2Rot qA(aA), qB(aB); const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); // m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); // m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); // Get the pulley axes. // m_uA = cA + m_rA - m_groundAnchorA; this.m_uA.Copy(cA).SelfAdd(this.m_rA).SelfSub(this.m_groundAnchorA); // m_uB = cB + m_rB - m_groundAnchorB; this.m_uB.Copy(cB).SelfAdd(this.m_rB).SelfSub(this.m_groundAnchorB); const lengthA = this.m_uA.Length(); const lengthB = this.m_uB.Length(); if (lengthA > 10 * b2_linearSlop) { this.m_uA.SelfMul(1 / lengthA); } else { this.m_uA.SetZero(); } if (lengthB > 10 * b2_linearSlop) { this.m_uB.SelfMul(1 / lengthB); } else { this.m_uB.SetZero(); } // Compute effective mass. const ruA = b2Vec2.CrossVV(this.m_rA, this.m_uA); const ruB = b2Vec2.CrossVV(this.m_rB, this.m_uB); const mA = this.m_invMassA + this.m_invIA * ruA * ruA; const mB = this.m_invMassB + this.m_invIB * ruB * ruB; this.m_mass = mA + this.m_ratio * this.m_ratio * mB; if (this.m_mass > 0) { this.m_mass = 1 / this.m_mass; } if (data.step.warmStarting) { // Scale impulses to support variable time steps. this.m_impulse *= data.step.dtRatio; // Warm starting. // b2Vec2 PA = -(m_impulse) * m_uA; const PA = b2Vec2.MulSV(-(this.m_impulse), this.m_uA, b2PulleyJoint.InitVelocityConstraints_s_PA); // b2Vec2 PB = (-m_ratio * m_impulse) * m_uB; const PB = b2Vec2.MulSV((-this.m_ratio * this.m_impulse), this.m_uB, b2PulleyJoint.InitVelocityConstraints_s_PB); // vA += m_invMassA * PA; vA.SelfMulAdd(this.m_invMassA, PA); wA += this.m_invIA * b2Vec2.CrossVV(this.m_rA, PA); // vB += m_invMassB * PB; vB.SelfMulAdd(this.m_invMassB, PB); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, PB); } else { this.m_impulse = 0; } // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolveVelocityConstraints(data) { const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; // b2Vec2 vpA = vA + b2Cross(wA, m_rA); const vpA = b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2PulleyJoint.SolveVelocityConstraints_s_vpA); // b2Vec2 vpB = vB + b2Cross(wB, m_rB); const vpB = b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2PulleyJoint.SolveVelocityConstraints_s_vpB); const Cdot = -b2Vec2.DotVV(this.m_uA, vpA) - this.m_ratio * b2Vec2.DotVV(this.m_uB, vpB); const impulse = -this.m_mass * Cdot; this.m_impulse += impulse; // b2Vec2 PA = -impulse * m_uA; const PA = b2Vec2.MulSV(-impulse, this.m_uA, b2PulleyJoint.SolveVelocityConstraints_s_PA); // b2Vec2 PB = -m_ratio * impulse * m_uB; const PB = b2Vec2.MulSV(-this.m_ratio * impulse, this.m_uB, b2PulleyJoint.SolveVelocityConstraints_s_PB); // vA += m_invMassA * PA; vA.SelfMulAdd(this.m_invMassA, PA); wA += this.m_invIA * b2Vec2.CrossVV(this.m_rA, PA); // vB += m_invMassB * PB; vB.SelfMulAdd(this.m_invMassB, PB); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, PB); // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolvePositionConstraints(data) { const cA = data.positions[this.m_indexA].c; let aA = data.positions[this.m_indexA].a; const cB = data.positions[this.m_indexB].c; let aB = data.positions[this.m_indexB].a; // b2Rot qA(aA), qB(aB); const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); // b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); const rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); // b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); const rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); // Get the pulley axes. // b2Vec2 uA = cA + rA - m_groundAnchorA; const uA = this.m_uA.Copy(cA).SelfAdd(rA).SelfSub(this.m_groundAnchorA); // b2Vec2 uB = cB + rB - m_groundAnchorB; const uB = this.m_uB.Copy(cB).SelfAdd(rB).SelfSub(this.m_groundAnchorB); const lengthA = uA.Length(); const lengthB = uB.Length(); if (lengthA > 10 * b2_linearSlop) { uA.SelfMul(1 / lengthA); } else { uA.SetZero(); } if (lengthB > 10 * b2_linearSlop) { uB.SelfMul(1 / lengthB); } else { uB.SetZero(); } // Compute effective mass. const ruA = b2Vec2.CrossVV(rA, uA); const ruB = b2Vec2.CrossVV(rB, uB); const mA = this.m_invMassA + this.m_invIA * ruA * ruA; const mB = this.m_invMassB + this.m_invIB * ruB * ruB; let mass = mA + this.m_ratio * this.m_ratio * mB; if (mass > 0) { mass = 1 / mass; } const C = this.m_constant - lengthA - this.m_ratio * lengthB; const linearError = b2Abs(C); const impulse = -mass * C; // b2Vec2 PA = -impulse * uA; const PA = b2Vec2.MulSV(-impulse, uA, b2PulleyJoint.SolvePositionConstraints_s_PA); // b2Vec2 PB = -m_ratio * impulse * uB; const PB = b2Vec2.MulSV(-this.m_ratio * impulse, uB, b2PulleyJoint.SolvePositionConstraints_s_PB); // cA += m_invMassA * PA; cA.SelfMulAdd(this.m_invMassA, PA); aA += this.m_invIA * b2Vec2.CrossVV(rA, PA); // cB += m_invMassB * PB; cB.SelfMulAdd(this.m_invMassB, PB); aB += this.m_invIB * b2Vec2.CrossVV(rB, PB); // data.positions[this.m_indexA].c = cA; data.positions[this.m_indexA].a = aA; // data.positions[this.m_indexB].c = cB; data.positions[this.m_indexB].a = aB; return linearError < b2_linearSlop; } GetAnchorA(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); } GetAnchorB(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); } GetReactionForce(inv_dt, out) { // b2Vec2 P = m_impulse * m_uB; // return inv_dt * P; out.x = inv_dt * this.m_impulse * this.m_uB.x; out.y = inv_dt * this.m_impulse * this.m_uB.y; return out; } GetReactionTorque(inv_dt) { return 0; } GetGroundAnchorA() { return this.m_groundAnchorA; } GetGroundAnchorB() { return this.m_groundAnchorB; } GetLengthA() { return this.m_lengthA; } GetLengthB() { return this.m_lengthB; } GetRatio() { return this.m_ratio; } GetCurrentLengthA() { // b2Vec2 p = m_bodyA->GetWorldPoint(m_localAnchorA); // b2Vec2 s = m_groundAnchorA; // b2Vec2 d = p - s; // return d.Length(); const p = this.m_bodyA.GetWorldPoint(this.m_localAnchorA, b2PulleyJoint.GetCurrentLengthA_s_p); const s = this.m_groundAnchorA; return b2Vec2.DistanceVV(p, s); } GetCurrentLengthB() { // b2Vec2 p = m_bodyB->GetWorldPoint(m_localAnchorB); // b2Vec2 s = m_groundAnchorB; // b2Vec2 d = p - s; // return d.Length(); const p = this.m_bodyB.GetWorldPoint(this.m_localAnchorB, b2PulleyJoint.GetCurrentLengthB_s_p); const s = this.m_groundAnchorB; return b2Vec2.DistanceVV(p, s); } Dump(log) { const indexA = this.m_bodyA.m_islandIndex; const indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2PulleyJointDef = new b2PulleyJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", (this.m_collideConnected) ? ("true") : ("false")); log(" jd.groundAnchorA.Set(%.15f, %.15f);\n", this.m_groundAnchorA.x, this.m_groundAnchorA.y); log(" jd.groundAnchorB.Set(%.15f, %.15f);\n", this.m_groundAnchorB.x, this.m_groundAnchorB.y); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.lengthA = %.15f;\n", this.m_lengthA); log(" jd.lengthB = %.15f;\n", this.m_lengthB); log(" jd.ratio = %.15f;\n", this.m_ratio); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); } ShiftOrigin(newOrigin) { this.m_groundAnchorA.SelfSub(newOrigin); this.m_groundAnchorB.SelfSub(newOrigin); } }
JavaScript
class b2RevoluteJoint extends b2Joint { constructor(def) { super(def); // Solver shared this.m_localAnchorA = new b2Vec2(); this.m_localAnchorB = new b2Vec2(); this.m_impulse = new b2Vec3(); this.m_motorImpulse = 0; this.m_enableMotor = false; this.m_maxMotorTorque = 0; this.m_motorSpeed = 0; this.m_enableLimit = false; this.m_referenceAngle = 0; this.m_lowerAngle = 0; this.m_upperAngle = 0; // Solver temp this.m_indexA = 0; this.m_indexB = 0; this.m_rA = new b2Vec2(); this.m_rB = new b2Vec2(); this.m_localCenterA = new b2Vec2(); this.m_localCenterB = new b2Vec2(); this.m_invMassA = 0; this.m_invMassB = 0; this.m_invIA = 0; this.m_invIB = 0; this.m_mass = new b2Mat33(); // effective mass for point-to-point constraint. this.m_motorMass = 0; // effective mass for motor/limit angular constraint. this.m_limitState = b2LimitState.e_inactiveLimit; this.m_qA = new b2Rot(); this.m_qB = new b2Rot(); this.m_lalcA = new b2Vec2(); this.m_lalcB = new b2Vec2(); this.m_K = new b2Mat22(); this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA, b2Vec2.ZERO)); this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB, b2Vec2.ZERO)); this.m_referenceAngle = b2Maybe(def.referenceAngle, 0); this.m_impulse.SetZero(); this.m_motorImpulse = 0; this.m_lowerAngle = b2Maybe(def.lowerAngle, 0); this.m_upperAngle = b2Maybe(def.upperAngle, 0); this.m_maxMotorTorque = b2Maybe(def.maxMotorTorque, 0); this.m_motorSpeed = b2Maybe(def.motorSpeed, 0); this.m_enableLimit = b2Maybe(def.enableLimit, false); this.m_enableMotor = b2Maybe(def.enableMotor, false); this.m_limitState = b2LimitState.e_inactiveLimit; } InitVelocityConstraints(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; const aA = data.positions[this.m_indexA].a; const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const aB = data.positions[this.m_indexB].a; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; // b2Rot qA(aA), qB(aB); const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); // m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); // m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] const mA = this.m_invMassA, mB = this.m_invMassB; const iA = this.m_invIA, iB = this.m_invIB; const fixedRotation = (iA + iB === 0); this.m_mass.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB; this.m_mass.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB; this.m_mass.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB; this.m_mass.ex.y = this.m_mass.ey.x; this.m_mass.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB; this.m_mass.ez.y = this.m_rA.x * iA + this.m_rB.x * iB; this.m_mass.ex.z = this.m_mass.ez.x; this.m_mass.ey.z = this.m_mass.ez.y; this.m_mass.ez.z = iA + iB; this.m_motorMass = iA + iB; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } if (!this.m_enableMotor || fixedRotation) { this.m_motorImpulse = 0; } if (this.m_enableLimit && !fixedRotation) { const jointAngle = aB - aA - this.m_referenceAngle; if (b2Abs(this.m_upperAngle - this.m_lowerAngle) < 2 * b2_angularSlop) { this.m_limitState = b2LimitState.e_equalLimits; } else if (jointAngle <= this.m_lowerAngle) { if (this.m_limitState !== b2LimitState.e_atLowerLimit) { this.m_impulse.z = 0; } this.m_limitState = b2LimitState.e_atLowerLimit; } else if (jointAngle >= this.m_upperAngle) { if (this.m_limitState !== b2LimitState.e_atUpperLimit) { this.m_impulse.z = 0; } this.m_limitState = b2LimitState.e_atUpperLimit; } else { this.m_limitState = b2LimitState.e_inactiveLimit; this.m_impulse.z = 0; } } else { this.m_limitState = b2LimitState.e_inactiveLimit; } if (data.step.warmStarting) { // Scale impulses to support a variable time step. this.m_impulse.SelfMul(data.step.dtRatio); this.m_motorImpulse *= data.step.dtRatio; // b2Vec2 P(m_impulse.x, m_impulse.y); const P = b2RevoluteJoint.InitVelocityConstraints_s_P.Set(this.m_impulse.x, this.m_impulse.y); // vA -= mA * P; vA.SelfMulSub(mA, P); wA -= iA * (b2Vec2.CrossVV(this.m_rA, P) + this.m_motorImpulse + this.m_impulse.z); // vB += mB * P; vB.SelfMulAdd(mB, P); wB += iB * (b2Vec2.CrossVV(this.m_rB, P) + this.m_motorImpulse + this.m_impulse.z); } else { this.m_impulse.SetZero(); this.m_motorImpulse = 0; } // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolveVelocityConstraints(data) { const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; const mA = this.m_invMassA, mB = this.m_invMassB; const iA = this.m_invIA, iB = this.m_invIB; const fixedRotation = (iA + iB === 0); // Solve motor constraint. if (this.m_enableMotor && this.m_limitState !== b2LimitState.e_equalLimits && !fixedRotation) { const Cdot = wB - wA - this.m_motorSpeed; let impulse = -this.m_motorMass * Cdot; const oldImpulse = this.m_motorImpulse; const maxImpulse = data.step.dt * this.m_maxMotorTorque; this.m_motorImpulse = b2Clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve limit constraint. if (this.m_enableLimit && this.m_limitState !== b2LimitState.e_inactiveLimit && !fixedRotation) { // b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); const Cdot1 = b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2Vec2.s_t1), b2RevoluteJoint.SolveVelocityConstraints_s_Cdot1); const Cdot2 = wB - wA; // b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); // b2Vec3 impulse = -this.m_mass.Solve33(Cdot); const impulse_v3 = this.m_mass.Solve33(Cdot1.x, Cdot1.y, Cdot2, b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v3).SelfNeg(); if (this.m_limitState === b2LimitState.e_equalLimits) { this.m_impulse.SelfAdd(impulse_v3); } else if (this.m_limitState === b2LimitState.e_atLowerLimit) { const newImpulse = this.m_impulse.z + impulse_v3.z; if (newImpulse < 0) { // b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); const rhs_x = -Cdot1.x + this.m_impulse.z * this.m_mass.ez.x; const rhs_y = -Cdot1.y + this.m_impulse.z * this.m_mass.ez.y; const reduced_v2 = this.m_mass.Solve22(rhs_x, rhs_y, b2RevoluteJoint.SolveVelocityConstraints_s_reduced_v2); impulse_v3.x = reduced_v2.x; impulse_v3.y = reduced_v2.y; impulse_v3.z = -this.m_impulse.z; this.m_impulse.x += reduced_v2.x; this.m_impulse.y += reduced_v2.y; this.m_impulse.z = 0; } else { this.m_impulse.SelfAdd(impulse_v3); } } else if (this.m_limitState === b2LimitState.e_atUpperLimit) { const newImpulse = this.m_impulse.z + impulse_v3.z; if (newImpulse > 0) { // b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); const rhs_x = -Cdot1.x + this.m_impulse.z * this.m_mass.ez.x; const rhs_y = -Cdot1.y + this.m_impulse.z * this.m_mass.ez.y; const reduced_v2 = this.m_mass.Solve22(rhs_x, rhs_y, b2RevoluteJoint.SolveVelocityConstraints_s_reduced_v2); impulse_v3.x = reduced_v2.x; impulse_v3.y = reduced_v2.y; impulse_v3.z = -this.m_impulse.z; this.m_impulse.x += reduced_v2.x; this.m_impulse.y += reduced_v2.y; this.m_impulse.z = 0; } else { this.m_impulse.SelfAdd(impulse_v3); } } // b2Vec2 P(impulse.x, impulse.y); const P = b2RevoluteJoint.SolveVelocityConstraints_s_P.Set(impulse_v3.x, impulse_v3.y); // vA -= mA * P; vA.SelfMulSub(mA, P); wA -= iA * (b2Vec2.CrossVV(this.m_rA, P) + impulse_v3.z); // vB += mB * P; vB.SelfMulAdd(mB, P); wB += iB * (b2Vec2.CrossVV(this.m_rB, P) + impulse_v3.z); } else { // Solve point-to-point constraint // b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); const Cdot_v2 = b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2Vec2.s_t1), b2RevoluteJoint.SolveVelocityConstraints_s_Cdot_v2); // b2Vec2 impulse = m_mass.Solve22(-Cdot); const impulse_v2 = this.m_mass.Solve22(-Cdot_v2.x, -Cdot_v2.y, b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v2); this.m_impulse.x += impulse_v2.x; this.m_impulse.y += impulse_v2.y; // vA -= mA * impulse; vA.SelfMulSub(mA, impulse_v2); wA -= iA * b2Vec2.CrossVV(this.m_rA, impulse_v2); // vB += mB * impulse; vB.SelfMulAdd(mB, impulse_v2); wB += iB * b2Vec2.CrossVV(this.m_rB, impulse_v2); } // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolvePositionConstraints(data) { const cA = data.positions[this.m_indexA].c; let aA = data.positions[this.m_indexA].a; const cB = data.positions[this.m_indexB].c; let aB = data.positions[this.m_indexB].a; // b2Rot qA(aA), qB(aB); const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); let angularError = 0; let positionError = 0; const fixedRotation = (this.m_invIA + this.m_invIB === 0); // Solve angular limit constraint. if (this.m_enableLimit && this.m_limitState !== b2LimitState.e_inactiveLimit && !fixedRotation) { const angle = aB - aA - this.m_referenceAngle; let limitImpulse = 0; if (this.m_limitState === b2LimitState.e_equalLimits) { // Prevent large angular corrections const C = b2Clamp(angle - this.m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection); limitImpulse = -this.m_motorMass * C; angularError = b2Abs(C); } else if (this.m_limitState === b2LimitState.e_atLowerLimit) { let C = angle - this.m_lowerAngle; angularError = -C; // Prevent large angular corrections and allow some slop. C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0); limitImpulse = -this.m_motorMass * C; } else if (this.m_limitState === b2LimitState.e_atUpperLimit) { let C = angle - this.m_upperAngle; angularError = C; // Prevent large angular corrections and allow some slop. C = b2Clamp(C - b2_angularSlop, 0, b2_maxAngularCorrection); limitImpulse = -this.m_motorMass * C; } aA -= this.m_invIA * limitImpulse; aB += this.m_invIB * limitImpulse; } // Solve point-to-point constraint. { qA.SetAngle(aA); qB.SetAngle(aB); // b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); const rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); // b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); const rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); // b2Vec2 C = cB + rB - cA - rA; const C_v2 = b2Vec2.SubVV(b2Vec2.AddVV(cB, rB, b2Vec2.s_t0), b2Vec2.AddVV(cA, rA, b2Vec2.s_t1), b2RevoluteJoint.SolvePositionConstraints_s_C_v2); // positionError = C.Length(); positionError = C_v2.Length(); const mA = this.m_invMassA, mB = this.m_invMassB; const iA = this.m_invIA, iB = this.m_invIB; const K = this.m_K; K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; // b2Vec2 impulse = -K.Solve(C); const impulse = K.Solve(C_v2.x, C_v2.y, b2RevoluteJoint.SolvePositionConstraints_s_impulse).SelfNeg(); // cA -= mA * impulse; cA.SelfMulSub(mA, impulse); aA -= iA * b2Vec2.CrossVV(rA, impulse); // cB += mB * impulse; cB.SelfMulAdd(mB, impulse); aB += iB * b2Vec2.CrossVV(rB, impulse); } // data.positions[this.m_indexA].c = cA; data.positions[this.m_indexA].a = aA; // data.positions[this.m_indexB].c = cB; data.positions[this.m_indexB].a = aB; return positionError <= b2_linearSlop && angularError <= b2_angularSlop; } GetAnchorA(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); } GetAnchorB(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); } GetReactionForce(inv_dt, out) { // b2Vec2 P(this.m_impulse.x, this.m_impulse.y); // return inv_dt * P; out.x = inv_dt * this.m_impulse.x; out.y = inv_dt * this.m_impulse.y; return out; } GetReactionTorque(inv_dt) { return inv_dt * this.m_impulse.z; } GetLocalAnchorA() { return this.m_localAnchorA; } GetLocalAnchorB() { return this.m_localAnchorB; } GetReferenceAngle() { return this.m_referenceAngle; } GetJointAngle() { // b2Body* bA = this.m_bodyA; // b2Body* bB = this.m_bodyB; // return bB->this.m_sweep.a - bA->this.m_sweep.a - this.m_referenceAngle; return this.m_bodyB.m_sweep.a - this.m_bodyA.m_sweep.a - this.m_referenceAngle; } GetJointSpeed() { // b2Body* bA = this.m_bodyA; // b2Body* bB = this.m_bodyB; // return bB->this.m_angularVelocity - bA->this.m_angularVelocity; return this.m_bodyB.m_angularVelocity - this.m_bodyA.m_angularVelocity; } IsMotorEnabled() { return this.m_enableMotor; } EnableMotor(flag) { if (flag !== this.m_enableMotor) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_enableMotor = flag; } } GetMotorTorque(inv_dt) { return inv_dt * this.m_motorImpulse; } GetMotorSpeed() { return this.m_motorSpeed; } SetMaxMotorTorque(torque) { if (torque !== this.m_maxMotorTorque) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_maxMotorTorque = torque; } } GetMaxMotorTorque() { return this.m_maxMotorTorque; } IsLimitEnabled() { return this.m_enableLimit; } EnableLimit(flag) { if (flag !== this.m_enableLimit) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_enableLimit = flag; this.m_impulse.z = 0; } } GetLowerLimit() { return this.m_lowerAngle; } GetUpperLimit() { return this.m_upperAngle; } SetLimits(lower, upper) { if (lower !== this.m_lowerAngle || upper !== this.m_upperAngle) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_impulse.z = 0; this.m_lowerAngle = lower; this.m_upperAngle = upper; } } SetMotorSpeed(speed) { if (speed !== this.m_motorSpeed) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_motorSpeed = speed; } } Dump(log) { const indexA = this.m_bodyA.m_islandIndex; const indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2RevoluteJointDef = new b2RevoluteJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", (this.m_collideConnected) ? ("true") : ("false")); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.referenceAngle = %.15f;\n", this.m_referenceAngle); log(" jd.enableLimit = %s;\n", (this.m_enableLimit) ? ("true") : ("false")); log(" jd.lowerAngle = %.15f;\n", this.m_lowerAngle); log(" jd.upperAngle = %.15f;\n", this.m_upperAngle); log(" jd.enableMotor = %s;\n", (this.m_enableMotor) ? ("true") : ("false")); log(" jd.motorSpeed = %.15f;\n", this.m_motorSpeed); log(" jd.maxMotorTorque = %.15f;\n", this.m_maxMotorTorque); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); } }
JavaScript
class b2RopeJoint extends b2Joint { constructor(def) { super(def); // Solver shared this.m_localAnchorA = new b2Vec2(); this.m_localAnchorB = new b2Vec2(); this.m_maxLength = 0; this.m_length = 0; this.m_impulse = 0; // Solver temp this.m_indexA = 0; this.m_indexB = 0; this.m_u = new b2Vec2(); this.m_rA = new b2Vec2(); this.m_rB = new b2Vec2(); this.m_localCenterA = new b2Vec2(); this.m_localCenterB = new b2Vec2(); this.m_invMassA = 0; this.m_invMassB = 0; this.m_invIA = 0; this.m_invIB = 0; this.m_mass = 0; this.m_state = b2LimitState.e_inactiveLimit; this.m_qA = new b2Rot(); this.m_qB = new b2Rot(); this.m_lalcA = new b2Vec2(); this.m_lalcB = new b2Vec2(); this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA, new b2Vec2(-1, 0))); this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB, new b2Vec2(1, 0))); this.m_maxLength = b2Maybe(def.maxLength, 0); } InitVelocityConstraints(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; const cA = data.positions[this.m_indexA].c; const aA = data.positions[this.m_indexA].a; const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const cB = data.positions[this.m_indexB].c; const aB = data.positions[this.m_indexB].a; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); // this.m_rA = b2Mul(qA, this.m_localAnchorA - this.m_localCenterA); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); // this.m_rB = b2Mul(qB, this.m_localAnchorB - this.m_localCenterB); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); // this.m_u = cB + this.m_rB - cA - this.m_rA; this.m_u.Copy(cB).SelfAdd(this.m_rB).SelfSub(cA).SelfSub(this.m_rA); this.m_length = this.m_u.Length(); const C = this.m_length - this.m_maxLength; if (C > 0) { this.m_state = b2LimitState.e_atUpperLimit; } else { this.m_state = b2LimitState.e_inactiveLimit; } if (this.m_length > b2_linearSlop) { this.m_u.SelfMul(1 / this.m_length); } else { this.m_u.SetZero(); this.m_mass = 0; this.m_impulse = 0; return; } // Compute effective mass. const crA = b2Vec2.CrossVV(this.m_rA, this.m_u); const crB = b2Vec2.CrossVV(this.m_rB, this.m_u); const invMass = this.m_invMassA + this.m_invIA * crA * crA + this.m_invMassB + this.m_invIB * crB * crB; this.m_mass = invMass !== 0 ? 1 / invMass : 0; if (data.step.warmStarting) { // Scale the impulse to support a variable time step. this.m_impulse *= data.step.dtRatio; // b2Vec2 P = m_impulse * m_u; const P = b2Vec2.MulSV(this.m_impulse, this.m_u, b2RopeJoint.InitVelocityConstraints_s_P); // vA -= m_invMassA * P; vA.SelfMulSub(this.m_invMassA, P); wA -= this.m_invIA * b2Vec2.CrossVV(this.m_rA, P); // vB += m_invMassB * P; vB.SelfMulAdd(this.m_invMassB, P); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, P); } else { this.m_impulse = 0; } // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolveVelocityConstraints(data) { const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; // Cdot = dot(u, v + cross(w, r)) // b2Vec2 vpA = vA + b2Cross(wA, m_rA); const vpA = b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2RopeJoint.SolveVelocityConstraints_s_vpA); // b2Vec2 vpB = vB + b2Cross(wB, m_rB); const vpB = b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2RopeJoint.SolveVelocityConstraints_s_vpB); // float32 C = m_length - m_maxLength; const C = this.m_length - this.m_maxLength; // float32 Cdot = b2Dot(m_u, vpB - vpA); let Cdot = b2Vec2.DotVV(this.m_u, b2Vec2.SubVV(vpB, vpA, b2Vec2.s_t0)); // Predictive constraint. if (C < 0) { Cdot += data.step.inv_dt * C; } let impulse = -this.m_mass * Cdot; const oldImpulse = this.m_impulse; this.m_impulse = b2Min(0, this.m_impulse + impulse); impulse = this.m_impulse - oldImpulse; // b2Vec2 P = impulse * m_u; const P = b2Vec2.MulSV(impulse, this.m_u, b2RopeJoint.SolveVelocityConstraints_s_P); // vA -= m_invMassA * P; vA.SelfMulSub(this.m_invMassA, P); wA -= this.m_invIA * b2Vec2.CrossVV(this.m_rA, P); // vB += m_invMassB * P; vB.SelfMulAdd(this.m_invMassB, P); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, P); // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolvePositionConstraints(data) { const cA = data.positions[this.m_indexA].c; let aA = data.positions[this.m_indexA].a; const cB = data.positions[this.m_indexB].c; let aB = data.positions[this.m_indexB].a; const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); // b2Vec2 rA = b2Mul(qA, this.m_localAnchorA - this.m_localCenterA); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); const rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); // b2Vec2 rB = b2Mul(qB, this.m_localAnchorB - this.m_localCenterB); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); const rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); // b2Vec2 u = cB + rB - cA - rA; const u = this.m_u.Copy(cB).SelfAdd(rB).SelfSub(cA).SelfSub(rA); const length = u.Normalize(); let C = length - this.m_maxLength; C = b2Clamp(C, 0, b2_maxLinearCorrection); const impulse = -this.m_mass * C; // b2Vec2 P = impulse * u; const P = b2Vec2.MulSV(impulse, u, b2RopeJoint.SolvePositionConstraints_s_P); // cA -= m_invMassA * P; cA.SelfMulSub(this.m_invMassA, P); aA -= this.m_invIA * b2Vec2.CrossVV(rA, P); // cB += m_invMassB * P; cB.SelfMulAdd(this.m_invMassB, P); aB += this.m_invIB * b2Vec2.CrossVV(rB, P); // data.positions[this.m_indexA].c = cA; data.positions[this.m_indexA].a = aA; // data.positions[this.m_indexB].c = cB; data.positions[this.m_indexB].a = aB; return length - this.m_maxLength < b2_linearSlop; } GetAnchorA(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); } GetAnchorB(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); } GetReactionForce(inv_dt, out) { // return out.Set(inv_dt * this.m_linearImpulse.x, inv_dt * this.m_linearImpulse.y); return b2Vec2.MulSV((inv_dt * this.m_impulse), this.m_u, out); } GetReactionTorque(inv_dt) { return 0; } GetLocalAnchorA() { return this.m_localAnchorA; } GetLocalAnchorB() { return this.m_localAnchorB; } SetMaxLength(length) { this.m_maxLength = length; } GetMaxLength() { return this.m_maxLength; } GetLimitState() { return this.m_state; } Dump(log) { const indexA = this.m_bodyA.m_islandIndex; const indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2RopeJointDef = new b2RopeJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", (this.m_collideConnected) ? ("true") : ("false")); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.maxLength = %.15f;\n", this.m_maxLength); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); } }
JavaScript
class b2WeldJoint extends b2Joint { constructor(def) { super(def); this.m_frequencyHz = 0; this.m_dampingRatio = 0; this.m_bias = 0; // Solver shared this.m_localAnchorA = new b2Vec2(); this.m_localAnchorB = new b2Vec2(); this.m_referenceAngle = 0; this.m_gamma = 0; this.m_impulse = new b2Vec3(0, 0, 0); // Solver temp this.m_indexA = 0; this.m_indexB = 0; this.m_rA = new b2Vec2(); this.m_rB = new b2Vec2(); this.m_localCenterA = new b2Vec2(); this.m_localCenterB = new b2Vec2(); this.m_invMassA = 0; this.m_invMassB = 0; this.m_invIA = 0; this.m_invIB = 0; this.m_mass = new b2Mat33(); this.m_qA = new b2Rot(); this.m_qB = new b2Rot(); this.m_lalcA = new b2Vec2(); this.m_lalcB = new b2Vec2(); this.m_K = new b2Mat33(); this.m_frequencyHz = b2Maybe(def.frequencyHz, 0); this.m_dampingRatio = b2Maybe(def.dampingRatio, 0); this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA, b2Vec2.ZERO)); this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB, b2Vec2.ZERO)); this.m_referenceAngle = b2Maybe(def.referenceAngle, 0); this.m_impulse.SetZero(); } InitVelocityConstraints(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; const aA = data.positions[this.m_indexA].a; const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const aB = data.positions[this.m_indexB].a; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); // m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); // m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] const mA = this.m_invMassA, mB = this.m_invMassB; const iA = this.m_invIA, iB = this.m_invIB; const K = this.m_K; K.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB; K.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB; K.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB; K.ez.y = this.m_rA.x * iA + this.m_rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0) { K.GetInverse22(this.m_mass); let invM = iA + iB; const m = invM > 0 ? 1 / invM : 0; const C = aB - aA - this.m_referenceAngle; // Frequency const omega = 2 * b2_pi * this.m_frequencyHz; // Damping coefficient const d = 2 * m * this.m_dampingRatio * omega; // Spring stiffness const k = m * omega * omega; // magic formulas const h = data.step.dt; this.m_gamma = h * (d + h * k); this.m_gamma = this.m_gamma !== 0 ? 1 / this.m_gamma : 0; this.m_bias = C * h * k * this.m_gamma; invM += this.m_gamma; this.m_mass.ez.z = invM !== 0 ? 1 / invM : 0; } else { K.GetSymInverse33(this.m_mass); this.m_gamma = 0; this.m_bias = 0; } if (data.step.warmStarting) { // Scale impulses to support a variable time step. this.m_impulse.SelfMul(data.step.dtRatio); // b2Vec2 P(m_impulse.x, m_impulse.y); const P = b2WeldJoint.InitVelocityConstraints_s_P.Set(this.m_impulse.x, this.m_impulse.y); // vA -= mA * P; vA.SelfMulSub(mA, P); wA -= iA * (b2Vec2.CrossVV(this.m_rA, P) + this.m_impulse.z); // vB += mB * P; vB.SelfMulAdd(mB, P); wB += iB * (b2Vec2.CrossVV(this.m_rB, P) + this.m_impulse.z); } else { this.m_impulse.SetZero(); } // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolveVelocityConstraints(data) { const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; const mA = this.m_invMassA, mB = this.m_invMassB; const iA = this.m_invIA, iB = this.m_invIB; if (this.m_frequencyHz > 0) { const Cdot2 = wB - wA; const impulse2 = -this.m_mass.ez.z * (Cdot2 + this.m_bias + this.m_gamma * this.m_impulse.z); this.m_impulse.z += impulse2; wA -= iA * impulse2; wB += iB * impulse2; // b2Vec2 Cdot1 = vB + b2Vec2.CrossSV(wB, this.m_rB) - vA - b2Vec2.CrossSV(wA, this.m_rA); const Cdot1 = b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2Vec2.s_t1), b2WeldJoint.SolveVelocityConstraints_s_Cdot1); // b2Vec2 impulse1 = -b2Mul22(m_mass, Cdot1); const impulse1 = b2Mat33.MulM33XY(this.m_mass, Cdot1.x, Cdot1.y, b2WeldJoint.SolveVelocityConstraints_s_impulse1).SelfNeg(); this.m_impulse.x += impulse1.x; this.m_impulse.y += impulse1.y; // b2Vec2 P = impulse1; const P = impulse1; // vA -= mA * P; vA.SelfMulSub(mA, P); // wA -= iA * b2Cross(m_rA, P); wA -= iA * b2Vec2.CrossVV(this.m_rA, P); // vB += mB * P; vB.SelfMulAdd(mB, P); // wB += iB * b2Cross(m_rB, P); wB += iB * b2Vec2.CrossVV(this.m_rB, P); } else { // b2Vec2 Cdot1 = vB + b2Cross(wB, this.m_rB) - vA - b2Cross(wA, this.m_rA); const Cdot1 = b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2Vec2.s_t1), b2WeldJoint.SolveVelocityConstraints_s_Cdot1); const Cdot2 = wB - wA; // b2Vec3 const Cdot(Cdot1.x, Cdot1.y, Cdot2); // b2Vec3 impulse = -b2Mul(m_mass, Cdot); const impulse = b2Mat33.MulM33XYZ(this.m_mass, Cdot1.x, Cdot1.y, Cdot2, b2WeldJoint.SolveVelocityConstraints_s_impulse).SelfNeg(); this.m_impulse.SelfAdd(impulse); // b2Vec2 P(impulse.x, impulse.y); const P = b2WeldJoint.SolveVelocityConstraints_s_P.Set(impulse.x, impulse.y); // vA -= mA * P; vA.SelfMulSub(mA, P); wA -= iA * (b2Vec2.CrossVV(this.m_rA, P) + impulse.z); // vB += mB * P; vB.SelfMulAdd(mB, P); wB += iB * (b2Vec2.CrossVV(this.m_rB, P) + impulse.z); } // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolvePositionConstraints(data) { const cA = data.positions[this.m_indexA].c; let aA = data.positions[this.m_indexA].a; const cB = data.positions[this.m_indexB].c; let aB = data.positions[this.m_indexB].a; const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); const mA = this.m_invMassA, mB = this.m_invMassB; const iA = this.m_invIA, iB = this.m_invIB; // b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); const rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); // b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); const rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); let positionError, angularError; const K = this.m_K; K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; K.ez.x = -rA.y * iA - rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; K.ez.y = rA.x * iA + rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0) { // b2Vec2 C1 = cB + rB - cA - rA; const C1 = b2Vec2.SubVV(b2Vec2.AddVV(cB, rB, b2Vec2.s_t0), b2Vec2.AddVV(cA, rA, b2Vec2.s_t1), b2WeldJoint.SolvePositionConstraints_s_C1); positionError = C1.Length(); angularError = 0; // b2Vec2 P = -K.Solve22(C1); const P = K.Solve22(C1.x, C1.y, b2WeldJoint.SolvePositionConstraints_s_P).SelfNeg(); // cA -= mA * P; cA.SelfMulSub(mA, P); aA -= iA * b2Vec2.CrossVV(rA, P); // cB += mB * P; cB.SelfMulAdd(mB, P); aB += iB * b2Vec2.CrossVV(rB, P); } else { // b2Vec2 C1 = cB + rB - cA - rA; const C1 = b2Vec2.SubVV(b2Vec2.AddVV(cB, rB, b2Vec2.s_t0), b2Vec2.AddVV(cA, rA, b2Vec2.s_t1), b2WeldJoint.SolvePositionConstraints_s_C1); const C2 = aB - aA - this.m_referenceAngle; positionError = C1.Length(); angularError = b2Abs(C2); // b2Vec3 C(C1.x, C1.y, C2); // b2Vec3 impulse = -K.Solve33(C); const impulse = K.Solve33(C1.x, C1.y, C2, b2WeldJoint.SolvePositionConstraints_s_impulse).SelfNeg(); // b2Vec2 P(impulse.x, impulse.y); const P = b2WeldJoint.SolvePositionConstraints_s_P.Set(impulse.x, impulse.y); // cA -= mA * P; cA.SelfMulSub(mA, P); aA -= iA * (b2Vec2.CrossVV(this.m_rA, P) + impulse.z); // cB += mB * P; cB.SelfMulAdd(mB, P); aB += iB * (b2Vec2.CrossVV(this.m_rB, P) + impulse.z); } // data.positions[this.m_indexA].c = cA; data.positions[this.m_indexA].a = aA; // data.positions[this.m_indexB].c = cB; data.positions[this.m_indexB].a = aB; return positionError <= b2_linearSlop && angularError <= b2_angularSlop; } GetAnchorA(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); } GetAnchorB(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); } GetReactionForce(inv_dt, out) { // b2Vec2 P(this.m_impulse.x, this.m_impulse.y); // return inv_dt * P; out.x = inv_dt * this.m_impulse.x; out.y = inv_dt * this.m_impulse.y; return out; } GetReactionTorque(inv_dt) { return inv_dt * this.m_impulse.z; } GetLocalAnchorA() { return this.m_localAnchorA; } GetLocalAnchorB() { return this.m_localAnchorB; } GetReferenceAngle() { return this.m_referenceAngle; } SetFrequency(hz) { this.m_frequencyHz = hz; } GetFrequency() { return this.m_frequencyHz; } SetDampingRatio(ratio) { this.m_dampingRatio = ratio; } GetDampingRatio() { return this.m_dampingRatio; } Dump(log) { const indexA = this.m_bodyA.m_islandIndex; const indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2WeldJointDef = new b2WeldJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", (this.m_collideConnected) ? ("true") : ("false")); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.referenceAngle = %.15f;\n", this.m_referenceAngle); log(" jd.frequencyHz = %.15f;\n", this.m_frequencyHz); log(" jd.dampingRatio = %.15f;\n", this.m_dampingRatio); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); } }
JavaScript
class b2WheelJoint extends b2Joint { constructor(def) { super(def); this.m_frequencyHz = 0; this.m_dampingRatio = 0; // Solver shared this.m_localAnchorA = new b2Vec2(); this.m_localAnchorB = new b2Vec2(); this.m_localXAxisA = new b2Vec2(); this.m_localYAxisA = new b2Vec2(); this.m_impulse = 0; this.m_motorImpulse = 0; this.m_springImpulse = 0; this.m_maxMotorTorque = 0; this.m_motorSpeed = 0; this.m_enableMotor = false; // Solver temp this.m_indexA = 0; this.m_indexB = 0; this.m_localCenterA = new b2Vec2(); this.m_localCenterB = new b2Vec2(); this.m_invMassA = 0; this.m_invMassB = 0; this.m_invIA = 0; this.m_invIB = 0; this.m_ax = new b2Vec2(); this.m_ay = new b2Vec2(); this.m_sAx = 0; this.m_sBx = 0; this.m_sAy = 0; this.m_sBy = 0; this.m_mass = 0; this.m_motorMass = 0; this.m_springMass = 0; this.m_bias = 0; this.m_gamma = 0; this.m_qA = new b2Rot(); this.m_qB = new b2Rot(); this.m_lalcA = new b2Vec2(); this.m_lalcB = new b2Vec2(); this.m_rA = new b2Vec2(); this.m_rB = new b2Vec2(); this.m_frequencyHz = b2Maybe(def.frequencyHz, 2); this.m_dampingRatio = b2Maybe(def.dampingRatio, 0.7); this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA, b2Vec2.ZERO)); this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB, b2Vec2.ZERO)); this.m_localXAxisA.Copy(b2Maybe(def.localAxisA, b2Vec2.UNITX)); b2Vec2.CrossOneV(this.m_localXAxisA, this.m_localYAxisA); this.m_maxMotorTorque = b2Maybe(def.maxMotorTorque, 0); this.m_motorSpeed = b2Maybe(def.motorSpeed, 0); this.m_enableMotor = b2Maybe(def.enableMotor, false); this.m_ax.SetZero(); this.m_ay.SetZero(); } GetMotorSpeed() { return this.m_motorSpeed; } GetMaxMotorTorque() { return this.m_maxMotorTorque; } SetSpringFrequencyHz(hz) { this.m_frequencyHz = hz; } GetSpringFrequencyHz() { return this.m_frequencyHz; } SetSpringDampingRatio(ratio) { this.m_dampingRatio = ratio; } GetSpringDampingRatio() { return this.m_dampingRatio; } InitVelocityConstraints(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; const mA = this.m_invMassA, mB = this.m_invMassB; const iA = this.m_invIA, iB = this.m_invIB; const cA = data.positions[this.m_indexA].c; const aA = data.positions[this.m_indexA].a; const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const cB = data.positions[this.m_indexB].c; const aB = data.positions[this.m_indexB].a; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); // Compute the effective masses. // b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); const rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); // b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); const rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); // b2Vec2 d = cB + rB - cA - rA; const d = b2Vec2.SubVV(b2Vec2.AddVV(cB, rB, b2Vec2.s_t0), b2Vec2.AddVV(cA, rA, b2Vec2.s_t1), b2WheelJoint.InitVelocityConstraints_s_d); // Point to line constraint { // m_ay = b2Mul(qA, m_localYAxisA); b2Rot.MulRV(qA, this.m_localYAxisA, this.m_ay); // m_sAy = b2Cross(d + rA, m_ay); this.m_sAy = b2Vec2.CrossVV(b2Vec2.AddVV(d, rA, b2Vec2.s_t0), this.m_ay); // m_sBy = b2Cross(rB, m_ay); this.m_sBy = b2Vec2.CrossVV(rB, this.m_ay); this.m_mass = mA + mB + iA * this.m_sAy * this.m_sAy + iB * this.m_sBy * this.m_sBy; if (this.m_mass > 0) { this.m_mass = 1 / this.m_mass; } } // Spring constraint this.m_springMass = 0; this.m_bias = 0; this.m_gamma = 0; if (this.m_frequencyHz > 0) { // m_ax = b2Mul(qA, m_localXAxisA); b2Rot.MulRV(qA, this.m_localXAxisA, this.m_ax); // m_sAx = b2Cross(d + rA, m_ax); this.m_sAx = b2Vec2.CrossVV(b2Vec2.AddVV(d, rA, b2Vec2.s_t0), this.m_ax); // m_sBx = b2Cross(rB, m_ax); this.m_sBx = b2Vec2.CrossVV(rB, this.m_ax); const invMass = mA + mB + iA * this.m_sAx * this.m_sAx + iB * this.m_sBx * this.m_sBx; if (invMass > 0) { this.m_springMass = 1 / invMass; const C = b2Vec2.DotVV(d, this.m_ax); // Frequency const omega = 2 * b2_pi * this.m_frequencyHz; // Damping coefficient const damp = 2 * this.m_springMass * this.m_dampingRatio * omega; // Spring stiffness const k = this.m_springMass * omega * omega; // magic formulas const h = data.step.dt; this.m_gamma = h * (damp + h * k); if (this.m_gamma > 0) { this.m_gamma = 1 / this.m_gamma; } this.m_bias = C * h * k * this.m_gamma; this.m_springMass = invMass + this.m_gamma; if (this.m_springMass > 0) { this.m_springMass = 1 / this.m_springMass; } } } else { this.m_springImpulse = 0; } // Rotational motor if (this.m_enableMotor) { this.m_motorMass = iA + iB; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } } else { this.m_motorMass = 0; this.m_motorImpulse = 0; } if (data.step.warmStarting) { // Account for variable time step. this.m_impulse *= data.step.dtRatio; this.m_springImpulse *= data.step.dtRatio; this.m_motorImpulse *= data.step.dtRatio; // b2Vec2 P = m_impulse * m_ay + m_springImpulse * m_ax; const P = b2Vec2.AddVV(b2Vec2.MulSV(this.m_impulse, this.m_ay, b2Vec2.s_t0), b2Vec2.MulSV(this.m_springImpulse, this.m_ax, b2Vec2.s_t1), b2WheelJoint.InitVelocityConstraints_s_P); // float32 LA = m_impulse * m_sAy + m_springImpulse * m_sAx + m_motorImpulse; const LA = this.m_impulse * this.m_sAy + this.m_springImpulse * this.m_sAx + this.m_motorImpulse; // float32 LB = m_impulse * m_sBy + m_springImpulse * m_sBx + m_motorImpulse; const LB = this.m_impulse * this.m_sBy + this.m_springImpulse * this.m_sBx + this.m_motorImpulse; // vA -= m_invMassA * P; vA.SelfMulSub(this.m_invMassA, P); wA -= this.m_invIA * LA; // vB += m_invMassB * P; vB.SelfMulAdd(this.m_invMassB, P); wB += this.m_invIB * LB; } else { this.m_impulse = 0; this.m_springImpulse = 0; this.m_motorImpulse = 0; } // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolveVelocityConstraints(data) { const mA = this.m_invMassA, mB = this.m_invMassB; const iA = this.m_invIA, iB = this.m_invIB; const vA = data.velocities[this.m_indexA].v; let wA = data.velocities[this.m_indexA].w; const vB = data.velocities[this.m_indexB].v; let wB = data.velocities[this.m_indexB].w; // Solve spring constraint { const Cdot = b2Vec2.DotVV(this.m_ax, b2Vec2.SubVV(vB, vA, b2Vec2.s_t0)) + this.m_sBx * wB - this.m_sAx * wA; const impulse = -this.m_springMass * (Cdot + this.m_bias + this.m_gamma * this.m_springImpulse); this.m_springImpulse += impulse; // b2Vec2 P = impulse * m_ax; const P = b2Vec2.MulSV(impulse, this.m_ax, b2WheelJoint.SolveVelocityConstraints_s_P); const LA = impulse * this.m_sAx; const LB = impulse * this.m_sBx; // vA -= mA * P; vA.SelfMulSub(mA, P); wA -= iA * LA; // vB += mB * P; vB.SelfMulAdd(mB, P); wB += iB * LB; } // Solve rotational motor constraint { const Cdot = wB - wA - this.m_motorSpeed; let impulse = -this.m_motorMass * Cdot; const oldImpulse = this.m_motorImpulse; const maxImpulse = data.step.dt * this.m_maxMotorTorque; this.m_motorImpulse = b2Clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve point to line constraint { const Cdot = b2Vec2.DotVV(this.m_ay, b2Vec2.SubVV(vB, vA, b2Vec2.s_t0)) + this.m_sBy * wB - this.m_sAy * wA; const impulse = -this.m_mass * Cdot; this.m_impulse += impulse; // b2Vec2 P = impulse * m_ay; const P = b2Vec2.MulSV(impulse, this.m_ay, b2WheelJoint.SolveVelocityConstraints_s_P); const LA = impulse * this.m_sAy; const LB = impulse * this.m_sBy; // vA -= mA * P; vA.SelfMulSub(mA, P); wA -= iA * LA; // vB += mB * P; vB.SelfMulAdd(mB, P); wB += iB * LB; } // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } SolvePositionConstraints(data) { const cA = data.positions[this.m_indexA].c; let aA = data.positions[this.m_indexA].a; const cB = data.positions[this.m_indexB].c; let aB = data.positions[this.m_indexB].a; const qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); // b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); const rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); // b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); const rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); // b2Vec2 d = (cB - cA) + rB - rA; const d = b2Vec2.AddVV(b2Vec2.SubVV(cB, cA, b2Vec2.s_t0), b2Vec2.SubVV(rB, rA, b2Vec2.s_t1), b2WheelJoint.SolvePositionConstraints_s_d); // b2Vec2 ay = b2Mul(qA, m_localYAxisA); const ay = b2Rot.MulRV(qA, this.m_localYAxisA, this.m_ay); // float32 sAy = b2Cross(d + rA, ay); const sAy = b2Vec2.CrossVV(b2Vec2.AddVV(d, rA, b2Vec2.s_t0), ay); // float32 sBy = b2Cross(rB, ay); const sBy = b2Vec2.CrossVV(rB, ay); // float32 C = b2Dot(d, ay); const C = b2Vec2.DotVV(d, this.m_ay); const k = this.m_invMassA + this.m_invMassB + this.m_invIA * this.m_sAy * this.m_sAy + this.m_invIB * this.m_sBy * this.m_sBy; let impulse; if (k !== 0) { impulse = -C / k; } else { impulse = 0; } // b2Vec2 P = impulse * ay; const P = b2Vec2.MulSV(impulse, ay, b2WheelJoint.SolvePositionConstraints_s_P); const LA = impulse * sAy; const LB = impulse * sBy; // cA -= m_invMassA * P; cA.SelfMulSub(this.m_invMassA, P); aA -= this.m_invIA * LA; // cB += m_invMassB * P; cB.SelfMulAdd(this.m_invMassB, P); aB += this.m_invIB * LB; // data.positions[this.m_indexA].c = cA; data.positions[this.m_indexA].a = aA; // data.positions[this.m_indexB].c = cB; data.positions[this.m_indexB].a = aB; return b2Abs(C) <= b2_linearSlop; } GetDefinition(def) { // DEBUG: b2Assert(false); // TODO return def; } GetAnchorA(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); } GetAnchorB(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); } GetReactionForce(inv_dt, out) { // return inv_dt * (m_impulse * m_ay + m_springImpulse * m_ax); out.x = inv_dt * (this.m_impulse * this.m_ay.x + this.m_springImpulse * this.m_ax.x); out.y = inv_dt * (this.m_impulse * this.m_ay.y + this.m_springImpulse * this.m_ax.y); return out; } GetReactionTorque(inv_dt) { return inv_dt * this.m_motorImpulse; } GetLocalAnchorA() { return this.m_localAnchorA; } GetLocalAnchorB() { return this.m_localAnchorB; } GetLocalAxisA() { return this.m_localXAxisA; } GetJointTranslation() { return this.GetPrismaticJointTranslation(); } GetJointLinearSpeed() { return this.GetPrismaticJointSpeed(); } GetJointAngle() { return this.GetRevoluteJointAngle(); } GetJointAngularSpeed() { return this.GetRevoluteJointSpeed(); } GetPrismaticJointTranslation() { const bA = this.m_bodyA; const bB = this.m_bodyB; const pA = bA.GetWorldPoint(this.m_localAnchorA, new b2Vec2()); const pB = bB.GetWorldPoint(this.m_localAnchorB, new b2Vec2()); const d = b2Vec2.SubVV(pB, pA, new b2Vec2()); const axis = bA.GetWorldVector(this.m_localXAxisA, new b2Vec2()); const translation = b2Vec2.DotVV(d, axis); return translation; } GetPrismaticJointSpeed() { const bA = this.m_bodyA; const bB = this.m_bodyB; // b2Vec2 rA = b2Mul(bA->m_xf.q, m_localAnchorA - bA->m_sweep.localCenter); b2Vec2.SubVV(this.m_localAnchorA, bA.m_sweep.localCenter, this.m_lalcA); const rA = b2Rot.MulRV(bA.m_xf.q, this.m_lalcA, this.m_rA); // b2Vec2 rB = b2Mul(bB->m_xf.q, m_localAnchorB - bB->m_sweep.localCenter); b2Vec2.SubVV(this.m_localAnchorB, bB.m_sweep.localCenter, this.m_lalcB); const rB = b2Rot.MulRV(bB.m_xf.q, this.m_lalcB, this.m_rB); // b2Vec2 pA = bA->m_sweep.c + rA; const pA = b2Vec2.AddVV(bA.m_sweep.c, rA, b2Vec2.s_t0); // pA uses s_t0 // b2Vec2 pB = bB->m_sweep.c + rB; const pB = b2Vec2.AddVV(bB.m_sweep.c, rB, b2Vec2.s_t1); // pB uses s_t1 // b2Vec2 d = pB - pA; const d = b2Vec2.SubVV(pB, pA, b2Vec2.s_t2); // d uses s_t2 // b2Vec2 axis = b2Mul(bA.m_xf.q, m_localXAxisA); const axis = bA.GetWorldVector(this.m_localXAxisA, new b2Vec2()); const vA = bA.m_linearVelocity; const vB = bB.m_linearVelocity; const wA = bA.m_angularVelocity; const wB = bB.m_angularVelocity; // float32 speed = b2Dot(d, b2Cross(wA, axis)) + b2Dot(axis, vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA)); const speed = b2Vec2.DotVV(d, b2Vec2.CrossSV(wA, axis, b2Vec2.s_t0)) + b2Vec2.DotVV(axis, b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, rA, b2Vec2.s_t1), b2Vec2.s_t0)); return speed; } GetRevoluteJointAngle() { // b2Body* bA = this.m_bodyA; // b2Body* bB = this.m_bodyB; // return bB->this.m_sweep.a - bA->this.m_sweep.a; return this.m_bodyB.m_sweep.a - this.m_bodyA.m_sweep.a; } GetRevoluteJointSpeed() { const wA = this.m_bodyA.m_angularVelocity; const wB = this.m_bodyB.m_angularVelocity; return wB - wA; } IsMotorEnabled() { return this.m_enableMotor; } EnableMotor(flag) { if (flag !== this.m_enableMotor) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_enableMotor = flag; } } SetMotorSpeed(speed) { if (speed !== this.m_motorSpeed) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_motorSpeed = speed; } } SetMaxMotorTorque(force) { if (force !== this.m_maxMotorTorque) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_maxMotorTorque = force; } } GetMotorTorque(inv_dt) { return inv_dt * this.m_motorImpulse; } Dump(log) { const indexA = this.m_bodyA.m_islandIndex; const indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2WheelJointDef = new b2WheelJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", (this.m_collideConnected) ? ("true") : ("false")); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.localAxisA.Set(%.15f, %.15f);\n", this.m_localXAxisA.x, this.m_localXAxisA.y); log(" jd.enableMotor = %s;\n", (this.m_enableMotor) ? ("true") : ("false")); log(" jd.motorSpeed = %.15f;\n", this.m_motorSpeed); log(" jd.maxMotorTorque = %.15f;\n", this.m_maxMotorTorque); log(" jd.frequencyHz = %.15f;\n", this.m_frequencyHz); log(" jd.dampingRatio = %.15f;\n", this.m_dampingRatio); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); } }
JavaScript
class b2CircleContact extends b2Contact { constructor() { super(); } static Create(allocator) { return new b2CircleContact(); } static Destroy(contact, allocator) { } Reset(fixtureA, indexA, fixtureB, indexB) { super.Reset(fixtureA, indexA, fixtureB, indexB); } Evaluate(manifold, xfA, xfB) { const shapeA = this.m_fixtureA.GetShape(); const shapeB = this.m_fixtureB.GetShape(); // DEBUG: b2Assert(shapeA.GetType() === b2ShapeType.e_circleShape); // DEBUG: b2Assert(shapeB.GetType() === b2ShapeType.e_circleShape); b2CollideCircles(manifold, shapeA, xfA, shapeB, xfB); } }
JavaScript
class b2PolygonContact extends b2Contact { constructor() { super(); } static Create(allocator) { return new b2PolygonContact(); } static Destroy(contact, allocator) { } Reset(fixtureA, indexA, fixtureB, indexB) { super.Reset(fixtureA, indexA, fixtureB, indexB); } Evaluate(manifold, xfA, xfB) { const shapeA = this.m_fixtureA.GetShape(); const shapeB = this.m_fixtureB.GetShape(); // DEBUG: b2Assert(shapeA.GetType() === b2ShapeType.e_polygonShape); // DEBUG: b2Assert(shapeB.GetType() === b2ShapeType.e_polygonShape); b2CollidePolygons(manifold, shapeA, xfA, shapeB, xfB); } }
JavaScript
class b2PolygonAndCircleContact extends b2Contact { constructor() { super(); } static Create(allocator) { return new b2PolygonAndCircleContact(); } static Destroy(contact, allocator) { } Reset(fixtureA, indexA, fixtureB, indexB) { super.Reset(fixtureA, indexA, fixtureB, indexB); // DEBUG: b2Assert(fixtureA.GetType() === b2ShapeType.e_polygonShape); // DEBUG: b2Assert(fixtureB.GetType() === b2ShapeType.e_circleShape); } Evaluate(manifold, xfA, xfB) { const shapeA = this.m_fixtureA.GetShape(); const shapeB = this.m_fixtureB.GetShape(); // DEBUG: b2Assert(shapeA instanceof b2PolygonShape); // DEBUG: b2Assert(shapeB instanceof b2CircleShape); b2CollidePolygonAndCircle(manifold, shapeA, xfA, shapeB, xfB); } }
JavaScript
class b2EdgeAndCircleContact extends b2Contact { constructor() { super(); } static Create(allocator) { return new b2EdgeAndCircleContact(); } static Destroy(contact, allocator) { } Reset(fixtureA, indexA, fixtureB, indexB) { super.Reset(fixtureA, indexA, fixtureB, indexB); // DEBUG: b2Assert(fixtureA.GetType() === b2ShapeType.e_edgeShape); // DEBUG: b2Assert(fixtureB.GetType() === b2ShapeType.e_circleShape); } Evaluate(manifold, xfA, xfB) { const shapeA = this.m_fixtureA.GetShape(); const shapeB = this.m_fixtureB.GetShape(); // DEBUG: b2Assert(shapeA instanceof b2EdgeShape); // DEBUG: b2Assert(shapeB instanceof b2CircleShape); b2CollideEdgeAndCircle(manifold, shapeA, xfA, shapeB, xfB); } }
JavaScript
class b2EdgeAndPolygonContact extends b2Contact { constructor() { super(); } static Create(allocator) { return new b2EdgeAndPolygonContact(); } static Destroy(contact, allocator) { } Reset(fixtureA, indexA, fixtureB, indexB) { super.Reset(fixtureA, indexA, fixtureB, indexB); // DEBUG: b2Assert(fixtureA.GetType() === b2ShapeType.e_edgeShape); // DEBUG: b2Assert(fixtureB.GetType() === b2ShapeType.e_polygonShape); } Evaluate(manifold, xfA, xfB) { const shapeA = this.m_fixtureA.GetShape(); const shapeB = this.m_fixtureB.GetShape(); // DEBUG: b2Assert(shapeA instanceof b2EdgeShape); // DEBUG: b2Assert(shapeB instanceof b2PolygonShape); b2CollideEdgeAndPolygon(manifold, shapeA, xfA, shapeB, xfB); } }
JavaScript
class b2ChainAndCircleContact extends b2Contact { constructor() { super(); } static Create(allocator) { return new b2ChainAndCircleContact(); } static Destroy(contact, allocator) { } Reset(fixtureA, indexA, fixtureB, indexB) { super.Reset(fixtureA, indexA, fixtureB, indexB); // DEBUG: b2Assert(fixtureA.GetType() === b2ShapeType.e_chainShape); // DEBUG: b2Assert(fixtureB.GetType() === b2ShapeType.e_circleShape); } Evaluate(manifold, xfA, xfB) { const shapeA = this.m_fixtureA.GetShape(); const shapeB = this.m_fixtureB.GetShape(); // DEBUG: b2Assert(shapeA instanceof b2ChainShape); // DEBUG: b2Assert(shapeB instanceof b2CircleShape); const chain = shapeA; const edge = b2ChainAndCircleContact.Evaluate_s_edge; chain.GetChildEdge(edge, this.m_indexA); b2CollideEdgeAndCircle(manifold, edge, xfA, shapeB, xfB); } }
JavaScript
class b2ChainAndPolygonContact extends b2Contact { constructor() { super(); } static Create(allocator) { return new b2ChainAndPolygonContact(); } static Destroy(contact, allocator) { } Reset(fixtureA, indexA, fixtureB, indexB) { super.Reset(fixtureA, indexA, fixtureB, indexB); // DEBUG: b2Assert(fixtureA.GetType() === b2ShapeType.e_chainShape); // DEBUG: b2Assert(fixtureB.GetType() === b2ShapeType.e_polygonShape); } Evaluate(manifold, xfA, xfB) { const shapeA = this.m_fixtureA.GetShape(); const shapeB = this.m_fixtureB.GetShape(); // DEBUG: b2Assert(shapeA instanceof b2ChainShape); // DEBUG: b2Assert(shapeB instanceof b2PolygonShape); const chain = shapeA; const edge = b2ChainAndPolygonContact.Evaluate_s_edge; chain.GetChildEdge(edge, this.m_indexA); b2CollideEdgeAndPolygon(manifold, edge, xfA, shapeB, xfB); } }
JavaScript
class b2ContactRegister { constructor() { // public pool: b2Contact[]; this.createFcn = null; this.destroyFcn = null; this.primary = false; } }
JavaScript
class b2ContactFilter { /// Return true if contact calculations should be performed between these two shapes. /// @warning for performance reasons this is only called when the AABBs begin to overlap. ShouldCollide(fixtureA, fixtureB) { const bodyA = fixtureA.GetBody(); const bodyB = fixtureB.GetBody(); // At least one body should be dynamic or kinematic. if (bodyB.GetType() === b2BodyType.b2_staticBody && bodyA.GetType() === b2BodyType.b2_staticBody) { return false; } // Does a joint prevent collision? if (!bodyB.ShouldCollideConnected(bodyA)) { return false; } const filter1 = fixtureA.GetFilterData(); const filter2 = fixtureB.GetFilterData(); if (filter1.groupIndex === filter2.groupIndex && filter1.groupIndex !== 0) { return (filter1.groupIndex > 0); } const collide = (((filter1.maskBits & filter2.categoryBits) !== 0) && ((filter1.categoryBits & filter2.maskBits) !== 0)); return collide; } // #if B2_ENABLE_PARTICLE ShouldCollideFixtureParticle(fixture, system, index) { return true; } ShouldCollideParticleParticle(system, indexA, indexB) { return true; } }
JavaScript
class b2ContactImpulse { constructor() { this.normalImpulses = b2MakeNumberArray(b2_maxManifoldPoints); this.tangentImpulses = b2MakeNumberArray(b2_maxManifoldPoints); this.count = 0; } }
JavaScript
class b2ContactManager { constructor() { this.m_broadPhase = new b2BroadPhase(); this.m_contactList = null; this.m_contactCount = 0; this.m_contactFilter = b2ContactFilter.b2_defaultFilter; this.m_contactListener = b2ContactListener.b2_defaultListener; this.m_allocator = null; this.m_contactFactory = new b2ContactFactory(this.m_allocator); } // Broad-phase callback. AddPair(proxyA, proxyB) { // DEBUG: b2Assert(proxyA instanceof b2FixtureProxy); // DEBUG: b2Assert(proxyB instanceof b2FixtureProxy); let fixtureA = proxyA.fixture; let fixtureB = proxyB.fixture; let indexA = proxyA.childIndex; let indexB = proxyB.childIndex; let bodyA = fixtureA.GetBody(); let bodyB = fixtureB.GetBody(); // Are the fixtures on the same body? if (bodyA === bodyB) { return; } // TODO_ERIN use a hash table to remove a potential bottleneck when both // bodies have a lot of contacts. // Does a contact already exist? let edge = bodyB.GetContactList(); while (edge) { if (edge.other === bodyA) { const fA = edge.contact.GetFixtureA(); const fB = edge.contact.GetFixtureB(); const iA = edge.contact.GetChildIndexA(); const iB = edge.contact.GetChildIndexB(); if (fA === fixtureA && fB === fixtureB && iA === indexA && iB === indexB) { // A contact already exists. return; } if (fA === fixtureB && fB === fixtureA && iA === indexB && iB === indexA) { // A contact already exists. return; } } edge = edge.next; } // Check user filtering. if (this.m_contactFilter && !this.m_contactFilter.ShouldCollide(fixtureA, fixtureB)) { return; } // Call the factory. const c = this.m_contactFactory.Create(fixtureA, indexA, fixtureB, indexB); if (c === null) { return; } // Contact creation may swap fixtures. fixtureA = c.GetFixtureA(); fixtureB = c.GetFixtureB(); indexA = c.GetChildIndexA(); indexB = c.GetChildIndexB(); bodyA = fixtureA.m_body; bodyB = fixtureB.m_body; // Insert into the world. c.m_prev = null; c.m_next = this.m_contactList; if (this.m_contactList !== null) { this.m_contactList.m_prev = c; } this.m_contactList = c; // Connect to island graph. // Connect to body A 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; // Connect to body B 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; // Wake up the bodies if (!fixtureA.IsSensor() && !fixtureB.IsSensor()) { bodyA.SetAwake(true); bodyB.SetAwake(true); } ++this.m_contactCount; } FindNewContacts() { this.m_broadPhase.UpdatePairs((proxyA, proxyB) => { this.AddPair(proxyA, proxyB); }); } Destroy(c) { const fixtureA = c.GetFixtureA(); const fixtureB = c.GetFixtureB(); const bodyA = fixtureA.GetBody(); const bodyB = fixtureB.GetBody(); if (this.m_contactListener && c.IsTouching()) { this.m_contactListener.EndContact(c); } // Remove from the world. 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_contactList) { this.m_contactList = c.m_next; } // Remove from body 1 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; } // Remove from body 2 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; } // Call the factory. this.m_contactFactory.Destroy(c); --this.m_contactCount; } // This is the top level collision call for the time step. Here // all the narrow phase collision is processed for the world // contact list. Collide() { // Update awake contacts. let c = this.m_contactList; while (c) { const fixtureA = c.GetFixtureA(); const fixtureB = c.GetFixtureB(); const indexA = c.GetChildIndexA(); const indexB = c.GetChildIndexB(); const bodyA = fixtureA.GetBody(); const bodyB = fixtureB.GetBody(); // Is this contact flagged for filtering? if (c.m_filterFlag) { // Check user filtering. if (this.m_contactFilter && !this.m_contactFilter.ShouldCollide(fixtureA, fixtureB)) { const cNuke = c; c = cNuke.m_next; this.Destroy(cNuke); continue; } // Clear the filtering flag. c.m_filterFlag = false; } const activeA = bodyA.IsAwake() && bodyA.m_type !== b2BodyType.b2_staticBody; const activeB = bodyB.IsAwake() && bodyB.m_type !== b2BodyType.b2_staticBody; // At least one body must be awake and it must be dynamic or kinematic. if (!activeA && !activeB) { c = c.m_next; continue; } const proxyA = fixtureA.m_proxies[indexA].treeNode; const proxyB = fixtureB.m_proxies[indexB].treeNode; const overlap = b2TestOverlapAABB(proxyA.aabb, proxyB.aabb); // Here we destroy contacts that cease to overlap in the broad-phase. if (!overlap) { const cNuke = c; c = cNuke.m_next; this.Destroy(cNuke); continue; } // The contact persists. c.Update(this.m_contactListener); c = c.m_next; } } }
JavaScript
class b2Profile { constructor() { this.step = 0; this.collide = 0; this.solve = 0; this.solveInit = 0; this.solveVelocity = 0; this.solvePosition = 0; this.broadphase = 0; this.solveTOI = 0; } Reset() { this.step = 0; this.collide = 0; this.solve = 0; this.solveInit = 0; this.solveVelocity = 0; this.solvePosition = 0; this.broadphase = 0; this.solveTOI = 0; return this; } }
JavaScript
class b2TimeStep { constructor() { this.dt = 0; // time step this.inv_dt = 0; // inverse time step (0 if dt == 0). this.dtRatio = 0; // dt * inv_dt0 this.velocityIterations = 0; this.positionIterations = 0; // #if B2_ENABLE_PARTICLE this.particleIterations = 0; // #endif this.warmStarting = false; } Copy(step) { this.dt = step.dt; this.inv_dt = step.inv_dt; this.dtRatio = step.dtRatio; this.positionIterations = step.positionIterations; this.velocityIterations = step.velocityIterations; // #if B2_ENABLE_PARTICLE this.particleIterations = step.particleIterations; // #endif this.warmStarting = step.warmStarting; return this; } }
JavaScript
class b2Island { constructor() { this.m_allocator = null; this.m_bodies = [ /*1024*/]; // TODO: b2Settings this.m_contacts = [ /*1024*/]; // TODO: b2Settings this.m_joints = [ /*1024*/]; // TODO: b2Settings this.m_positions = b2Position.MakeArray(1024); // TODO: b2Settings this.m_velocities = b2Velocity.MakeArray(1024); // TODO: b2Settings this.m_bodyCount = 0; this.m_jointCount = 0; this.m_contactCount = 0; this.m_bodyCapacity = 0; this.m_contactCapacity = 0; this.m_jointCapacity = 0; } Initialize(bodyCapacity, contactCapacity, jointCapacity, allocator, listener) { 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; // TODO: // while (this.m_bodies.length < bodyCapacity) { // this.m_bodies[this.m_bodies.length] = null; // } // TODO: // while (this.m_contacts.length < contactCapacity) { // this.m_contacts[this.m_contacts.length] = null; // } // TODO: // while (this.m_joints.length < jointCapacity) { // this.m_joints[this.m_joints.length] = null; // } // TODO: if (this.m_positions.length < bodyCapacity) { const new_length = b2Max(this.m_positions.length * 2, bodyCapacity); while (this.m_positions.length < new_length) { this.m_positions[this.m_positions.length] = new b2Position(); } } // TODO: if (this.m_velocities.length < bodyCapacity) { const new_length = b2Max(this.m_velocities.length * 2, bodyCapacity); while (this.m_velocities.length < new_length) { this.m_velocities[this.m_velocities.length] = new b2Velocity(); } } } Clear() { this.m_bodyCount = 0; this.m_contactCount = 0; this.m_jointCount = 0; } AddBody(body) { // DEBUG: b2Assert(this.m_bodyCount < this.m_bodyCapacity); body.m_islandIndex = this.m_bodyCount; this.m_bodies[this.m_bodyCount++] = body; } AddContact(contact) { // DEBUG: b2Assert(this.m_contactCount < this.m_contactCapacity); this.m_contacts[this.m_contactCount++] = contact; } AddJoint(joint) { // DEBUG: b2Assert(this.m_jointCount < this.m_jointCapacity); this.m_joints[this.m_jointCount++] = joint; } Solve(profile, step, gravity, allowSleep) { const timer = b2Island.s_timer.Reset(); const h = step.dt; // Integrate velocities and apply damping. Initialize the body state. for (let i = 0; i < this.m_bodyCount; ++i) { const b = this.m_bodies[i]; // const c: b2Vec2 = this.m_positions[i].c.Copy(b.m_sweep.c); const a = b.m_sweep.a; const v = this.m_velocities[i].v.Copy(b.m_linearVelocity); let w = b.m_angularVelocity; // Store positions for continuous collision. b.m_sweep.c0.Copy(b.m_sweep.c); b.m_sweep.a0 = b.m_sweep.a; if (b.m_type === b2BodyType.b2_dynamicBody) { // Integrate velocities. v.x += h * (b.m_gravityScale * gravity.x + b.m_invMass * b.m_force.x); v.y += h * (b.m_gravityScale * gravity.y + b.m_invMass * b.m_force.y); w += h * b.m_invI * b.m_torque; // Apply damping. // ODE: dv/dt + c * v = 0 // Solution: v(t) = v0 * exp(-c * t) // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt) // v2 = exp(-c * dt) * v1 // Pade approximation: // v2 = v1 * 1 / (1 + c * dt) v.SelfMul(1.0 / (1.0 + h * b.m_linearDamping)); w *= 1.0 / (1.0 + h * b.m_angularDamping); } // this.m_positions[i].c = c; this.m_positions[i].a = a; // this.m_velocities[i].v = v; this.m_velocities[i].w = w; } timer.Reset(); // Solver data const solverData = b2Island.s_solverData; solverData.step.Copy(step); solverData.positions = this.m_positions; solverData.velocities = this.m_velocities; // Initialize velocity constraints. const contactSolverDef = b2Island.s_contactSolverDef; contactSolverDef.step.Copy(step); contactSolverDef.contacts = this.m_contacts; contactSolverDef.count = this.m_contactCount; contactSolverDef.positions = this.m_positions; contactSolverDef.velocities = this.m_velocities; contactSolverDef.allocator = this.m_allocator; const contactSolver = b2Island.s_contactSolver.Initialize(contactSolverDef); contactSolver.InitializeVelocityConstraints(); if (step.warmStarting) { contactSolver.WarmStart(); } for (let i = 0; i < this.m_jointCount; ++i) { this.m_joints[i].InitVelocityConstraints(solverData); } profile.solveInit = timer.GetMilliseconds(); // Solve velocity constraints. timer.Reset(); for (let i = 0; i < step.velocityIterations; ++i) { for (let j = 0; j < this.m_jointCount; ++j) { this.m_joints[j].SolveVelocityConstraints(solverData); } contactSolver.SolveVelocityConstraints(); } // Store impulses for warm starting contactSolver.StoreImpulses(); profile.solveVelocity = timer.GetMilliseconds(); // Integrate positions. for (let i = 0; i < this.m_bodyCount; ++i) { const c = this.m_positions[i].c; let a = this.m_positions[i].a; const v = this.m_velocities[i].v; let w = this.m_velocities[i].w; // Check for large velocities const translation = b2Vec2.MulSV(h, v, b2Island.s_translation); if (b2Vec2.DotVV(translation, translation) > b2_maxTranslationSquared) { const ratio = b2_maxTranslation / translation.Length(); v.SelfMul(ratio); } const rotation = h * w; if (rotation * rotation > b2_maxRotationSquared) { const ratio = b2_maxRotation / b2Abs(rotation); w *= ratio; } // Integrate c.x += h * v.x; c.y += h * v.y; a += h * w; // this.m_positions[i].c = c; this.m_positions[i].a = a; // this.m_velocities[i].v = v; this.m_velocities[i].w = w; } // Solve position constraints timer.Reset(); let positionSolved = false; for (let i = 0; i < step.positionIterations; ++i) { const contactsOkay = contactSolver.SolvePositionConstraints(); let jointsOkay = true; for (let j = 0; j < this.m_jointCount; ++j) { const jointOkay = this.m_joints[j].SolvePositionConstraints(solverData); jointsOkay = jointsOkay && jointOkay; } if (contactsOkay && jointsOkay) { // Exit early if the position errors are small. positionSolved = true; break; } } // Copy state buffers back to the bodies for (let i = 0; i < this.m_bodyCount; ++i) { const body = this.m_bodies[i]; body.m_sweep.c.Copy(this.m_positions[i].c); body.m_sweep.a = this.m_positions[i].a; body.m_linearVelocity.Copy(this.m_velocities[i].v); body.m_angularVelocity = this.m_velocities[i].w; body.SynchronizeTransform(); } profile.solvePosition = timer.GetMilliseconds(); this.Report(contactSolver.m_velocityConstraints); if (allowSleep) { let minSleepTime = b2_maxFloat; const linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance; const angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance; for (let i = 0; i < this.m_bodyCount; ++i) { const b = this.m_bodies[i]; if (b.GetType() === b2BodyType.b2_staticBody) { continue; } if (!b.m_autoSleepFlag || b.m_angularVelocity * b.m_angularVelocity > angTolSqr || b2Vec2.DotVV(b.m_linearVelocity, b.m_linearVelocity) > linTolSqr) { b.m_sleepTime = 0; minSleepTime = 0; } else { b.m_sleepTime += h; minSleepTime = b2Min(minSleepTime, b.m_sleepTime); } } if (minSleepTime >= b2_timeToSleep && positionSolved) { for (let i = 0; i < this.m_bodyCount; ++i) { const b = this.m_bodies[i]; b.SetAwake(false); } } } } SolveTOI(subStep, toiIndexA, toiIndexB) { // DEBUG: b2Assert(toiIndexA < this.m_bodyCount); // DEBUG: b2Assert(toiIndexB < this.m_bodyCount); // Initialize the body state. for (let i = 0; i < this.m_bodyCount; ++i) { const b = this.m_bodies[i]; this.m_positions[i].c.Copy(b.m_sweep.c); this.m_positions[i].a = b.m_sweep.a; this.m_velocities[i].v.Copy(b.m_linearVelocity); this.m_velocities[i].w = b.m_angularVelocity; } const contactSolverDef = b2Island.s_contactSolverDef; contactSolverDef.contacts = this.m_contacts; contactSolverDef.count = this.m_contactCount; contactSolverDef.allocator = this.m_allocator; contactSolverDef.step.Copy(subStep); contactSolverDef.positions = this.m_positions; contactSolverDef.velocities = this.m_velocities; const contactSolver = b2Island.s_contactSolver.Initialize(contactSolverDef); // Solve position constraints. for (let i = 0; i < subStep.positionIterations; ++i) { const contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB); if (contactsOkay) { break; } } /* #if 0 // Is the new position really safe? for (int32 i = 0; i < this.m_contactCount; ++i) { b2Contact* c = this.m_contacts[i]; b2Fixture* fA = c.GetFixtureA(); b2Fixture* fB = c.GetFixtureB(); b2Body* bA = fA.GetBody(); b2Body* bB = fB.GetBody(); int32 indexA = c.GetChildIndexA(); int32 indexB = c.GetChildIndexB(); b2DistanceInput input; input.proxyA.Set(fA.GetShape(), indexA); input.proxyB.Set(fB.GetShape(), indexB); input.transformA = bA.GetTransform(); input.transformB = bB.GetTransform(); input.useRadii = false; b2DistanceOutput output; b2SimplexCache cache; cache.count = 0; b2Distance(&output, &cache, &input); if (output.distance === 0 || cache.count === 3) { cache.count += 0; } } #endif */ // Leap of faith to new safe state. this.m_bodies[toiIndexA].m_sweep.c0.Copy(this.m_positions[toiIndexA].c); this.m_bodies[toiIndexA].m_sweep.a0 = this.m_positions[toiIndexA].a; this.m_bodies[toiIndexB].m_sweep.c0.Copy(this.m_positions[toiIndexB].c); this.m_bodies[toiIndexB].m_sweep.a0 = this.m_positions[toiIndexB].a; // No warm starting is needed for TOI events because warm // starting impulses were applied in the discrete solver. contactSolver.InitializeVelocityConstraints(); // Solve velocity constraints. for (let i = 0; i < subStep.velocityIterations; ++i) { contactSolver.SolveVelocityConstraints(); } // Don't store the TOI contact forces for warm starting // because they can be quite large. const h = subStep.dt; // Integrate positions for (let i = 0; i < this.m_bodyCount; ++i) { const c = this.m_positions[i].c; let a = this.m_positions[i].a; const v = this.m_velocities[i].v; let w = this.m_velocities[i].w; // Check for large velocities const translation = b2Vec2.MulSV(h, v, b2Island.s_translation); if (b2Vec2.DotVV(translation, translation) > b2_maxTranslationSquared) { const ratio = b2_maxTranslation / translation.Length(); v.SelfMul(ratio); } const rotation = h * w; if (rotation * rotation > b2_maxRotationSquared) { const ratio = b2_maxRotation / b2Abs(rotation); w *= ratio; } // Integrate c.SelfMulAdd(h, v); a += h * w; // this.m_positions[i].c = c; this.m_positions[i].a = a; // this.m_velocities[i].v = v; this.m_velocities[i].w = w; // Sync bodies const body = this.m_bodies[i]; body.m_sweep.c.Copy(c); body.m_sweep.a = a; body.m_linearVelocity.Copy(v); body.m_angularVelocity = w; body.SynchronizeTransform(); } this.Report(contactSolver.m_velocityConstraints); } Report(constraints) { if (this.m_listener === null) { return; } for (let i = 0; i < this.m_contactCount; ++i) { const c = this.m_contacts[i]; if (!c) { continue; } const vc = constraints[i]; const impulse = b2Island.s_impulse; impulse.count = vc.pointCount; for (let j = 0; j < vc.pointCount; ++j) { impulse.normalImpulses[j] = vc.points[j].normalImpulse; impulse.tangentImpulses[j] = vc.points[j].tangentImpulse; } this.m_listener.PostSolve(c, impulse); } } }
JavaScript
class b2StackQueue { constructor(capacity) { this.m_front = 0; this.m_back = 0; this.m_capacity = 0; this.m_buffer = b2MakeArray(capacity, (index) => null); this.m_capacity = capacity; } Push(item) { if (this.m_back >= this.m_capacity) { for (let i = this.m_front; i < this.m_back; i++) { this.m_buffer[i - this.m_front] = this.m_buffer[i]; } this.m_back -= this.m_front; this.m_front = 0; if (this.m_back >= this.m_capacity) { if (this.m_capacity > 0) { this.m_buffer.concat(b2MakeArray(this.m_capacity, (index) => null)); this.m_capacity *= 2; } else { this.m_buffer.concat(b2MakeArray(1, (index) => null)); this.m_capacity = 1; } ///m_buffer = (T*) m_allocator->Reallocate(m_buffer, sizeof(T) * m_capacity); } } this.m_buffer[this.m_back] = item; this.m_back++; } Pop() { // DEBUG: b2Assert(this.m_front < this.m_back); this.m_buffer[this.m_front] = null; this.m_front++; } Empty() { // DEBUG: b2Assert(this.m_front <= this.m_back); return this.m_front === this.m_back; } Front() { const item = this.m_buffer[this.m_front]; if (!item) { throw new Error(); } return item; } }
JavaScript
class b2VoronoiDiagram { constructor(generatorCapacity) { this.m_generatorCapacity = 0; this.m_generatorCount = 0; this.m_countX = 0; this.m_countY = 0; this.m_diagram = []; this.m_generatorBuffer = b2MakeArray(generatorCapacity, (index) => new b2VoronoiDiagram.Generator()); this.m_generatorCapacity = generatorCapacity; } /** * Add a generator. * * @param center the position of the generator. * @param tag a tag used to identify the generator in callback functions. * @param necessary whether to callback for nodes associated with the generator. */ AddGenerator(center, tag, necessary) { // DEBUG: b2Assert(this.m_generatorCount < this.m_generatorCapacity); const g = this.m_generatorBuffer[this.m_generatorCount++]; g.center.Copy(center); g.tag = tag; g.necessary = necessary; } /** * Generate the Voronoi diagram. It is rasterized with a given * interval in the same range as the necessary generators exist. * * @param radius the interval of the diagram. * @param margin margin for which the range of the diagram is extended. */ Generate(radius, margin) { const inverseRadius = 1 / radius; const lower = new b2Vec2(+b2_maxFloat, +b2_maxFloat); const upper = new b2Vec2(-b2_maxFloat, -b2_maxFloat); let necessary_count = 0; for (let k = 0; k < this.m_generatorCount; k++) { const g = this.m_generatorBuffer[k]; if (g.necessary) { b2Vec2.MinV(lower, g.center, lower); b2Vec2.MaxV(upper, g.center, upper); ++necessary_count; } } if (necessary_count === 0) { ///debugger; this.m_countX = 0; this.m_countY = 0; return; } lower.x -= margin; lower.y -= margin; upper.x += margin; upper.y += margin; this.m_countX = 1 + Math.floor(inverseRadius * (upper.x - lower.x)); this.m_countY = 1 + Math.floor(inverseRadius * (upper.y - lower.y)); /// m_diagram = (Generator**) m_allocator->Allocate(sizeof(Generator*) * m_countX * m_countY); /// for (int32 i = 0; i < m_countX * m_countY; i++) /// { /// m_diagram[i] = NULL; /// } this.m_diagram = []; // b2MakeArray(this.m_countX * this.m_countY, (index) => null); // (4 * m_countX * m_countY) is the queue capacity that is experimentally // known to be necessary and sufficient for general particle distributions. const queue = new b2StackQueue(4 * this.m_countX * this.m_countY); for (let k = 0; k < this.m_generatorCount; k++) { const g = this.m_generatorBuffer[k]; /// g.center = inverseRadius * (g.center - lower); g.center.SelfSub(lower).SelfMul(inverseRadius); const x = Math.floor(g.center.x); const y = Math.floor(g.center.y); if (x >= 0 && y >= 0 && x < this.m_countX && y < this.m_countY) { queue.Push(new b2VoronoiDiagram.Task(x, y, x + y * this.m_countX, g)); } } while (!queue.Empty()) { const task = queue.Front(); const x = task.m_x; const y = task.m_y; const i = task.m_i; const g = task.m_generator; queue.Pop(); if (!this.m_diagram[i]) { this.m_diagram[i] = g; if (x > 0) { queue.Push(new b2VoronoiDiagram.Task(x - 1, y, i - 1, g)); } if (y > 0) { queue.Push(new b2VoronoiDiagram.Task(x, y - 1, i - this.m_countX, g)); } if (x < this.m_countX - 1) { queue.Push(new b2VoronoiDiagram.Task(x + 1, y, i + 1, g)); } if (y < this.m_countY - 1) { queue.Push(new b2VoronoiDiagram.Task(x, y + 1, i + this.m_countX, g)); } } } for (let y = 0; y < this.m_countY; y++) { for (let x = 0; x < this.m_countX - 1; x++) { const i = x + y * this.m_countX; const a = this.m_diagram[i]; const b = this.m_diagram[i + 1]; if (a !== b) { queue.Push(new b2VoronoiDiagram.Task(x, y, i, b)); queue.Push(new b2VoronoiDiagram.Task(x + 1, y, i + 1, a)); } } } for (let y = 0; y < this.m_countY - 1; y++) { for (let x = 0; x < this.m_countX; x++) { const i = x + y * this.m_countX; const a = this.m_diagram[i]; const b = this.m_diagram[i + this.m_countX]; if (a !== b) { queue.Push(new b2VoronoiDiagram.Task(x, y, i, b)); queue.Push(new b2VoronoiDiagram.Task(x, y + 1, i + this.m_countX, a)); } } } while (!queue.Empty()) { const task = queue.Front(); const x = task.m_x; const y = task.m_y; const i = task.m_i; const k = task.m_generator; queue.Pop(); const a = this.m_diagram[i]; const b = k; if (a !== b) { const ax = a.center.x - x; const ay = a.center.y - y; const bx = b.center.x - x; const by = b.center.y - y; const a2 = ax * ax + ay * ay; const b2 = bx * bx + by * by; if (a2 > b2) { this.m_diagram[i] = b; if (x > 0) { queue.Push(new b2VoronoiDiagram.Task(x - 1, y, i - 1, b)); } if (y > 0) { queue.Push(new b2VoronoiDiagram.Task(x, y - 1, i - this.m_countX, b)); } if (x < this.m_countX - 1) { queue.Push(new b2VoronoiDiagram.Task(x + 1, y, i + 1, b)); } if (y < this.m_countY - 1) { queue.Push(new b2VoronoiDiagram.Task(x, y + 1, i + this.m_countX, b)); } } } } } /** * Enumerate all nodes that contain at least one necessary * generator. */ GetNodes(callback) { for (let y = 0; y < this.m_countY - 1; y++) { for (let x = 0; x < this.m_countX - 1; x++) { const i = x + y * this.m_countX; const a = this.m_diagram[i]; const b = this.m_diagram[i + 1]; const c = this.m_diagram[i + this.m_countX]; const d = this.m_diagram[i + 1 + this.m_countX]; if (b !== c) { if (a !== b && a !== c && (a.necessary || b.necessary || c.necessary)) { callback(a.tag, b.tag, c.tag); } if (d !== b && d !== c && (a.necessary || b.necessary || c.necessary)) { callback(b.tag, d.tag, c.tag); } } } } } }
JavaScript
class NoVersionOrUpdateDateColumnError extends TypeORMError_1.TypeORMError { constructor(entity) { super(`Entity ${entity} does not have version or update date columns.`); } }
JavaScript
class BoxNode extends StretchyNode { /** * constructor * @param {String} backgroundColor * @param {String} borderColor * @param {Number} borderWidth * @param {Number} minWidth * @param {Array<String>} classes */ constructor (backgroundColor, borderColor, borderWidth, minWidth, classes) { super(minWidth, classes) this.backgroundColor = backgroundColor this.borderColor = borderColor this.borderWidth = borderWidth } /** * Converts the VirtualNode model to a JSON Object. */ toJSON () { const json = super.toJSON() json.backgroundColor = this.backgroundColor json.borderColor = this.borderColor json.borderWidth = this.borderWidth return json } /** * Returns the type of the VirtualCanvasNode * * @return {String} */ get type () { return 'BoxNode' } }
JavaScript
class ActiveTemplate { /** * @param {Dotcom.Template} template The parent template * @param {Object} params The parameters for the template * @param {Object} data The data for the template */ constructor(template, params, data) { this.template = template; this._params = params; this._data = data; } /** * Render the template based on this ActiveTemplate's params and data * @return {string} */ render() { return this.template._fn.call(this, this._params, this._data); } /** * Renders another template template based upon this ActiveTemplate's params and data * @return {string} */ partial(name, data) { data = data || {}; Object.keys(this._data).forEach(k => data[k] = data.hasOwnProperty(k) ? data[k] : this._data[k]); return this.template.constructor.generate(name).render(this._params, data); } /** * Renders another raw template template based upon this ActiveTemplate's params and data * @return {string} */ rawPartial(name, data) { data = data || {}; Object.keys(this._data).forEach(k => data[k] = data.hasOwnProperty(k) ? data[k] : this._data[k]); return this.template.constructor.raw(name).render(this._params, data); } /** * Renders another template template based upon this ActiveTemplate's params and data * @return {string} */ child() { return this.template.constructor.generate.apply( this.template.constructor, this.template._children ).render(this._params, this._data); } }
JavaScript
class Template { /** * Retrieves the template from the cache or loads the template and caches it * @param {string} The template name (full path in the the ./templates directory). * @param {optional boolean} raw Whether or not the template is "raw" (i.e. just an HTML string, no template engine required.) Defaults to false. * @return {Dotcom.Template} The template instance */ static get(name, raw) { raw = !!raw | 0; // coerce to 0, 1 if (!this._templates[name]) { this._templates[name] = Array(2); } if(this._templates[name][raw]) { return this._templates[name][raw]; } let filename = './templates/' + name; try { let contents = fs.readFileSync(filename); this._templates[name][raw] = raw ? () => { return contents; } : dot.template(contents); return this._templates[name][raw]; } catch(e) { console.log(e); console.log('Could not load template ' + name); } return this._templates['!']; } /** * Retrieves the template matching the provided name. Lazy loads new templates from disk, otherwise caches. * @param {string} templates List of heirarchy of templates (each a full path in the the app/templates directory). * @return {Dotcom.Template} The template instance */ static generate(name) { let templates = Array.prototype.slice.call(arguments); if (templates.length === 1) { return new Template(this.get(name)); } return new Template( this.get(name), templates.slice(1) ); } /** * Retrieves a "raw" template (i.e. just an HTML string, no template engine required.) * @param {string} name The traw emplate name (full path in the the app/templates directory). * @return {Dotcom.Template} The template instance */ static raw(name) { return new Template(this.get(name, true)); } /** * @param {function} fn The method to render your template with * @param {string} children Remaining children template in heirarchy */ constructor(fn, children) { this._fn = fn; this._children = children; } /** * Generates (renders) your template by creating an ActiveTemplate instance * @param {Object} params The parameters for the template * @param {Object} data The data for the template * @return {ActiveTemplate} */ render(params, data) { params = Object.create(params || {}); data = Object.assign(Object.create(process.env), data || {}); return new ActiveTemplate(this, params, data).render(); } }
JavaScript
class stmuxOptions { parseOptions() { /* parse command-line arguments */ this.argv = _yargs.default.usage("Usage: $0 [-h] [-v] [-w] [-a <activator>] [-t <title>] [-f <file>] [-- <spec>]").help("h").alias("h", "help").default("h", false).describe("h", "show usage help").boolean("v").alias("v", "version").default("v", false).describe("v", "show program version information").string("w").nargs("w", 1).alias("w", "wait").default("w", "").describe("w", "wait after last finished command (on \"error\" or \"always\")").string("a").nargs("a", 1).alias("a", "activator").default("a", "a").describe("a", "use CTRL+<activator> as the prefix to special commands").string("t").nargs("t", 1).alias("t", "title").default("t", "stmux").describe("t", "set title on terminal").string("c").nargs("c", 1).alias("c", "cursor").default("c", "block").describe("c", "set type of cursor (block, underline or line)").boolean("n").alias("n", "number").default("n", false).describe("n", "show terminal number in terminal title").string("e").nargs("e", 1).alias("e", "error").default("e", "(?:ERROR|Error|error)").describe("e", "observe terminal for errors (global option)").string("m").nargs("m", 1).alias("m", "method").default("m", "").describe("m", "notification method(s) in case an error was detected").boolean("M").alias("M", "mouse").default("M", false).describe("M", "enable mouse event handling").string("f").nargs("f", 1).alias("f", "file").default("f", "-").describe("f", "read specification from configuration file").strict().showHelpOnFail(true).demand(0).parse(process.argv.slice(2)); /* short-circuit processing of "-V" command-line option */ if (this.argv.version) { process.stderr.write(this.my.name + " " + this.my.version + " <" + this.my.homepage + ">\n"); process.stderr.write(this.my.description + "\n"); process.stderr.write("Copyright (c) 2017 " + this.my.author.name + " <" + this.my.author.url + ">\n"); process.stderr.write("Licensed under " + this.my.license + " <http://spdx.org/licenses/" + this.my.license + ".html>\n"); process.exit(0); } /* determine specification */ if (this.argv._.length > 0) { /* via command-line arguments */ this.spec = this.argv._.map(arg => { if (arg.match(/[\s"]/)) arg = `"${arg.replace(/"/g, "\\\"")}"`; return arg; }).join(" "); } else { if (this.argv.file === "-") { /* via stdin */ this.spec = ""; process.stdin.setEncoding("utf-8"); const BUFSIZE = 256; const buf = Buffer.alloc(BUFSIZE); while (true) { let bytesRead = 0; try { bytesRead = _fs.default.readSync(process.stdin.fd, buf, 0, BUFSIZE); } catch (ex) { if (ex.code === "EAGAIN") continue;else if (ex.code === "EOF") break;else throw ex; } if (bytesRead === 0) break; this.spec += buf.toString(null, 0, bytesRead); } } else { /* via file */ if (!_fs.default.existsSync(this.argv.file)) this.fatal(`cannot find specification file "${this.argv.file}"`); this.spec = _fs.default.readFileSync(this.argv.file, "utf8"); } } } }
JavaScript
class Bird { /** * Create a formated string with the speed of the bird * @param {number} speed * @return {string} */ fly(speed) { return 'Flying at ' + speed + ' km/h'; } }
JavaScript
class Penguin extends Bird { /** * The method can't do the same of the super fly, making an LSP Violation * @throws {Error} */ fly() { throw new Error('Sorry, I cannot fly :o('); } }
JavaScript
class App extends React.Component { /** *Creates an instance of App. * @param {object} props * @memberof App */ constructor(props) { super(props); this.state = { showIntro: undefined, }; this.onViewChange = this.onViewChange.bind(this); this.showMainNavigation = this.showMainNavigation.bind(this); } /** * Change the active view after tabbar switched * @param {Event} e * @memberof App */ onViewChange(e) { const location = { pathname: `/${e.currentTarget.dataset.story}`, }; this.props.history.push(location); } /** * Change the showIntro to false * @memberof App */ showMainNavigation() { this.setState({ showIntro: false, }); } render() { const viewsData = [ { view: Workflow, name: 'workflow', text: 'Путешествие', icon: workflowIcon, }, { view: Games, name: 'games', text: 'Игры', icon: gamesIcon, }, { view: LeaderBoard, name: 'leaderboard', text: 'Лидеры', icon: leaderboardIcon, }, { view: Events, name: 'events', text: 'События', icon: eventsIcon, }, { view: Profile, name: 'profile', text: 'Профиль', icon: profileIcon, }, ]; if ( typeof this.state.showIntro === 'undefined' && typeof this.props.user.isFirstEntry !== 'undefined' ) { this.setState({ showIntro: this.props.user.isFirstEntry }); } let result; if (typeof this.state.showIntro === 'undefined') { result = <SpinnerCentered />; } else if (this.state.showIntro === true) { result = <Introduction onStartClick={this.showMainNavigation} />; } else { result = ( <Navigation activeView={this.props.viewName} viewsData={viewsData} onViewChange={this.onViewChange} /> ); } return result; } }
JavaScript
class ProcessMessenger extends MessengerInterface { /** * Constructor for the messenger class. * @param {object} configuration User-provided configuration details for the messenger. */ constructor(configuration) { super(configuration); } /** * Initialize the messenger instance. * @async */ async initialize() { // NOOP } /** * Configure the Messenger with the related processes. * @param {Process[]} processes The process instances this process can communicate with. */ async configureProcessInstances(processes) { this.processes = processes; const uuid = this.getUUID(); const self = this; for (const workerProcess of this.processes) { workerProcess.on('message', (message) => { Logger.debug(`Process "${uuid}" handling message: ${message}`); const msg = ParseMessage(message); // Only action if intended for this process if (msg.forRecipient(uuid)) { self.onMessage(msg); } else { Logger.debug(`Messenger "${uuid}" ignored message: ${message}`); } }); } } /** * Get the UUID for the messenger instance to use as sender or recipient address. * @return {string} The UUID of the messenger. */ getUUID() { return process.pid.toString(); } /** * Clean up any resources associated with the messenger. */ async dispose() { // NOOP } /** * Send a message using the messenger. * @param {Message} message The message object. */ send(message) { // Convert to string and send const msg = message.stringify(); for (const proc of this.processes) { proc.send(msg); Logger.debug(`Process "${this.getUUID()}" sent message: ${msg}`); } } }
JavaScript
class Employee { constructor(name, id, email){ // this. ... } // getters and setters }
JavaScript
class Registry { constructor(name, idField, mode = Registry.MODES.HISTORY) { this.__name = name || 'Registry'; this.__idField = idField || 'id'; this.__registered = []; this.__protected = {}; this.__unregister = {}; this.__banned = {}; this.__subscribers = {}; this.__mode = mode in Registry.MODES ? mode : Registry.MODES.HISTORY; } get protected() { return Object.values(this.__protected); } get registered() { return this.__registered; } get unregistered() { return Object.values(this.__unregister); } get banned() { return Object.values(this.__banned); } get listById() { const unregister = this.__unregister; const banned = this.__banned; const registered = Array.from(this.__registered).filter( item => !(item[this.__idField] in unregister) && !(item[this.__idField] in banned), ); return _.chain(registered) .sortBy('order') .indexBy(this.__idField) .value(); } get list() { return Object.values(this.listById); } set mode(newMode = Registry.MODES.HISTORY) { this.__mode = newMode in Registry.MODES ? newMode : Registry.MODES.HISTORY; } get mode() { return this.__mode; } get(id, defaultValue) { return op.get(this.listById, [id], defaultValue); } isProtected(id) { return id in this.__protected; } isRegistered(id) { return !!_.findWhere(this.__registered, { id }); } isUnRegistered(id) { return !(id in this.listById); } isBanned(id) { return id in this.__banned; } ban(id) { const ids = _.flatten([id]); ids.forEach(id => op.set(this.__banned, [id], id)); if (this.__mode === Registry.MODES.CLEAN) { this.cleanup(id); } this.notify({ type: 'ban', id }); return this; } cleanup(id) { const [remove] = _.flatten([id]); if (this.isProtected(remove)) return this; this.__registered = this.__registered.filter( item => item[this.__idField] !== remove, ); this.notify({ type: 'cleanup', id }); return this; } flush() { this.__registered = []; this.__protected = {}; this.__unregister = {}; this.__banned = {}; this.notify({ type: 'flush' }); } protect(id) { const ids = _.flatten([id]); ids.forEach(id => op.set(this.__protected, [id], id)); this.notify({ type: 'protect', id, }); return this; } register(id, data = {}) { // one argument register if (typeof id === 'object' && this.__idField in id) { data = id; id = data[this.__idField]; } if (!id) id = uuid(); if (this.isBanned(id)) { return new Error( `${this.__name} unable to register banned item ${id}`, ); } if (this.isProtected(id) && this.isRegistered(id)) { return new Error( `${this.__name} unable to replace protected item ${id}`, ); } data['order'] = op.get(data, 'order', 100); const item = { ...data, [this.__idField]: id }; if (this.__mode === Registry.MODES.CLEAN) { this.cleanup(id); } this.__registered.push(item); op.del(this.__unregister, [id]); this.notify({ type: 'register', id, data: item, }); return this; } unprotect(id) { const ids = _.flatten([id]); ids.forEach(id => op.del(this.__protected, id)); this.notify({ type: 'unprotect', id, }); return this; } unregister(id) { if (!id) return this; const ids = _.chain([id]) .flatten() .uniq() .value(); ids.forEach(id => { if (id in this.__protected) return; if (this.__mode === Registry.MODES.CLEAN) { this.cleanup(id); return; } op.set(this.__unregister, [id], id); }); this.notify({ type: 'unregister', id, }); return this; } subscribe(cb, id) { if (!id) id = uuid(); if (typeof cb === 'function') { this.__subscribers[id] = cb; } return () => this.unsubscribe(id); } unsubscribe(id) { op.del(this.__subscribers, [id]); } unsubscribeAll() { this.__subscribers = {}; } notify(context) { Object.entries(this.__subscribers).forEach(([id, cb]) => { if (typeof cb === 'function') cb(this, context); }); } }
JavaScript
class RemoteProxyFunction { constructor(fnName, remoteObject) { this._fnName = fnName; this._remoteObject = remoteObject; // map of all calls that were made to a remote context this.callInstances = {}; } exec(...args) { // generate a new instance-id for this particular function call const instanceID = Util.id(); const signatures = this.callInstances; // ensure this instance ID has not been added previously // NOTE: This should not ever be executed as all instance ID's are unique // If this executes then the PRNG scheme needs to be swapped if (signatures[instanceID]) { return new Promise((_, reject) => { return reject(new Error("RemoteProxyFunction.exec() - internal error - prng error")); }); } // add this call as a unique instance and save the Promise // to be executed later return new Promise((accept, reject) => { // save this promise to be executed later signatures[instanceID] = { accept: accept, reject: reject }; const signature = "c:" + this._fnName + ":" + instanceID; this._remoteObject.socket.emit(signature, args); }); } }
JavaScript
class ActionContext { @computed get isImplicitIntent() { if (!isImplicitIntentRequested({intent: this.intent, ...this.intentParams})) return false //try to find corresponding session if (!restoreImplicitSession(this.intentParams.session)) return false //looks ok return true } /** * Requested intent. * @type {String} */ @observable intent = null /** * Request params. * @type {Object} */ @observable.shallow intentParams = null @observable networkName = 'public' /** * Requested transaction context. * @type {TxContext} */ @observable txContext = null /** * Intent confirmation status. * @type {boolean} */ @observable confirmed = false /** * Whether action processed or not. * @type {Boolean} */ @observable processed = false /** * Errors found during intent validation or execution. * @type {String} */ @observable intentErrors = null response = null @observable directKeyInput = false /** * Directly provided secret key (only for direct input case). * @type {String} */ secret = null @observable selectedAccountInfo = null @computed get selectedPublicKey() { try { if (this.directKeyInput) { if (!this.secret) return null return Keypair.fromSecret(this.secret).publicKey() } return accountManager.activeAccount?.publicKey || null } catch (e) { console.error(e) } } get requiresExistingAccount() { return !['public_key', 'sign_message', 'implicit_flow'].includes(this.intent) } @computed get autoSubmitToHorizon() { return this?.intentParams?.submit || false } /** * Set current context based on the request params. * @param {object} params - Intent request parameters. */ @action async setContext(params) { this.reset() const {intent, ...intentParams} = params Object.assign(this, { intentErrors: null, confirmed: false, processed: false, intent, intentParams }) //intent should be present if (!intent) { this.intentErrors = 'Parameter "intent" is required.' return this.rejectRequest() } /*if (account && !StrKey.isValidEd25519PublicKey(account)) { this.intentErrors = 'Invalid "account" parameter. Stellar account public key expected.' return }*/ const {network, networkName} = resolveNetworkParams(intentParams) this.networkName = networkName this.intentProps = intentInterface[intent] if (!this.intentProps) { this.intentErrors = `Unknown intent "${intent}".` return this.rejectRequest() } const allowedParams = this.intentProps.params for (let param in allowedParams) if (allowedParams.hasOwnProperty(param)) { const descriptor = allowedParams[param], value = intentParams[param] if (descriptor.required && !value) { this.intentErrors = `Parameter "${param}" is required.` return this.rejectRequest() } } //set transaction context in advance for the tx intent if (intent === 'tx') { const {network} = resolveNetworkParams(intentParams) const tx = new Transaction(intentParams.xdr, network) await this.setTxContext(tx) } //validate implicit flow request preconditions if (intent === 'implicit_flow') { let {intents = [], app_origin} = intentParams if (app_origin !== window.origin && whitelist.length && !whitelist.includes(app_origin)) { this.intentErrors = `Origin "${app_origin}" is not allowed to request implicit flow permissions.` return this.rejectRequest() } if (typeof intents === 'string') { intents = intents.split(',') } if (!(intents instanceof Array) || !intents.length) { //TODO: reject intent immediately if possible this.intentErrors = `No intents were specified for the implicit mode.` return this.rejectRequest() } this.intentParams.intents = intents //check that intent exists and is allowed in the implicit mode for (let requestedIntent of intents) { const descriptor = intentInterface[requestedIntent] if (!descriptor) { this.intentErrors = `Unknown intent requested: "${requestedIntent}".` return this.rejectRequest() } if (!descriptor.implicitFlow) { this.intentErrors = `Intent ${requestedIntent} can't be used in the implicit flow.` return this.rejectRequest() } } } } @action reset() { Object.assign(this, { intent: null, intentProps: null, intentParams: null, secret: null, txContext: null, response: null, intentErrors: null, confirmed: false, processed: false }) } @computed get isFinalized() { return this.confirmed && !!this.response } /** * Confirm the intent request. */ @action async confirmRequest() { this.confirmed = true try { this.response = await responder.process(this) if (!this.response) return if (!this.txContext || this.txContext.isFullySigned) { //TODO: do not auto-submit tx to the network return await this.finalize() } } catch (e) { console.error(e) this.intentErrors = e if (this.isImplicitIntent) { return this.rejectRequest(e) } } } /** * Send response back to the caller window and reset action context state - only for interactive flow. * @return {Promise<Object>} */ @action async finalize() { if (!this.intent) return //likely it was called after the response has been submitted try { if (!this.response) throw new Error('Tried to finalize the action without a response.') lastActionResult.setResult(this.response) const res = await dispatchIntentResponse(this.response, this) __history.push('/result') this.reset() return res } catch (e) { console.error(e) this.intentErrors = e this.reset() } } /** * Reject the request. * @param {Error} [error] - Rejection reason or validation error. */ rejectRequest(error) { const {intent, intentErrors} = this if (!intent) return if (!error && intentErrors) { if (intentErrors.code === undefined) { error = errors.invalidIntentRequest(intentErrors) } else { error = intentErrors } } return handleIntentResponseError(error, this) .then(res => { this.reset() return res }) .catch(e => { this.reset() return e }) } /** * Cancel current action. */ @action cancelAction() { //TODO: implement contextual action and nav path here __history.push('/') } /** * Prepare and set TxContext for supported intents. * @param {Transaction} transaction * @return {Promise<TxContext>} */ @action async setTxContext(transaction) { //set tx context, retrieve network params from intent params const txContext = new TxContext(transaction, this.intentParams) //discover available signers using current account //TODO: update available signers when the activeAccount is changed const {activeAccount} = accountManager, availableSigners = !activeAccount ? [] : [activeAccount.publicKey] txContext.setAvailableSigners(availableSigners) try { await txContext.updateSignatureSchema() } catch (e) { console.error(e) } runInAction(() => { actionContext.txContext = txContext }) return txContext } @action loadSelectedAccountInfo() { loadSelectedAccountInfo(this) .then(info => runInAction(() => { this.selectedAccountInfo = info })) } }
JavaScript
class EditorProperty { /** * the preferred tagName of this property, the tagname is not guarantueed to be used unless mustWrap is truthy * @property tagName * @type String * @default 'span' */ tagName; /** * indicates whether creation of a new node should be enforced when applying the property * @property newContext * @type boolean * @default false */ newContext; /** * Array of dom attributes to add to a domnode when applying the property * @property attributes * @type Object */ attributes; constructor({tagName = DEFAULT_TAG_NAME, newContext = false, attributes = {}}){ this.tagName = tagName; this.newContext = newContext; this.attributes = attributes; } /** * verify if the provided node is has this property enabled * @method enabledAt * @param {RichNode} richNode to check * @return Boolean */ enabledAt(richNode) { if (!richNode) return false; if (richNode.type === 'tag') { if (this.newContext && tagName(richNode.domNode) !== this.tagName) { return false; } else { for (let key of Object.keys(this.attributes)) { const domNode = richNode.domNode; if (!domNode.hasAttribute(key)) return false; if (! domNode.getAttribute(key).includes(this.attributes[key])) return false; } return true; } return true; } return this.enabledAt(richNode.parent); } }
JavaScript
class MenuList extends React.Component { constructor(...args) { super(...args); this.filterHTML = this.filterHTML.bind(this); this.mainClasses = this.mainClasses.bind(this); this.menuItems = this.menuItems.bind(this); this.menuTitle = this.menuTitle.bind(this); this.onSearch = this.onSearch.bind(this); this.showMenuItems = this.showMenuItems.bind(this); this.toggleChildren = this.toggleChildren.bind(this); } static propTypes = { children: PropTypes.array.isRequired, className: PropTypes.string, filter: PropTypes.bool, title: PropTypes.string, collapsible: PropTypes.bool }; state = { filter: null, open: this.props.initiallyOpen || false } static defaultProps = { filter: false, collapsible: true } render() { return ( <div className={ this.mainClasses() } { ...tagComponent('menu-list', this.props) }> { this.menuTitle() } <ul className='carbon-menu-list__list'> { this.menuItems() } </ul> </div> ); } /** Actions **/ onSearch(ev) { this.setState({ filter: ev.target.value, open: true }); } toggleChildren(){ this.setState({ open: !this.state.open }); } /** Helpers **/ showMenuItems() { return (!this.props.title || !this.props.collapsible) || this.state.open; } /** Markup **/ filterHTML() { if (!this.props.filter) { return null; } return (<MenuListItem key={ 'filter' }><Textbox onChange={ this.onSearch } value={ this.state.filter || '' } autoFocus={ true } icon="search" placeholder={ this.props.filterPlaceholder } /></MenuListItem>); } mainClasses() { return classNames( "carbon-menu-list", this.props.className ); } menuItems() { if (this.showMenuItems()) { let items = this.props.children; if (this.props.filter && this.state.filter) { let regex = new RegExp(escapeStringRegexp(this.state.filter), 'i'); items = items.filter(child => child.props.name.search(regex) > -1); } return ([ this.filterHTML(), items ]); } } menuTitle() { if (!this.props.title) { return null; } return ( <Link className='carbon-menu-list__title' data-element='title' onClick={ this.toggleChildren } > { this.props.title } </Link> ); } }
JavaScript
class BinaryIsInPathCheck extends DoctorCheck { constructor (binary) { super(); this.binary = binary; } async diagnose () { let resolvedPath; try { let executable = system.isWindows() ? 'where' : 'which'; let {stdout} = await exec(executable, [this.binary]); if (stdout.match(/not found/gi)) { throw new Error('Not Found'); } resolvedPath = system.isWindows() ? stdout.split(EOL)[0] : stdout.replace(EOL, ''); } catch (err) { return nok(`${this.binary} is MISSING in PATH!`); } return await fs.exists(resolvedPath) ? ok(`${this.binary} was found at ${resolvedPath}`) : nok(`${this.binary} was found in PATH at '${resolvedPath}', but this is NOT a valid path!`); } fix () { return `Manually install the ${this.binary} binary and add it to PATH.`; } }
JavaScript
class Products extends BaseService { /** * Resource url. * @type { string } */ resourceUrl = 'products'; }
JavaScript
class TimeSeries extends React.PureComponent { static defaultProps = defaultProps; static propTypes = propTypes; constructor(props) { super(props); this.scaleX = scaleLinear(); this.scaleY = scaleLinear(); this.bisector = bisector(d => d[props.xKey]).left; } componentDidMount() { this.updateRender(); } UNSAFE_componentWillReceiveProps(nextProps) { if (this.props !== nextProps) { this.updateRender(); } } componentDidUpdate() { this.updateRender(); } onMouseEnter = (overLayLine, overLayCircle) => { this.tooltip.show(); overLayCircle .style('opacity', 1); overLayLine .style('opacity', 1); } onMouseLeave = (overLayLine, overLayCircle) => { this.tooltip.hide(); overLayCircle .style('opacity', 0); overLayLine .style('opacity', 0); } onMouseMove = (overLay, overLayLine, overLayCircle) => { const { data, xKey, yKey, tooltipRender } = this.props; const x0 = this.scaleX.invert(mouse(overLay.node())[0]); const i = this.bisector(data, x0); const d0 = data[i - 1]; const d1 = data[i]; let d; if (d0 && d1) { d = x0 - d0[xKey] > d1[xKey] - x0 ? d1 : d0; } else { d = d0 || d1; } if (!d) { this.onMouseLeave(overLayLine, overLayCircle); return; } const { x, y } = overLay.node().getBoundingClientRect(); const xPoint = this.scaleX(d[xKey] || 0); const yPoint = this.scaleY(d[yKey] || 0); this.tooltip.setTooltip(tooltipRender(d)); this.tooltip.move({ x: xPoint + x, y: y + yPoint, orentation: 'right', padding: 10, duration: 30, }); overLayCircle .transition() .duration(30) .attr('cx', xPoint || 0) .attr('cy', yPoint || 0); overLayLine .transition() .duration(30) .attr('x', xPoint || 0); } getXTickValues = ([min, max]) => { const { xTicks = this.scaleX.ticks().length } = this.props; const interval = Math.floor((max - min) / xTicks); const values = [max]; for (let i = min; i < max; i += interval) { values.push(i); } return values; } setTooltip = (tooltip) => { this.tooltip = tooltip; } updateRender() { const { margins: { right, top, left, bottom, }, boundingClientRect: { height, width, }, } = this.props; if (!width) { return; } const svgHeight = height - bottom - top; const svgWidth = width - right - left; this.scaleX.range([0, svgWidth]); this.scaleY.range([svgHeight, 0]); this.renderBarChart(svgHeight, svgWidth); } renderBarChart(height, width) { const { data, xKey, yKey, yTicks, margins, xTickFormat, yTickFormat, showArea, } = this.props; const { top, left } = margins; this.scaleX.domain(extent(data.map(d => d[xKey]))); this.scaleY.domain(extent(data.map(d => d[yKey]))); const svg = select(this.svg); svg.select('*').remove(); if (data.length === 0) { return; } const xTickValues = this.getXTickValues(this.scaleX.domain()); const xAxis = axisBottom(this.scaleX) .tickSizeInner(-height) // .tickSizeOuter(0) .tickFormat(xTickFormat) // .ticks(5) .tickValues(xTickValues); const yAxis = axisLeft(this.scaleY) .tickSizeInner(-width) .tickSizeOuter(0) .tickFormat(yTickFormat); if (yTicks) { yAxis.ticks(yTicks); } const line = d3Line() // .curve(curveMonotoneX) .x(d => this.scaleX(d[xKey] || 0)) .y(d => this.scaleY(d[yKey] || 0)); const root = svg.append('g') .attr('transform', `translate(${left},${top})`); root.append('g') .attr('class', 'axis axis--x') .attr('transform', `translate(0, ${height})`) .call(xAxis); root.append('g') .attr('class', 'axis axis--y') .call(yAxis); if (showArea) { const lineArea = area() // .curve(curveMonotoneX) .x(d => this.scaleX(d[xKey] || 0)) .y1(d => this.scaleY(d[yKey] || 0)) .y0(height); root.append('g') .attr('class', 'time-area') .append('path') .data([data]) .attr('d', lineArea); } root.append('g') .attr('class', 'time-path') .append('path') .data([data]) .attr('d', line); const overLayLine = root.append('rect') .attr('class', 'overlay-line') .attr('width', 0.1) .attr('x', 0) .attr('height', height) .style('opacity', 0); const overLayCircle = root.append('circle') .attr('class', 'overlay-circle') .attr('cx', 0) .attr('cy', 0) .attr('r', 3) .style('opacity', 0); const overLay = root.append('rect') .attr('class', 'overlay') .attr('width', width) .attr('height', height) .on('mouseenter', () => this.onMouseEnter(overLayLine, overLayCircle)) .on('mouseleave', () => this.onMouseLeave(overLayLine, overLayCircle)) .on('mousemove', () => this.onMouseMove(overLay, overLayLine, overLayCircle)); } render() { const { className } = this.props; return ( <div className={`${className} ${styles.timeSeries}`}> <svg ref={(svg) => { this.svg = svg; }} /> <Tooltip setTooltipApi={this.setTooltip} /> </div> ); } }
JavaScript
class SvgInstagramLoader extends SvgContentLoader { /** * Attached Event */ attached(...args) { super.attached && super.attached(...args); this.addClass('svg-loader__inner--instagram'); } /** * @var {Number} */ get instagramImageY() { return this.imageDiameter + 20; } /** * @return {Number} */ get instagramImageHeight() { let height = this.height - this.instagramImageY; if (height <= 0 && !this.logged) { console.warn('Instagram loader height too small.'); // eslint-disable-line no-console this.logged = false; } return height < 0 ? 0 : height; } /** * Getter - Compute the space between the title lines. * @return {Number} */ get titleLineSpace() { return Math.floor((this.imageDiameter - 2 * this.lineHeight) / 3); } /** * Getter - Compute the width of the first title line. * @return {Number} */ get firstTitleLineWidth() { return Math.floor(this.width - this.imageDiameter - 10); } /** * Getter - Compute the width of the seccond title line. * @return {Number} */ get seccondTitleLineWidth() { return Math.floor(this.firstTitleLineWidth * 0.8); } }
JavaScript
class SortParagraphsParagraph { /** * @constructor * @param {object} params Parameters. * @param {string} params.text Paragraph text. * @param {object} params.l10n Titles for move buttons. * @param {object} callbacks Callback functions. * @param {function} [callbacks.onMoveUp] Callback button move up. * @param {function} [callbacks.onMoveDown] Callback button move down. * @param {function} [callbacks.onFocusOut] Callback paragraph loses focus. * @param {function} [callbacks.onDragStart] Callback drag start. * @param {function} [callbacks.onDragOver] Callback drag over. * @param {function} [callbacks.onDragEnter] Callback drag enter. * @param {function} [callbacks.onDragLeave] Callback drag leave. * @param {function} [callbacks.onDragEnd] Callback drag end. * @param {function} [callbacks.onKeyboardUp] Callback keyboard up. * @param {function} [callbacks.onKeyboardDown] Callback keyboard down. * @param {function} [callbacks.onKeyboardSelect] Callback keyboard select. * @param {function} [callbacks.onKeyboardCancel] Callback keyboard cancel. */ constructor(params, callbacks) { this.text = params.text; this.l10n = params.l10n; // Callbacks for button movement this.callbacks = callbacks || {}; this.callbacks.onMoveUp = this.callbacks.onMoveUp || (() => {}); this.callbacks.onMoveDown = this.callbacks.onMoveDown || (() => {}); // Callbacks for dragging this.callbacks.onFocusOut = this.callbacks.onFocusOut || (() => {}); this.callbacks.onDragStart = this.callbacks.onDragStart || (() => {}); this.callbacks.onDragOver = this.callbacks.onDragOver || (() => {}); this.callbacks.onDragEnter = this.callbacks.onDragEnter || (() => {}); this.callbacks.onDragLeave = this.callbacks.onDragLeave || (() => {}); this.callbacks.onDragEnd = this.callbacks.onDragEnd || (() => {}); // Callbacks for keyboard movement this.callbacks.onKeyboardUp = this.callbacks.onKeyboardUp || (() => {}); this.callbacks.onKeyboardDown = this.callbacks.onKeyboardDown || (() => {}); this.callbacks.onKeyboardSelect = this.callbacks.onKeyboardSelect || (() => {}); this.callbacks.onKeyboardCancel = this.callbacks.onKeyboardCancel || (() => {}); this.callbacks.onMouseSelect = this.callbacks.onMouseSelect || (() => {}); // Buttons this.buttons = []; // Build content this.content = this.buildParagraph(this.text, this.l10n); } /** * Return the DOM for this class. * @return {HTMLElement} DOM for this class. */ getDOM() { return this.content; } /** * Build Paragraph. */ buildParagraph() { const paragraph = document.createElement('div'); paragraph.classList.add('h5p-sort-paragraphs-paragraph'); paragraph.setAttribute('role', 'option'); paragraph.setAttribute('draggable', true); // Left container for information const containerLeft = this.buildContainerLeft(); paragraph.appendChild(containerLeft); this.buttons['up'] = this.buildButtonUp(); containerLeft.appendChild(this.buttons['up'].getDOM()); // Container for correct/wrong markers this.containerCorrections = this.buildContainerCorrections(); containerLeft.appendChild(this.containerCorrections); // Conatainer for paragraph text this.containerText = this.buildContainerText(); paragraph.appendChild(this.containerText); // Right container for information const containerRight = this.buildContainerRight(); paragraph.appendChild(containerRight); this.buttons['down'] = this.buildButtonDown(); containerRight.appendChild(this.buttons['down'].getDOM()); // H5P Question score explanations this.scoreExplanations = this.buildScoreExplanations(); containerRight.appendChild(this.scoreExplanations); // Handlers this.addKeyboardHandlers(paragraph); this.addDragHandlers(paragraph); return paragraph; } /** * Build left container for additional elements. * @return {HTMLElement} Left container for additional elements. */ buildContainerLeft() { const paragraphContentLeft = document.createElement('div'); paragraphContentLeft.classList.add('h5p-sort-paragraphs-paragraph-container-left'); return paragraphContentLeft; } /** * Build button for moving up. * @return {Button} Button for moving up. */ buildButtonUp() { return new Button( { a11y: { active: this.l10n.up, disabled: this.l10n.disabled }, classes: ['h5p-sort-paragraphs-button', 'h5p-sort-paragraphs-paragraph-button-up'] }, { onClick: (() => { this.callbacks.onMoveUp(this.content); }) } ); } /** * Build container for corrections. * @return {HTMLElement} Container for corrections. */ buildContainerCorrections() { const corrections = document.createElement('div'); corrections.classList.add('h5p-sort-paragraphs-paragraph-corrections'); return corrections; } /** * Build text container. * @return {HTMLElement} Text container. */ buildContainerText() { const content = document.createElement('div'); content.classList.add('h5p-sort-paragraphs-paragraph-container'); content.innerHTML = this.text; return content; } /** * Build right container for additional elements. * @return {HTMLElement} Right container for additional elements. */ buildContainerRight() { const contentRight = document.createElement('div'); contentRight.classList.add('h5p-sort-paragraphs-paragraph-container-right'); return contentRight; } /** * Build button for moving down. * @return {Button} Button for moving down. */ buildButtonDown() { return new Button( { a11y: { active: this.l10n.down, disabled: this.l10n.disabled }, classes: ['h5p-sort-paragraphs-button', 'h5p-sort-paragraphs-paragraph-button-down'] }, { onClick: (() => { this.callbacks.onMoveDown(this.content); }) } ); } /** * Build H5P Question score explanations holder. * @return {HTMLElement} H5P Question score explanations holder. */ buildScoreExplanations() { const explanations = document.createElement('div'); explanations.classList.add('h5p-sort-paragraphs-paragraph-score-explanations'); return explanations; } /** * Add keyboard handlers to paragraph. * @param {HTMLElement} paragraph Paragraph. */ addKeyboardHandlers(paragraph) { paragraph.addEventListener('keydown', event => { switch (event.keyCode) { case 38: // Up event.preventDefault(); // No scrolling if (event.currentTarget === event.currentTarget.parentNode.firstChild) { return; // Skip, already top paragraph } this.callbacks.onKeyboardUp(event.currentTarget); break; case 40: // Down event.preventDefault(); // No scrolling if (event.currentTarget === event.currentTarget.parentNode.lastChild) { return; // Skip, already bottom paragraph } this.callbacks.onKeyboardDown(event.currentTarget); break; case 13: // Return // Intentional fallthrough case 32: // Space // Toggle state this.callbacks.onKeyboardSelect(event.currentTarget); break; case 27: // Escape this.callbacks.onKeyboardCancel(event.currentTarget); break; // TODO: Add handling for PageUp and PageDown } }); } /** * Add drag handlers to paragraph. * @param {HTMLElement} paragraph Paragraph. */ addDragHandlers(paragraph) { // Mouse down. Prevent dragging when using buttons. paragraph.addEventListener('mousedown', event => { if ( event.target === this.buttons['up'].getDOM() || event.target === this.buttons['down'].getDOM() ) { this.content.setAttribute('draggable', false); } }); // Mouse up. Allow dragging after using buttons. paragraph.addEventListener('mouseup', event => { if ( event.target === this.buttons['up'].getDOM() || event.target === this.buttons['down'].getDOM() ) { this.content.setAttribute('draggable', true); } else { this.callbacks.onMouseSelect(event.currentTarget); } }); // Focus out paragraph.addEventListener('focusout', event => { this.toggleEffect('selected', false); this.callbacks.onFocusOut(event.currentTarget); }); // Drag start paragraph.addEventListener('dragstart', event => { if (this.disabled) { return; } this.toggleEffect('over', true); this.toggleEffect('ghosted', true); event.dataTransfer.effectAllowed = 'move'; this.callbacks.onDragStart(event.currentTarget); }); // Drag over paragraph.addEventListener('dragover', event => { event.preventDefault(); this.callbacks.onDragOver(event.currentTarget); }); // Drag enter paragraph.addEventListener('dragenter', event => { this.callbacks.onDragEnter(event.currentTarget); }); // Drag leave paragraph.addEventListener('dragleave', event => { if (paragraph !== event.target || paragraph.contains(event.fromElement)) { return; } this.callbacks.onDragLeave(event.currentTarget); }); // Drag end paragraph.addEventListener('dragend', (event) => { this.toggleEffect('over', false); this.toggleEffect('ghosted', false); this.callbacks.onDragEnd(event.currentTarget); }); // Prevent visual dragging mode on mobile paragraph.addEventListener('touchstart', (event) => { if (!event.cancelable || this.disabled) { return; } paragraph.setAttribute('draggable', false); }); // Allow dragging again, device might allow mouse and touch paragraph.addEventListener('touchend', () => { if (this.disabled) { return; } paragraph.setAttribute('draggable', true); }); } /** * Enable paragraph. Paragraph movable via dragging or buttons. */ enable() { this.content.setAttribute('draggable', true); this.toggleEffect('disabled', false); for (let id in this.buttons) { this.buttons[id].enable(); } this.disabled = false; } /** * Disable paragraph. Paragraph not movable via dragging or buttons. */ disable() { this.disabled = true; this.content.setAttribute('draggable', false); this.toggleEffect('disabled', true); for (let id in this.buttons) { this.buttons[id].disable(); } } /** * Focus paragraph. */ focus() { this.content.focus(); } /** * Get paragraph's HTML text. * @return {string} HTML text. */ getText() { return this.containerText.innerHTML; } /** * Set HTML text. * @param {string} text HTML text. */ setText(text) { if (typeof text !== 'string') { return; } this.containerText.innerHTML = text; } /** * Set tab index. * @param {number} tabIndex TabIndex. */ setTabIndex(tabIndex) { if (typeof tabIndex !== 'number') { return; } this.content.setAttribute('tabIndex', tabIndex); } /** * Reset. */ reset() { this.content.classList.remove('disabled'); this.content.classList.remove('solution'); } /** * Show buttons container. */ showButtons() { for (let button in this.buttons) { this.buttons[button].show(); } } /** * Hide buttons container. */ hideButtons() { for (let button in this.buttons) { this.buttons[button].hide(); } } /** * Toggle button enabled state. * @param {string|number} id Id of button. * @param {boolean} enabled If true, set button enabled, else disabled. */ toggleButton(id, enabled) { if (!id || !this.buttons[id] || typeof enabled !== 'boolean') { return; } if (enabled) { this.buttons[id].enable(); } else { this.buttons[id].disable(); } } /** * Toggle CSS class named after an effect. * @param {string} effectName Effect name. * @param {boolean} enabled If true, effect will be set, else unset. */ toggleEffect(effectName, enabled) { const effects = ['over', 'ghosted', 'disabled', 'selected', 'correct', 'wrong', 'solution']; if (typeof enabled !== 'boolean' || effects.indexOf(effectName) === -1) { return; } if (enabled) { this.content.classList.add(`h5p-sort-paragraphs-${effectName}`); } else { this.content.classList.remove(`h5p-sort-paragraphs-${effectName}`); } } /** * Set aria label. * @param {string} ariaLabel Aria label. */ setAriaLabel(ariaLabel) { this.content.setAttribute('aria-label', ariaLabel); } /** * Add H5P Question score explanation. * @param {HTMLElement} explanation H5P Question score explanation. */ showScoreExplanation(explanation) { this.scoreExplanations.appendChild(explanation); } /** * Remove H5P Question score explanation. */ removeScoreExplanation() { this.scoreExplanations.innerHTML = ''; } }
JavaScript
class TablePropertiesUI extends Plugin { /** * @inheritDoc */ static get requires() { return [ ContextualBalloon ]; } /** * @inheritDoc */ static get pluginName() { return 'TablePropertiesUI'; } /** * @inheritDoc */ constructor( editor ) { super( editor ); editor.config.define( 'table.tableProperties', { borderColors: defaultColors, backgroundColors: defaultColors } ); } /** * @inheritDoc */ init() { const editor = this.editor; const t = editor.t; /** * The contextual balloon plugin instance. * * @private * @member {module:ui/panel/balloon/contextualballoon~ContextualBalloon} */ this._balloon = editor.plugins.get( ContextualBalloon ); /** * The properties form view displayed inside the balloon. * * @member {module:table/tableproperties/ui/tablepropertiesview~TablePropertiesView} */ this.view = this._createPropertiesView(); /** * The batch used to undo all changes made by the form (which are live, as the user types) * when "Cancel" was pressed. Each time the view is shown, a new batch is created. * * @protected * @member {module:engine/model/batch~Batch} */ this._undoStepBatch = null; editor.ui.componentFactory.add( 'tableProperties', locale => { const view = new ButtonView( locale ); view.set( { label: t( 'Table properties' ), icon: tableProperties, tooltip: true } ); this.listenTo( view, 'execute', () => this._showView() ); const commands = Object.values( propertyToCommandMap ) .map( commandName => editor.commands.get( commandName ) ); view.bind( 'isEnabled' ).toMany( commands, 'isEnabled', ( ...areEnabled ) => ( areEnabled.some( isCommandEnabled => isCommandEnabled ) ) ); return view; } ); } /** * @inheritDoc */ destroy() { super.destroy(); // Destroy created UI components as they are not automatically destroyed. // See https://github.com/ckeditor/ckeditor5/issues/1341. this.view.destroy(); } /** * Creates the {@link module:table/tableproperties/ui/tablepropertiesview~TablePropertiesView} instance. * * @private * @returns {module:table/tableproperties/ui/tablepropertiesview~TablePropertiesView} The table * properties form view instance. */ _createPropertiesView() { const editor = this.editor; const viewDocument = editor.editing.view.document; const config = editor.config.get( 'table.tableProperties' ); const borderColorsConfig = normalizeColorOptions( config.borderColors ); const localizedBorderColors = getLocalizedColorOptions( editor.locale, borderColorsConfig ); const backgroundColorsConfig = normalizeColorOptions( config.backgroundColors ); const localizedBackgroundColors = getLocalizedColorOptions( editor.locale, backgroundColorsConfig ); const view = new TablePropertiesView( editor.locale, { borderColors: localizedBorderColors, backgroundColors: localizedBackgroundColors } ); const t = editor.t; // Render the view so its #element is available for the clickOutsideHandler. view.render(); this.listenTo( view, 'submit', () => { this._hideView(); } ); this.listenTo( view, 'cancel', () => { // https://github.com/ckeditor/ckeditor5/issues/6180 if ( this._undoStepBatch.operations.length ) { editor.execute( 'undo', this._undoStepBatch ); } this._hideView(); } ); // Close the balloon on Esc key press. view.keystrokes.set( 'Esc', ( data, cancel ) => { this._hideView(); cancel(); } ); // Reposition the balloon or hide the form if a table is no longer selected. this.listenTo( editor.ui, 'update', () => { if ( !getTableWidgetAncestor( viewDocument.selection ) ) { this._hideView(); } else if ( this._isViewVisible ) { repositionContextualBalloon( editor, 'table' ); } } ); // Close on click outside of balloon panel element. clickOutsideHandler( { emitter: view, activator: () => this._isViewInBalloon, contextElements: [ this._balloon.view.element ], callback: () => this._hideView() } ); const colorErrorText = getLocalizedColorErrorText( t ); const lengthErrorText = getLocalizedLengthErrorText( t ); // Create the "UI -> editor data" binding. // These listeners update the editor data (via table commands) when any observable // property of the view has changed. They also validate the value and display errors in the UI // when necessary. This makes the view live, which means the changes are // visible in the editing as soon as the user types or changes fields' values. view.on( 'change:borderStyle', this._getPropertyChangeCallback( 'tableBorderStyle' ) ); view.on( 'change:borderColor', this._getValidatedPropertyChangeCallback( { viewField: view.borderColorInput, commandName: 'tableBorderColor', errorText: colorErrorText, validator: colorFieldValidator } ) ); view.on( 'change:borderWidth', this._getValidatedPropertyChangeCallback( { viewField: view.borderWidthInput, commandName: 'tableBorderWidth', errorText: lengthErrorText, validator: lineWidthFieldValidator } ) ); view.on( 'change:backgroundColor', this._getValidatedPropertyChangeCallback( { viewField: view.backgroundInput, commandName: 'tableBackgroundColor', errorText: colorErrorText, validator: colorFieldValidator } ) ); view.on( 'change:width', this._getValidatedPropertyChangeCallback( { viewField: view.widthInput, commandName: 'tableWidth', errorText: lengthErrorText, validator: lengthFieldValidator } ) ); view.on( 'change:height', this._getValidatedPropertyChangeCallback( { viewField: view.heightInput, commandName: 'tableHeight', errorText: lengthErrorText, validator: lengthFieldValidator } ) ); view.on( 'change:alignment', this._getPropertyChangeCallback( 'tableAlignment' ) ); return view; } /** * In this method the "editor data -> UI" binding is happening. * * When executed, this method obtains selected table property values from various table commands * and passes them to the {@link #view}. * * This way, the UI stays up–to–date with the editor data. * * @private */ _fillViewFormFromCommandValues() { const commands = this.editor.commands; Object.entries( propertyToCommandMap ) .map( ( [ property, commandName ] ) => [ property, commands.get( commandName ).value || '' ] ) .forEach( ( [ property, value ] ) => this.view.set( property, value ) ); } /** * Shows the {@link #view} in the {@link #_balloon}. * * **Note**: Each time a view is shown, the new {@link #_undoStepBatch} is created that contains * all changes made to the document when the view is visible, allowing a single undo step * for all of them. * * @protected */ _showView() { const editor = this.editor; this._balloon.add( { view: this.view, position: getBalloonTablePositionData( editor ) } ); // Create a new batch. Clicking "Cancel" will undo this batch. this._undoStepBatch = editor.model.createBatch(); // Update the view with the model values. this._fillViewFormFromCommandValues(); // Basic a11y. this.view.focus(); } /** * Removes the {@link #view} from the {@link #_balloon}. * * @protected */ _hideView() { if ( !this._isViewInBalloon ) { return; } const editor = this.editor; this.stopListening( editor.ui, 'update' ); // Blur any input element before removing it from DOM to prevent issues in some browsers. // See https://github.com/ckeditor/ckeditor5/issues/1501. this.view.saveButtonView.focus(); this._balloon.remove( this.view ); // Make sure the focus is not lost in the process by putting it directly // into the editing view. this.editor.editing.view.focus(); } /** * Returns `true` when the {@link #view} is the visible in the {@link #_balloon}. * * @private * @type {Boolean} */ get _isViewVisible() { return this._balloon.visibleView === this.view; } /** * Returns `true` when the {@link #view} is in the {@link #_balloon}. * * @private * @type {Boolean} */ get _isViewInBalloon() { return this._balloon.hasView( this.view ); } /** * Creates a callback that when executed upon {@link #view view's} property change * executes a related editor command with the new property value. * * @private * @param {String} commandName * @returns {Function} */ _getPropertyChangeCallback( commandName ) { return ( evt, propertyName, newValue ) => { this.editor.execute( commandName, { value: newValue, batch: this._undoStepBatch } ); }; } /** * Creates a callback that when executed upon {@link #view view's} property change: * * executes a related editor command with the new property value if the value is valid, * * or sets the error text next to the invalid field, if the value did not pass the validation. * * @private * @param {Object} options * @param {String} options.commandName * @param {module:ui/view~View} options.viewField * @param {Function} options.validator * @param {String} options.errorText * @returns {Function} */ _getValidatedPropertyChangeCallback( { commandName, viewField, validator, errorText } ) { const setErrorTextDebounced = debounce( () => { viewField.errorText = errorText; }, ERROR_TEXT_TIMEOUT ); return ( evt, propertyName, newValue ) => { setErrorTextDebounced.cancel(); if ( validator( newValue ) ) { this.editor.execute( commandName, { value: newValue, batch: this._undoStepBatch } ); viewField.errorText = null; } else { setErrorTextDebounced(); } }; } }
JavaScript
class EventEmbed extends BaseEmbed { /** * @param {Genesis} bot - An instance of Genesis * @param {Event} event - The deal to be included in the embed * @param {string} platform - The platform the event is for */ constructor(bot, event, platform) { super(); this.color = 0xfdec96; if (event) { this.title = `[${platform.toUpperCase()}] ${event.description}`; this.fields = []; this.description = event.tooltip; if (event.victimNode) { let vicDef = ''; if (event.faction) { vicDef += ` by attacking the ${event.faction}`; } if (event.node) { vicDef += ` at ${event.node}`; } this.fields.push({ name: '_ _', value: `Defend ${event.victimNode}${vicDef}.`, }); } if (event.rewards && event.rewards.length > 0) { this.fields.push({ name: 'Rewards', value: event.rewards ? event .rewards.map(reward => reward.asString).join('; ') : 'No Rewards', }); } if (event.maximumScore) { this.fields.push({ name: 'Completion Score', value: String(event.maximumScore) }); } if (event.affiliatedWith) { const jobString = event.jobs.map((job) => { const rewards = job.rewardPool.length > 0 ? job.rewardPool.map(reward => `* ${reward}`).join('\n') : 'No Clear Reward'; const rewardsFmtd = `\nWith \`\`\`haskell\n${rewards}\`\`\` as reward${job.rewardPool.length > 1 ? 's' : ''}.`; const desc = `**${job.type}**\nEnemies lvls ${job.enemyLevels[0]} - ${job.enemyLevels[1]}\n` + `Granting ${job.standingStages.join(', ')} base standing per stage.${job.rewardPool.length > 0 ? rewardsFmtd : ''}`; return desc; }).join('\n'); this.fields.push({ name: `Jobs from ${event.affiliatedWith}`, value: jobString }); } if (event.health && event.health !== '0.00') { this.footer.text = `${event.health}% Remaining`; } } else { this.title = 'No Current Events'; } } }
JavaScript
class FlipX extends ActionInstant { /** * PUBLIC METHODS * ----------------------------------------------------------------------------------------------------------------- */ update(dt) { if (!Type.isEmpty(this.target.flipX)) { this.target.flipX = !this.target.flipX; return; } this.target.scale.x = -this.target.scale.x; } /** * @desc Need to copy object with deep copy. Returns a clone of action. * @method * @public * @return {MANTICORE.animation.action.FlipX} */ clone(){ return FlipX.create(); } /** * @desc Returns a reversed action. * @method * @public * @return {MANTICORE.animation.action.FlipX} */ reverse () { return FlipX.create(); } }
JavaScript
class EmailServiceAPICallHookModel extends ModelBase { /** * Constructor for email service api call hook model. * * @augments ModelBase * * @constructor */ constructor() { super({ dbName: dbName }); const oThis = this; oThis.tableName = 'email_service_api_call_hooks'; } /** * Format Db data. * * @param {object} dbRow * * @return {object} */ formatDbData(dbRow) { const oThis = this; const formattedData = { id: dbRow.id, receiverEntityId: dbRow.receiver_entity_id, receiverEntityKind: dbRow.receiver_entity_kind, eventType: emailServiceApiCallHookConstants.eventKinds[dbRow.event_type], customDescription: dbRow.custom_description, executionTimestamp: dbRow.execution_timestamp, lockIdentifier: dbRow.lock_identifier, lockedAt: dbRow.locked_at, status: emailServiceApiCallHookConstants.statuses[dbRow.status], failedCount: dbRow.failed_count, params: JSON.parse(dbRow.params), successResponse: JSON.parse(dbRow.success_response), failedResponse: JSON.parse(dbRow.failed_response), createdAt: dbRow.created_at, updatedAt: dbRow.updated_at }; return oThis.sanitizeFormattedData(formattedData); } /** * Function to acquire lock on fresh hooks. * * @param {string} lockIdentifier * * @returns {Promise<any>} */ async acquireLocksOnFreshHooks(lockIdentifier) { const oThis = this; return oThis .update({ lock_identifier: lockIdentifier, locked_at: Math.round(Date.now() / 1000) }) .where('lock_identifier IS NULL') .where(['execution_timestamp < ?', Math.round(Date.now() / 1000)]) .where([ 'status = ?', emailServiceApiCallHookConstants.invertedStatuses[emailServiceApiCallHookConstants.pendingStatus] ]) .limit(emailServiceApiCallHookConstants.batchSizeForHooksProcessor) .fire(); } /** * Function to acquire lock on failed hooks. * * @param {string} lockIdentifier * * @returns {Promise<any>} */ async acquireLocksOnFailedHooks(lockIdentifier) { const oThis = this; return oThis .update({ lock_identifier: lockIdentifier, locked_at: Math.round(Date.now() / 1000) }) .where('lock_identifier IS NULL') .where(['failed_count <= ?', emailServiceApiCallHookConstants.retryLimitForFailedHooks]) .where([ 'status = ?', emailServiceApiCallHookConstants.invertedStatuses[emailServiceApiCallHookConstants.failedStatus] ]) .limit(emailServiceApiCallHookConstants.batchSizeForHooksProcessor) .fire(); } /** * Function to fetch locked hooks. * * @param {string} lockIdentifier * * @returns {Promise<void>} */ async fetchLockedHooks(lockIdentifier) { const oThis = this; const response = {}; const dbRows = await oThis .select('*') .where(['lock_identifier = ?', lockIdentifier]) .fire(); for (let index = 0; index < dbRows.length; index++) { const formatDbRow = oThis.formatDbData(dbRows[index]); response[formatDbRow.id] = formatDbRow; } return response; } /** * Mark status as processed. * * @param {number} hookId * @param {object} successResponse * * @returns {Promise<void>} */ async markStatusAsProcessed(hookId, successResponse) { const oThis = this; await oThis .update({ lock_identifier: null, locked_at: null, success_response: JSON.stringify(successResponse), status: emailServiceApiCallHookConstants.invertedStatuses[emailServiceApiCallHookConstants.processedStatus] }) .where(['id = ?', hookId]) .fire(); } /** * Mark hook as failed. * * @param {number} hookId * @param {number} failedCount * @param {object} failedLogs * * @returns {Promise<void>} */ async markFailedToBeRetried(hookId, failedCount, failedLogs) { const oThis = this; await oThis .update({ status: emailServiceApiCallHookConstants.invertedStatuses[emailServiceApiCallHookConstants.failedStatus], failed_count: failedCount + 1, lock_identifier: null, locked_at: null, failed_response: JSON.stringify(failedLogs) }) .where(['id = ?', hookId]) .fire(); } /** * Mark hooks as ignored. * * @param {number} hookId * @param {number} failedCount * @param {object} failedLogs * * @returns {Promise<void>} */ async markFailedToBeIgnored(hookId, failedCount, failedLogs) { const oThis = this; await oThis .update({ status: emailServiceApiCallHookConstants.invertedStatuses[emailServiceApiCallHookConstants.ignoredStatus], failed_count: failedCount + 1, lock_identifier: null, locked_at: null, failed_response: JSON.stringify(failedLogs) }) .where(['id = ?', hookId]) .fire(); } }
JavaScript
class Token extends TokenMongoose { /** * You can modify the amount of days that the token will be valid */ static expires () { return 5 } /** * You can modify the default schema */ static get schema () { // Edit your schema here return super.schema } /** * Customize populated properties for the user */ static getUserFields (type) { return '_id email' } }
JavaScript
class User extends Model { /** * get ViewModel class bind with Model * @return {ViewModel} - ViewModel class */ getViewModel() { return require('../vm/User'); } }
JavaScript
class dataFetcher { constructor(dataInfo) { this.source = dataInfo.source; this.url = dataInfo.url; this.dataRaw = null; } async fetch() { switch (this.source) { case "local": this.dataRaw = await this.localFetch(); break; case "remote": this.dataRaw = await this.remoteFetch(); break; default: this.dataRaw = null; break; } return this.dataRaw; } async localFetch() { return await Data[this.url]; } async remoteFetch() { return await tryAsync(fetch)(this.url); } }
JavaScript
class dataParser { constructor(dataInfo) { this.type = dataInfo.type; this.data = null; } async parse(dataRaw) { switch (this.type) { case "csv": this.data = await this.csv(dataRaw); break; case "json": this.data = await this.json(dataRaw); break; case "xml": this.data = await this.xml(dataRaw); break; case "text": this.data = await this.text(dataRaw); default: break; } return this.data; } /* CSV Parser: * Local: an array of rows * Remote: a string */ csv = trySync(dataRaw => { return d3.csvParse( typeof dataRaw === "object" ? dataRaw.join("\n") : dataRaw ); }); /* JSON Parser: * Local: the json object * Remote: a json string */ json = trySync(dataRaw => { return typeof dataRaw === "object" ? dataRaw : JSON.parse(dataRaw); }); /* XML Parser: * Local & Remote: the xml string */ xml = trySync(dataRaw => { return new DOMParser().parseFromString(dataRaw, "text/xml"); }); /* XML Parser: * Local & Remote: the xml string */ text = trySync(dataRaw => { return dataRaw; }); }
JavaScript
class AliasTargetInstance extends instance_1.InstanceBase { /** * @stability stable */ constructor(scope, id, props) { super(scope, id); if (props.service.namespace.type === namespace_1.NamespaceType.HTTP) { throw new Error('Namespace associated with Service must be a DNS Namespace.'); } // Should already be enforced when creating service, but validates if service is not instantiated with #createService const dnsRecordType = props.service.dnsRecordType; if (dnsRecordType !== service_1.DnsRecordType.A && dnsRecordType !== service_1.DnsRecordType.AAAA && dnsRecordType !== service_1.DnsRecordType.A_AAAA) { throw new Error('Service must use `A` or `AAAA` records to register an AliasRecordTarget.'); } if (props.service.routingPolicy !== service_1.RoutingPolicy.WEIGHTED) { throw new Error('Service must use `WEIGHTED` routing policy.'); } const resource = new servicediscovery_generated_1.CfnInstance(this, 'Resource', { instanceAttributes: { AWS_ALIAS_DNS_NAME: props.dnsName, ...props.customAttributes, }, instanceId: props.instanceId || core_1.Names.uniqueId(this), serviceId: props.service.serviceId, }); this.service = props.service; this.instanceId = resource.ref; this.dnsName = props.dnsName; } }
JavaScript
class DeepZoomInfo { constructor(attrs) { for (let key in attrs) { this[key] = attrs[key] } this.maxLevel = 0 // The highest level number, typically corresponds to the // number in the file system for the folder with tiles this.clip = this.clip || null // e.g. { level: 12, col: 301436, row: 354060 } this.type = this.type || 'dzi' this.urlTileTemplate = this.urlTileTemplate || '{path}/{level}/{column}_{row}.{format}' this.setupDimensions() } /* Computes the needed number of layers from the width and height * of the image. Note that this includes the level 0, i.e. 0 ... 4 * means that 5 levels exist. **/ numLevels() { let maxDimension = Math.max(this.width, this.height) let boundary = this.type === 'dzi' ? 1 : this.tileSize let numLevels = 0 while (maxDimension >= boundary) { maxDimension /= 2 numLevels++ } return numLevels } /** Computes the scale at the given level. * @param {number} level - The level of the wanted layer * @returns {number} scale **/ getScale(level) { let scale = 1 if (this.type === 'dzi') { scale = Math.pow(0.5, this.maxLevel - level + 1) } else { scale = Math.pow(0.5, this.maxLevel - level) } return scale } /** Computes the scaled width and height of the given level. * @param {number} level - The level of the wanted layer * @returns {array} size - The width and height **/ getDimensions(level) { let scale = this.getScale(level) let w = Math.ceil(this.width * scale) let h = Math.ceil(this.height * scale) return [w, h] } /** Computes the number of cols and rows of tiles. * @param {number} level - The level of the wanted layer * @returns {array} size - The cols and rows **/ getNumTiles(level) { let dim = this.getDimensions(level) let cols = Math.ceil(dim[0] / this.tileSize) let rows = Math.ceil(dim[1] / this.tileSize) if (this.clip) { let rest = this.rests[level] if (rest) { if (rest.restCol) { cols += 1 } if (rest.restRows) { rows += 1 } } } return [cols, rows] } setupDimensions(loadBaseImage = false) { /** Setup instance variables and load the base image, i.e. the largest image that can be represented as a single tile. @private **/ let ww = this.width let hh = this.height let scale = 1.0 let level = 0 let single = 0 const tsize = this.tileSize if (this.clip) { this.baseLevel = this.clip.minLevel this.maxLevel = this.clip.maxLevel this.baseImage = null this.size = this.getDimensions(this.baseLevel) this.offsets = {} this.rests = {} let startCol = this.clip.startCol let startRow = this.clip.startRow let floatStartCol = startCol let floatStartRow = startRow for (let i = this.maxLevel; i >= this.baseLevel; i--) { this.offsets[i] = {startCol, startRow} let restCol = floatStartCol % 1 let restRow = floatStartRow % 1 this.rests[i] = {restCol, restRow} startCol = Math.floor(startCol / 2) startRow = Math.floor(startRow / 2) floatStartCol /= 2 floatStartRow /= 2 } } else { const boundary = this.type === 'dzi' ? 1.0 : tsize while (ww > boundary && hh > boundary) { if (ww >= tsize && hh >= tsize) { single += 1 } scale = scale / 2.0 ww = Math.ceil(this.width * scale) hh = Math.ceil(this.height * scale) level += 1 } this.baseLevel = level - single this.maxLevel = this.numLevels() - 1 this.baseURL = this.urlForTile(this.baseLevel, 0, 0, false) if (loadBaseImage) { this.imageForURL(this.baseURL, e => { this.size = [e.target.naturalWidth, e.target.naturalHeight] this.baseImage = e.target }) } else { this.baseImage = null this.size = this.getDimensions(this.baseLevel) } } } get maxLoadableLevel() { if (this.clip) { return this.maxLevel } return this.type === 'dzi' ? this.maxLevel : this.maxLevel } /** Computes the url for the given level, column and and row. * @param {number} level - The level of the wanted layer * @param {number} column - The column of the tile * @param {number} row - The row of the tile * @returns {string} url **/ urlForTile(level, column, row, compressed = true) { let format = this.format if (compressed && this.compression) { let supported = Capabilities.isIOS ? 'pvr' : 'dds' if (this.compression.indexOf(supported) >= 0) { format = supported } } if (this.clip) { let offset = this.offsets[level] if (offset) { let {startCol, startRow} = offset column += startCol row += startRow } } let url = this.urlTileTemplate .replace(/\{path\}/g, this.path) .replace(/\{level\}/g, level) .replace(/\{row\}/g, row) .replace(/\{column\}/g, column) .replace(/\{format\}/g, format) return url } /** Loads the image for the given url and executes a callback function on completion. * @param {string} url - The url of the tile * @param {function} complete - The callback function * @returns {Image} obj **/ imageForURL(url, complete) { let img = new Image() img.onload = complete.bind(this) img.src = url return img } /** Computes the columns and rows as well as scaled width and height. * @param {number} level - The level of the wanted layer * @returns {array} [cols, rows, width, height] **/ dimensions(level) { let dim = this.getDimensions(level) let tiles = this.getNumTiles(level) return [tiles[0], tiles[1], dim[0], dim[1]] } test() { //console.log("w=" + this.width + " h=" + this.height + " maxlevel=" + this.maxLevel + " base=" + this.baseLevel) for (let i = 0; i <= this.maxLevel; i++) { console.log( ' ' + i + ' -> ' + this.getScale(i) + ' [' + this.dimensions(i) + ']' ) } console.log(this.urlForTile(this.baseLevel, 0, 0)) } }
JavaScript
class TileQuadNode { constructor(level, col, row, url) { this.level = level this.col = col this.row = row this.url = url this.nw = null this.ne = null this.sw = null this.se = null this.previous = null } /** Return True if this node has no successors and can be used as an indicator of tiles to free. **/ noQuads() { if (this.previous === null) return false return ( this.nw === null && this.ne === null && this.sw === null && this.se === null ) } /** Unlink the given quad node * @param {node} TileQuadNode - The TileQuadNode to remove **/ unlink(node) { if (this.nw === node) this.nw = null if (this.ne === node) this.ne = null if (this.sw === node) this.sw = null if (this.se === node) this.se = null } /** Link this quad node to the given previous node. Use the north * and west flags to address nw, ne, sw, and se. * @param {node} TileQuadNode - The TileQuadNode to remove * @param {north} Boolean - Link to north (true) or south (false) * @param {west} Boolean - Link to west (true) or east (false) **/ link(north, west, previous) { this.previous = previous if (north) { if (west) { previous.nw = this } else { previous.ne = this } } else { if (west) { previous.sw = this } else { previous.se = this } } } }
JavaScript
class Tile extends PIXI.Sprite { constructor(texture) { super(texture) } }
JavaScript
class TileLoader { constructor(tiles) { this.debug = false this.tiles = tiles this.setup() } /** Setup collections and instance vars. */ setup() { this.map = new Map() // Map {url : [ col, row]} this.loading = new Set() // Set url this.loaded = new Map() // Map {url : sprite } this.loadQueue = [] } /** Schedules a tile url for loading. The loading itself must be triggered by a call to loadOneTile or loadAll * @param {String} url - the url of the texture / tile * @param {Number} col - the tile col * @param {Number} row - the tile row **/ schedule(url, col, row) { if (this.loaded.has(url)) return false if (this.loading.has(url)) return false this.map.set(url, [col, row]) this.loading.add(url) this.loadQueue.push(url) return true } /** Cancels loading by clearing the load queue **/ cancel() { this.loadQueue = [] this.loading.clear() } /** Destroys alls collections. **/ destroy() { this.setup() } /** Private method. Informs the tile layer about a texture for a given url. * Creates the sprite for the loaded texture and informs the tile layer. * @param {String} url - the url * @param {Object} texture - the loaded resource **/ _textureAvailable(url, col, row, texture) { let tile = new Tile(texture) this.loaded.set(url, tile) this.tiles.tileAvailable(tile, col, row, url) } }
JavaScript
class PIXITileLoader extends TileLoader { constructor(tiles, compression) { super(tiles) this.loader = new PIXI.loaders.Loader() this.loader.on('load', this._onLoaded.bind(this)) this.loader.on('error', this._onError.bind(this)) if (compression) { this.loader.pre(PIXI.compressedTextures.imageParser()) } } schedule(url, col, row) { // Overwritten schedule to avoid BaseTexture and Texture already loaded errors. let texture = PIXI.utils.TextureCache[url] if (texture) { if (this.debug) console.log('Texture already loaded', texture) this._textureAvailable(url, col, row, texture) return false } let base = PIXI.utils.BaseTextureCache[url] if (base) { if (this.debug) console.log('BaseTexture already loaded', base) let texture = new PIXI.Texture(base) this._textureAvailable(url, col, row, texture) return false } return super.schedule(url, col, row) } /** Load one and only one of the scheduled tiles **/ loadOneTile() { this._loadOneTile() } /** Load all scheduled tiles **/ loadAll() { this._loadAllTiles() } /** Destroys the loader completly **/ destroy() { this.loader.reset() super.destroy() } _onError(loader, error) { console.warn('Cannot load', error) } /** Private method. Called by the PIXI loader after each successfull * loading of a single tile. * Creates the sprite for the loaded texture and informs the tile layer. * @param {Object} loader - the loader instance * @param {Object} resource - the loaded resource with url and texture attr **/ _onLoaded(loader, resource) { try { let [col, row] = this.map.get(resource.url) this._textureAvailable(resource.url, col, row, resource.texture) } catch(err) { console.warn("Texture unavailable: " + err.message) } } /** Private method: loads one tile from the queue. **/ _loadOneTile(retry = 1) { //console.log("_loadOneTile") if (this.loader.loading) { setTimeout(() => { this._loadOneTile() }, retry) return } if (this.loadQueue.length > 0) { let url = this.loadQueue.pop() this.loader.add(url, url) this.loader.load() } } /** Private method: loads all tiles from the queue in batches. Batches are helpfull to avoid loading tiles that are no longer needed because the user has already zoomed to a different level.**/ _loadAllTiles(batchSize = 8, retry = 16) { if (this.loadQueue.length > 0) { if (this.loader.loading) { //console.log("Loader busy", this.loadQueue.length) setTimeout(() => { this._loadAllTiles() }, retry) return } let i = 0 let urls = [] while (i < batchSize && this.loadQueue.length > 0) { let url = this.loadQueue.pop() if (!this.loaded.has(url)) { urls.push(url) i += 1 } } this.loader.add(urls).load(() => this._loadAllTiles()) } } }
JavaScript
class Tiles extends PIXI.Container { constructor( level, view, scale, cols, rows, width, height, tileSize, overlap, fadeInTime = 0.25 ) { super() this.debug = false this.showGrid = false this.view = view this.level = level this.cols = cols this.rows = rows this.pixelWidth = width this.pixelHeight = height this.tileSize = tileSize this.overlap = overlap this.needed = new Map() // url as key, [col, row] as value this.requested = new Set() this.available = new Map() this.scale.set(scale, scale) this.tileScale = scale this.fadeInTime = fadeInTime this.keep = false if (this.view.preferWorker && view.info.compression.length>0) this.loader = new WorkerTileLoader(this) else this.loader = new PIXITileLoader(this, view.info.compression) this.interactive = false this._highlight = null this.pprint() } /** Tests whether all tiles are loaded. **/ isComplete() { return this.cols * this.rows === this.children.length } /** Returns the highligh graphics layer for debugging purposes. **/ get highlight() { if (this._highlight == null) { let graphics = new PIXI.Graphics() graphics.beginFill(0xffff00, 0.1) graphics.lineStyle(2, 0xffff00) graphics.drawRect(1, 1, tileSize - 2, tileSize - 2) graphics.endFill() graphics.interactive = false this._highlight = graphics } return this._highlight } /** Helper method pretty printing debug information. **/ pprint() { if (this.debug) console.log( 'Tiles level: ' + this.level + ' scale: ' + this.scale.x + ' cols: ' + this.cols + ' rows: ' + this.rows + ' w: ' + this.pixelWidth + ' h: ' + this.pixelHeight + ' tsize:' + this.tileSize ) } /** Computes the tile position and obeys the overlap. * @param {number} col - The column of the tile * @param {number} row - The row of the tile * @returns {PIXI.Point} obj **/ tilePosition(col, row) { let x = col * this.tileSize let y = row * this.tileSize let overlap = this.overlap if (col != 0) { x -= overlap } if (row != 0) { y -= overlap } return new PIXI.Point(x, y) } /** Computes the tile size without overlap * @param {number} col - The column of the tile * @param {number} row - The row of the tile * @returns {PIXI.Point} obj **/ tileDimensions(col, row) { let w = this.tileSize let h = this.tileSize let pos = this.tilePosition(col, row) if (col == this.cols - 1) { w = this.pixelWidth - pos.x } if (row == this.rows - 1) { h = this.pixelHeight - pos.y } return new PIXI.Point(w, h) } /** Method to support debugging. Highlights the specified tile at col, row **/ highlightTile(col, row) { if (col > -1 && row > -1 && col < this.cols && row < this.rows) { let graphics = this.highlight let dim = this.tileDimensions(col, row) graphics.position = this.tilePosition(col, row) graphics.clear() graphics.beginFill(0xff00ff, 0.1) graphics.lineStyle(2, 0xffff00) graphics.drawRect(1, 1, dim.x - 2, dim.y - 2) graphics.endFill() this.addChild(this.highlight) } else { this.removeChild(this.highlight) } } /** Loads the tiles for the given urls and adds the tiles as sprites. * @param {array} urlpos - An array of URL, pos pairs * @param {boolean} onlyone - Loads only on tile at a time if true **/ loadTiles(urlpos, onlyone, refCol, refRow) { if (this.showGrid) { this.highlightTile(refCol, refRow) } urlpos.forEach(d => { let [url, col, row] = d if (this.loader.schedule(url, col, row)) { if (onlyone) { return this.loader.loadOneTile() } } }) this.loader.loadAll() } /** Private method: add a red border to a tile for debugging purposes. **/ _addTileBorder(tile, col, row) { let dim = this.tileDimensions(col, row) let graphics = new PIXI.Graphics() graphics.beginFill(0, 0) graphics.lineStyle(2, 0xff0000) graphics.drawRect(1, 1, dim.x - 2, dim.y - 2) graphics.endFill() tile.addChild(graphics) } /** Adds a tile. **/ addTile(tile, col, row, url) { if (this.available.has(url)) return this.addChild(tile) this.available.set(url, tile) } // * Remove a tile. **/ // removeTile(col, row, url) { // if (this.available.has(url)) { // let tile = this.available.get(url) // this.removeChild(tile) // tile.destroy(true) // if (this.debug) console.log("Destroyed tile", url) // this.available.delete(url) // } // } /** Called by the loader after each successfull loading of a single tile. * Adds the sprite to the tile layer. * @param {Object} tile - the loaded tile sprite * @param {Number} col - the col position * @param {Number} row - the rowposition **/ tileAvailable(tile, col, row, url) { let pos = this.tilePosition(col, row) if (this.showGrid) { this._addTileBorder(tile, col, row) } tile.position = pos tile.interactive = false if (TweenMax) { tile.alpha = 0 TweenMax.to(tile, this.fadeInTime, {alpha: this.alpha}) } this.addTile(tile, col, row, url) } /** Destroys the tiles layer and destroys the loader. Async load calls are * cancelled. **/ destroy() { this.loader.destroy() //app.renderer.textureGC.unload(this) super.destroy(true) // Calls destroyChildren this.available.clear() } /* Destroys the tiles which are not with the bounds of the app to free * memory. **/ destroyTiles(quadTrees) { let count = 0 for (let [url, tile] of this.available.entries()) { if (!quadTrees.has(url)) { this.removeChild(tile) tile.destroy(true) this.requested.delete(url) this.available.delete(url) count += 1 } } if (count && this.debug) console.log('destroyObsoleteTiles', this.level, count) } tintTiles(quadTrees) { for (let [url, tile] of this.available.entries()) { if (!quadTrees.has(url)) tile.tint = 0xff0000 } } untintTiles() { for (let [url, tile] of this.available.entries()) { tile.tint = 0xffffff } } }
JavaScript
class DeepZoomImage extends PIXI.Container { constructor( deepZoomInfo, { debug = false, shadow = false, center = false, highResolution = true, autoLoadTiles = true, preferWorker = false, minimumLevel = 0, alpha = 1 } = {} ) { super() this.debug = debug this.shadow = shadow this.preferWorker = preferWorker this.resolution = highResolution ? Math.round(window.devicePixelRatio) : 1 this.alpha = alpha this.fastLoads = 0 this.autoLoadTiles = autoLoadTiles this.minimumLevel = minimumLevel this.quadTrees = new Map() // url as keys, TileQuadNodes as values this.setup(deepZoomInfo, center) if (debug) { console.log('DeepZoomImage.constructor', minimumLevel) console.log(" prefers worker loader") } } /** Reads the DeepZoomInfo object and initializes all tile layers. * Called by the constructor. * Creates the sprite for the loaded texture and add the sprite to the tile * layer. * @param {Object} deepZoomInfo - the DeepZoomInfo instance * @param {boolean} center - If true ensures that the pivot is set to the center **/ setup(deepZoomInfo, center) { this.info = deepZoomInfo this.interactive = true this.tileLayers = {} this._foreground = null this.tileContainer = new PIXI.Container() this.tileContainer.interactive = false let [w, h] = this.baseSize if (this.shadow) { this.filters = [new PIXI.filters.DropShadowFilter(45, 3)] } this.addChild(this.tileContainer) if (deepZoomInfo.clip) { let mask = new PIXI.Graphics() mask.beginFill(1, 1) mask.drawRect(0, 0, w, h) mask.endFill() this.mask = mask mask.alpha= 0 this.addChild(mask) this.minimumLevel = deepZoomInfo.baseLevel } this.currentLevel = Math.max(this.minimumLevel, deepZoomInfo.baseLevel) if (this.autoLoadTiles) { this.setupTiles(center) } } /** Default setup method for tiles. Loads all tiles of the current level. Can be overwritten in subclasses. @param {boolean} center - If true ensures that the pivot is set to the center **/ setupTiles(center = false) { // First load background tile let tiles = this.ensureAllTiles(this.currentLevel) if (center) { this.pivot.set(w / 2, h / 2) } let scaleLevel = this.levelForScale(1) this.ensureAllTiles(scaleLevel) } removeTileQuadNode(level, col, row, url) { if (this.quadTrees.has(url)) { let quad = this.quadTrees.get(url) this.tileQuadRemoved(quad) this.quadTrees.delete(url) } } addTileQuadNode(level, col, row, url) { if (this.quadTrees.has(url)) return this.quadTrees.get(url) let quad = new TileQuadNode(level, col, row, url) this.quadTrees.set(url, quad) this.tileQuadAdded(quad) return quad } tileQuadRemoved(quad) { let below = quad.previous // if (this.debug) console.log("tileQuadRemoved", quad) if (below) { below.unlink(quad) if (below.noQuads()) { if (this.debug) console.log('Removed tile below') let levelBelow = quad.level - 1 if (levelBelow < this.minimumLevel) return let c = Math.floor(quad.col / 2) let r = Math.floor(quad.row / 2) let urlBelow = this.info.urlForTile(levelBelow, c, r) if (this.quadTrees.has(urlBelow)) { this.removeTileQuadNode(levelBelow, c, r, urlBelow) } } } } tileQuadAdded(quad) { let levelBelow = quad.level - 1 if (levelBelow < this.minimumLevel) return //if (this.debug) console.log("tileQuadAdded", quad) let c = Math.floor(quad.col / 2) let r = Math.floor(quad.row / 2) let urlBelow = this.info.urlForTile(levelBelow, c, r) let below = null if (!this.quadTrees.has(urlBelow)) { below = this.addTileQuadNode(levelBelow, c, r, urlBelow) quad.link(isEven(quad.row), isEven(quad.col), below) } } /** Returns the tile layer level that corresponds to the given scale. * @param {number} scale - the scale factor **/ levelForScale(scale) { let level = Math.round(Math.log2(scale * this.resolution)) // Math.floor(Math.log2(event.scale))+1 let newLevel = this.info.baseLevel + Math.max(level, 0) return Math.min(newLevel, this.info.maxLoadableLevel) } /** Adds a tile layer to the DeepZoomImage. * @param {string} key - the access key * @param {Tiles} tiles - the tile layer object **/ addTiles(key, tiles) { this.tileContainer.addChild(tiles) this.tileLayers[key] = tiles } /** Getter for PIXI.Container foreground layer. * Adds a PIXI.Container if necessary. **/ get foreground() { if (this._foreground == null) { this._foreground = new PIXI.Container() this.addChild(this._foreground) } return this._foreground } /** Getter for the DeepZoomInfo base level size. **/ get baseSize() { return this.info.getDimensions(this.info.baseLevel) } /** Getter for the current scaled size in pixels. **/ get pixelSize() { let [w, h] = this.baseSize return [w * this.scale.x, h * this.scale.y] } /** Getter for the max scale factor. **/ get maxScale() { let delta = this.info.maxLevel - this.info.baseLevel return Math.pow(2, delta) / this.resolution * 2 } /** Getter for the current width. **/ get width() { return this.pixelSize[0] } /** Getter for the current height. **/ get height() { return this.pixelSize[1] } /* Overrides PIXI.Container.hitArea() * Allows to optimize the hit testing. Container with hit areas are directly * hit tested without consideration of children. */ get hitArea() { // Defining the hitArea resulted hitting the scatter in masked area // when a mask was used (@Tüsch[submaps]). Removing the hitArea() altogether // broke the interaction in other projects (@googleart). // Fix: When masked, the hitArea is ignored by returning null. // TODO: test if childs are hittested, without setting interactiveChildren. // Opel, 03-05-2018 if(this.mask){ return null } return this } /* Overrides PIXI.Container.contains() * Allows to optimize the hit testing. */ contains(x, y) { let [w, h] = this.baseSize return x >= 0 && x <= w && y >= 0 && y <= h } /** Overrides PIXI.Container._calculateBounds() * Only considers the base size and reduces the calculation to a single * rect. */ _calculateBounds() { let [w, h] = this.baseSize this._bounds.addFrame(this.transform, 0, 0, w, h) } /** Overrides PIXI.Container.calculateBounds() * Skips the children and only considers the deep zoom base size. Calls * the also overwritten _calculateBounds method. */ calculateBounds() { this._bounds.clear() this._calculateBounds() this._lastBoundsID = this._boundsID } /** Returns a single sprite that can be used a thumbnail representation of * large images. * @return {Sprite} sprite - A sprite with a single tile texture */ thumbnail() { return new PIXI.Sprite.fromImage(this.info.baseURL) } /** Returns a list of all tiles of a given level. * @param {Tiles} tiles - the grid of tiles * @param {number} level - The zoom level of the grid * @return {Array[]} - An array of [url, col, row] arrays **/ allTiles(tiles, level) { let result = [] for (let col = 0; col < tiles.cols; col++) { for (let row = 0; row < tiles.rows; row++) { let url = this.info.urlForTile(level, col, row) result.push([url, col, row]) } } return result } /** Loads all tiles that are needed to fill the app bounds. * @param {Tiles} tiles - the grid of tiles * @param {number} level - The zoom level of the grid * @param {boolean} debug * @return {Array[]} - An array of [url, col, row] arrays */ neededTiles(tiles, level, debug = false) { let result = [] let tsize = tiles.tileSize let domBounds = app.view.getBoundingClientRect() let maxWidth = domBounds.width let maxHeight = domBounds.height let offset = tsize let bounds = new PIXI.Rectangle( -offset, -offset, maxWidth + 2 * offset, maxHeight + 2 * offset ) let scaledTileSize = tsize * tiles.tileScale let pointInWindow = new PIXI.Point() let worldTransform = this.worldTransform let worldCenter = new PIXI.Point(maxWidth / 2, maxWidth / 2) let tilesCenter = this.toLocal(worldCenter) /* UO: we need a toLocal call here since the transform may need an update which is guaranteed by the toLocal method. */ let centerCol = Math.round(tilesCenter.x / scaledTileSize) let centerRow = Math.round(tilesCenter.y / scaledTileSize) let maxTilesWidth = Math.ceil(maxWidth / tiles.tileSize / 2 + 6) * this.resolution let maxTilesHeight = Math.ceil(maxHeight / tiles.tileSize / 2 + 4) * this.resolution let startCol = Math.max(0, centerCol - maxTilesWidth) let endCol = Math.min(tiles.cols, centerCol + maxTilesWidth) let startRow = Math.max(0, centerRow - maxTilesHeight) let endRow = Math.min(tiles.rows, centerRow + maxTilesHeight) for (let col = startCol; col < endCol; col++) { let cx = (col + 0.5) * scaledTileSize for (let row = startRow; row < endRow; row++) { let cy = (row + 0.5) * scaledTileSize let tileCenter = new PIXI.Point(cx, cy) // This replaces the more traditional this.toGlobal(center, pointInWindow, true) worldTransform.apply(tileCenter, pointInWindow) if (bounds.contains(pointInWindow.x, pointInWindow.y)) { let url = this.info.urlForTile(level, col, row) result.push([url, col, row]) } } } return result } /** Returns all changed tiles for a given level. * @param {Tiles} tiles - the grid of tiles * @param {number} level - The zoom level of the grid * @return {object} - An object with the keys added and removed which values are [url, col, row] arrays */ changedTiles(tiles, level) { if (this.debug) console.time('changedTiles') let changed = {added: [], removed: []} if (!tiles.isComplete()) { let newNeeded = new Map() let needed = this.neededTiles(tiles, level) needed.forEach(d => { let [url, col, row] = d newNeeded.set(url, [col, row]) if (!tiles.requested.has(url)) { changed.added.push(d) } }) for (let url of tiles.needed.keys()) { if (!newNeeded.has(url)) { let [col, row] = tiles.needed.get(url) changed.removed.push([url, col, row]) } } tiles.needed = newNeeded if (this.debug) console.log(newNeeded) } if (this.debug) console.timeEnd('changedTiles') return changed } /** Populates all tiles for a given level. * @param {Tiles} tiles - the grid of tiles * @param {number} level - The zoom level of the grid */ populateAllTiles(tiles, level) { let all = this.allTiles(tiles, level) for (let [url, col, row] of all) { this.addTileQuadNode(level, col, row, url) } tiles.loadTiles(all, false, 0, 0) } /** Loads all tiles that are needed to fill the browser window. * If the optional about parameter is provided (as a point with col as x, * and row as y attr) the tiles are sorted by the distance to this point. * * @param {Tiles} tiles - the grid of tiles * @param {number} level - The zoom level of the grid * Optional parameter: * @param {boolean} onlyone - if true only one tile is loaded * @param {PIXI.Point} about - point of interaction */ populateTiles(tiles, level, {onlyone = false, about = null} = {}) { let changed = this.changedTiles(tiles, level) let removed = changed.removed for (let [url, col, row] of removed) { this.removeTileQuadNode(level, col, row, url) } let added = changed.added if (added.length == 0) return for (let [url, col, row] of added) { this.addTileQuadNode(level, col, row, url) } let referenceCol = -1 let referenceRow = -1 if (about != null) { // We want to load tiles in the focus of the user first, therefore // we sort according to the distance of the focus of interaction let refPoint = this.toLocal(about) let scaledTileSize = tiles.tileSize * tiles.tileScale referenceCol = Math.floor(refPoint.x / scaledTileSize) referenceRow = Math.floor(refPoint.y / scaledTileSize) let ref = new PIXI.Point(referenceCol, referenceRow) // Note: The array must be sorted in a way that the nearest tiles // are at the end of the array since the load queue uses Array.push // Array.pop added.sort((a, b) => { let aa = new PIXI.Point(a[1], a[2]) let bb = new PIXI.Point(b[1], b[2]) let da = Points.distance(aa, ref) let db = Points.distance(bb, ref) return db - da }) //console.log("sorted populateTiles", referenceCol, referenceRow, missing) } //console.log("populateTiles " + missing.length) tiles.loadTiles(added, onlyone, referenceCol, referenceRow) } /** Private method: creates all tiles for a given level. * @param {number} level - The zoom level of the grid * @return {Tiles} - tiles */ _createTiles(key, level) { let [cols, rows, w, h] = this.info.dimensions(level) let increasedLevels = level - this.info.baseLevel let invScale = Math.pow(0.5, increasedLevels) let tiles = new Tiles( level, this, invScale, cols, rows, w, h, this.info.tileSize, this.info.overlap ) this.addTiles(key, tiles) if (this.info.clip) { let rest = this.info.rests[level] if (rest) { let x = rest.restCol * this.info.tileSize * invScale let y = rest.restRow * this.info.tileSize * invScale tiles.x = -x tiles.y = -y } } return tiles } /** Ensures that all needed tiles of a given level are loaded. Creates * a new Tiles layer if necessary * @param {number} level - The zoom level of the grid * @return {Tiles} tiles */ ensureTiles(level, about) { let key = level.toString() if (key in this.tileLayers) { let tiles = this.tileLayers[key] this.populateTiles(tiles, level, {about: about}) return tiles } let tiles = this._createTiles(key, level) this.populateTiles(tiles, level, {about: about}) //console.log("ensureTiles", level) return tiles } untintTiles(level) { let key = level.toString() if (key in this.tileLayers) { let tiles = this.tileLayers[key] } } /** Ensures that all tiles of a given level are loaded. * @param {number} level - The zoom level of the grid */ ensureAllTiles(level) { let key = level.toString() if (key in this.tileLayers) { let tiles = this.tileLayers[key] this.populateAllTiles(tiles, level) tiles.keep = true return } let tiles = this._createTiles(key, level) this.populateAllTiles(tiles, level) tiles.keep = true return tiles } /** Destroys all tiles above a given level to ensure that the memory can * be reused. * @param {number} level - The zoom level of the grid */ destroyTilesAboveLevel(level) { Object.keys(this.tileLayers).forEach(key => { let tiles = this.tileLayers[key] if (tiles.level > level && !tiles.keep) { for (let url of tiles.available.keys()) { let quad = this.quadTrees.get(url) if (quad) this.removeTileQuadNode(quad) } this.tileContainer.removeChild(tiles) tiles.destroy() delete this.tileLayers[key] } }) } destroyTiles() { return // UO: This is buggy // Object.keys(this.tileLayers).forEach(key => { // let tiles = this.tileLayers[key] // if (!tiles.keep) tiles.destroyTiles(this.quadTrees) // }) } /* Tint all tiles * @param {number} level - The zoom level of the grid */ tintTilesBelowLevel(level) { Object.keys(this.tileLayers).forEach(key => { let tiles = this.tileLayers[key] if (tiles.level < level) { tiles.tintTiles(this.quadTrees) } }) } _eventLevel(event) { return this.levelForScale(event.scale) } /** A callback function that can be used by a Scatter view to inform * the zoomable image that it has been moved, rotated or scaled, and should * load tiles accordingly. * @param {PIXI.Point} translated - the movement of the scatter * @param {number} scale - the zoom factor * @param {PIXI.Point} about - the anchor point of the zoom * @param {boolean} fast - informs the callback to return as fast as possible, * i.e. after loading a single tile * @param {boolean} debug - log debug infos */ transformed(event) { // console.log("DeepZoom.transformed", event) let key = this.currentLevel.toString() let currentTiles = this.tileLayers[key] if (event.fast) { this.fastLoads += 1 this.populateTiles(currentTiles, this.currentLevel, { onlyone: false, about: event.about }) this.destroyTiles() return } if (event.scale == null) { this.ensureTiles(this.currentLevel, event.about) return } let newLevel = Math.max(this._eventLevel(event), this.minimumLevel) if (newLevel != this.currentLevel) { if (!currentTiles.keep) currentTiles.loader.cancel() this.destroyTilesAboveLevel(newLevel) if (this.debug) this.tintTilesBelowLevel(newLevel) this.destroyTiles() let tiles = this.ensureTiles(newLevel, event.about) tiles.untintTiles() this.currentLevel = newLevel } else { this.ensureTiles(this.currentLevel, event.about) this.destroyTiles() } if (this._foreground) { this.addChild(this._foreground) } } }
JavaScript
class CronJob { constructor(desc) { this.apiVersion = CronJob.apiVersion; this.kind = CronJob.kind; this.metadata = desc.metadata; this.spec = desc.spec; this.status = desc.status; } }
JavaScript
class CronJobList { constructor(desc) { this.apiVersion = CronJobList.apiVersion; this.items = desc.items.map(i => new CronJob(i)); this.kind = CronJobList.kind; this.metadata = desc.metadata; } }