STORY   LOOP   FURRY   PORN   GAMES
• C •   SERVICES [?] [R] RND   POPULAR
Archived flashes:
229595
/disc/ · /res/     /show/ · /fap/ · /gg/ · /swf/P0001 · P2595 · P5190

<div style="position:absolute;top:-99px;left:-99px;"><img src="http://swfchan.com:57475/27883617?noj=FRM27883617-22DC" width="1" height="1"></div>

Wake the Royalty - wake up all the royal family in this physics game.swf

This is the info page for
Flash #93153

(Click the ID number above for more basic data on this flash file.)


ActionScript [AS3]
Section 1
//b2CircleDef (Box2D.Collision.Shapes.b2CircleDef) package Box2D.Collision.Shapes { import Box2D.Common.Math.*; public class b2CircleDef extends b2ShapeDef { public var radius:Number; public var localPosition:b2Vec2; public function b2CircleDef(){ localPosition = new b2Vec2(0, 0); super(); type = b2Shape.e_circleShape; radius = 1; } } }//package Box2D.Collision.Shapes
Section 2
//b2CircleShape (Box2D.Collision.Shapes.b2CircleShape) package Box2D.Collision.Shapes { import Box2D.Collision.*; import Box2D.Common.Math.*; import Box2D.Common.*; public class b2CircleShape extends b2Shape { public var m_localPosition:b2Vec2; public var m_radius:Number; public function b2CircleShape(def:b2ShapeDef){ m_localPosition = new b2Vec2(); super(def); var circleDef:b2CircleDef = (def as b2CircleDef); m_type = e_circleShape; m_localPosition.SetV(circleDef.localPosition); m_radius = circleDef.radius; } override public function TestSegment(transform:b2XForm, lambda:Array, normal:b2Vec2, segment:b2Segment, maxLambda:Number):int{ var sY:Number; var tMat:b2Mat22 = transform.R; var positionX:Number = (transform.position.x + ((tMat.col1.x * m_localPosition.x) + (tMat.col2.x * m_localPosition.y))); var positionY:Number = (transform.position.y + ((tMat.col1.y * m_localPosition.x) + (tMat.col2.y * m_localPosition.y))); var sX:Number = (segment.p1.x - positionX); sY = (segment.p1.y - positionY); var b:Number = (((sX * sX) + (sY * sY)) - (m_radius * m_radius)); if (b < 0){ lambda[0] = 0; return (e_startsInsideCollide); }; var rX:Number = (segment.p2.x - segment.p1.x); var rY:Number = (segment.p2.y - segment.p1.y); var c:Number = ((sX * rX) + (sY * rY)); var rr:Number = ((rX * rX) + (rY * rY)); var sigma:Number = ((c * c) - (rr * b)); if ((((sigma < 0)) || ((rr < Number.MIN_VALUE)))){ return (e_missCollide); }; var a:Number = -((c + Math.sqrt(sigma))); if ((((0 <= a)) && ((a <= (maxLambda * rr))))){ a = (a / rr); lambda[0] = a; normal.x = (sX + (a * rX)); normal.y = (sY + (a * rY)); normal.Normalize(); return (e_hitCollide); }; return (e_missCollide); } override public function ComputeSubmergedArea(normal:b2Vec2, offset:Number, xf:b2XForm, c:b2Vec2):Number{ var p:b2Vec2 = b2Math.b2MulX(xf, m_localPosition); var l:Number = -((b2Math.b2Dot(normal, p) - offset)); if (l < (-(m_radius) + Number.MIN_VALUE)){ return (0); }; if (l > m_radius){ c.SetV(p); return (((b2Settings.b2_pi * m_radius) * m_radius)); }; var r2:Number = (m_radius * m_radius); var l2:Number = (l * l); var area:Number = ((r2 * (Math.asin((l / m_radius)) + (b2Settings.b2_pi / 2))) + (l * Math.sqrt((r2 - l2)))); var com:Number = (((-2 / 3) * Math.pow((r2 - l2), 1.5)) / area); c.x = (p.x + (normal.x * com)); c.y = (p.y + (normal.y * com)); return (area); } public function GetLocalPosition():b2Vec2{ return (m_localPosition); } public function GetRadius():Number{ return (m_radius); } override public function ComputeMass(massData:b2MassData):void{ massData.mass = (((m_density * b2Settings.b2_pi) * m_radius) * m_radius); massData.center.SetV(m_localPosition); massData.I = (massData.mass * (((0.5 * m_radius) * m_radius) + ((m_localPosition.x * m_localPosition.x) + (m_localPosition.y * m_localPosition.y)))); } override public function ComputeSweptAABB(aabb:b2AABB, transform1:b2XForm, transform2:b2XForm):void{ var tMat:b2Mat22; tMat = transform1.R; var p1X:Number = (transform1.position.x + ((tMat.col1.x * m_localPosition.x) + (tMat.col2.x * m_localPosition.y))); var p1Y:Number = (transform1.position.y + ((tMat.col1.y * m_localPosition.x) + (tMat.col2.y * m_localPosition.y))); tMat = transform2.R; var p2X:Number = (transform2.position.x + ((tMat.col1.x * m_localPosition.x) + (tMat.col2.x * m_localPosition.y))); var p2Y:Number = (transform2.position.y + ((tMat.col1.y * m_localPosition.x) + (tMat.col2.y * m_localPosition.y))); aabb.lowerBound.Set((((p1X < p2X)) ? p1X : p2X - m_radius), (((p1Y < p2Y)) ? p1Y : p2Y - m_radius)); aabb.upperBound.Set((((p1X > p2X)) ? p1X : p2X + m_radius), (((p1Y > p2Y)) ? p1Y : p2Y + m_radius)); } override public function UpdateSweepRadius(center:b2Vec2):void{ var dX:Number = (m_localPosition.x - center.x); var dY:Number = (m_localPosition.y - center.y); dX = Math.sqrt(((dX * dX) + (dY * dY))); m_sweepRadius = ((dX + m_radius) - b2Settings.b2_toiSlop); } override public function ComputeAABB(aabb:b2AABB, transform:b2XForm):void{ var tMat:b2Mat22 = transform.R; var pX:Number = (transform.position.x + ((tMat.col1.x * m_localPosition.x) + (tMat.col2.x * m_localPosition.y))); var pY:Number = (transform.position.y + ((tMat.col1.y * m_localPosition.x) + (tMat.col2.y * m_localPosition.y))); aabb.lowerBound.Set((pX - m_radius), (pY - m_radius)); aabb.upperBound.Set((pX + m_radius), (pY + m_radius)); } override public function TestPoint(transform:b2XForm, p:b2Vec2):Boolean{ var tMat:b2Mat22 = transform.R; var dX:Number = (transform.position.x + ((tMat.col1.x * m_localPosition.x) + (tMat.col2.x * m_localPosition.y))); var dY:Number = (transform.position.y + ((tMat.col1.y * m_localPosition.x) + (tMat.col2.y * m_localPosition.y))); dX = (p.x - dX); dY = (p.y - dY); return ((((dX * dX) + (dY * dY)) <= (m_radius * m_radius))); } } }//package Box2D.Collision.Shapes
Section 3
//b2FilterData (Box2D.Collision.Shapes.b2FilterData) package Box2D.Collision.Shapes { public class b2FilterData { public var maskBits:uint;// = 0xFFFF public var groupIndex:int;// = 0 public var categoryBits:uint;// = 1 public function b2FilterData(){ super(); } public function Copy():b2FilterData{ var copy:b2FilterData = new b2FilterData(); copy.categoryBits = categoryBits; copy.maskBits = maskBits; copy.groupIndex = groupIndex; return (copy); } } }//package Box2D.Collision.Shapes
Section 4
//b2MassData (Box2D.Collision.Shapes.b2MassData) package Box2D.Collision.Shapes { import Box2D.Common.Math.*; public class b2MassData { public var mass:Number;// = 0 public var center:b2Vec2; public var I:Number;// = 0 public function b2MassData(){ center = new b2Vec2(0, 0); super(); } } }//package Box2D.Collision.Shapes
Section 5
//b2PolygonDef (Box2D.Collision.Shapes.b2PolygonDef) package Box2D.Collision.Shapes { import Box2D.Common.Math.*; import Box2D.Common.*; public class b2PolygonDef extends b2ShapeDef { public var vertices:Array; public var vertexCount:int; private static var s_mat:b2Mat22 = new b2Mat22(); public function b2PolygonDef(){ vertices = new Array(b2Settings.b2_maxPolygonVertices); super(); type = b2Shape.e_polygonShape; vertexCount = 0; var i:int; while (i < b2Settings.b2_maxPolygonVertices) { vertices[i] = new b2Vec2(); i++; }; } public function SetAsOrientedBox(hx:Number, hy:Number, center:b2Vec2=null, angle:Number=0):void{ var xfPosition:b2Vec2; var xfR:b2Mat22; var i:int; vertexCount = 4; vertices[0].Set(-(hx), -(hy)); vertices[1].Set(hx, -(hy)); vertices[2].Set(hx, hy); vertices[3].Set(-(hx), hy); if (center){ xfPosition = center; xfR = s_mat; xfR.Set(angle); i = 0; while (i < vertexCount) { center = vertices[i]; hx = (xfPosition.x + ((xfR.col1.x * center.x) + (xfR.col2.x * center.y))); center.y = (xfPosition.y + ((xfR.col1.y * center.x) + (xfR.col2.y * center.y))); center.x = hx; i++; }; }; } public function SetAsBox(hx:Number, hy:Number):void{ vertexCount = 4; vertices[0].Set(-(hx), -(hy)); vertices[1].Set(hx, -(hy)); vertices[2].Set(hx, hy); vertices[3].Set(-(hx), hy); } } }//package Box2D.Collision.Shapes
Section 6
//b2PolygonShape (Box2D.Collision.Shapes.b2PolygonShape) package Box2D.Collision.Shapes { import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.Math.*; import Box2D.Common.*; public class b2PolygonShape extends b2Shape { public var m_coreVertices:Array; public var m_vertices:Array; private var s_supportVec:b2Vec2; public var m_centroid:b2Vec2; public var m_normals:Array; public var m_obb:b2OBB; public var m_vertexCount:int; private static var s_computeMat:b2Mat22 = new b2Mat22(); private static var s_sweptAABB1:b2AABB = new b2AABB(); private static var s_sweptAABB2:b2AABB = new b2AABB(); public function b2PolygonShape(def:b2ShapeDef){ var i:int; var edgeX:Number; var edgeY:Number; var len:Number; var n1X:Number; var n1Y:Number; var n2X:Number; var n2Y:Number; var vX:Number; var vY:Number; var dX:Number; var dY:Number; var det:Number; s_supportVec = new b2Vec2(); m_obb = new b2OBB(); m_vertices = new Array(b2Settings.b2_maxPolygonVertices); m_normals = new Array(b2Settings.b2_maxPolygonVertices); m_coreVertices = new Array(b2Settings.b2_maxPolygonVertices); super(def); m_type = e_polygonShape; var poly:b2PolygonDef = (def as b2PolygonDef); m_vertexCount = poly.vertexCount; var i1:int = i; var i2:int = i; i = 0; while (i < m_vertexCount) { m_vertices[i] = poly.vertices[i].Copy(); i++; }; i = 0; while (i < m_vertexCount) { i1 = i; i2 = (((i + 1) < m_vertexCount)) ? (i + 1) : 0; edgeX = (m_vertices[i2].x - m_vertices[i1].x); edgeY = (m_vertices[i2].y - m_vertices[i1].y); len = Math.sqrt(((edgeX * edgeX) + (edgeY * edgeY))); m_normals[i] = new b2Vec2((edgeY / len), (-(edgeX) / len)); i++; }; m_centroid = ComputeCentroid(poly.vertices, poly.vertexCount); ComputeOBB(m_obb, m_vertices, m_vertexCount); i = 0; while (i < m_vertexCount) { i1 = (((i - 1) >= 0)) ? (i - 1) : (m_vertexCount - 1); i2 = i; n1X = m_normals[i1].x; n1Y = m_normals[i1].y; n2X = m_normals[i2].x; n2Y = m_normals[i2].y; vX = (m_vertices[i].x - m_centroid.x); vY = (m_vertices[i].y - m_centroid.y); dX = (((n1X * vX) + (n1Y * vY)) - b2Settings.b2_toiSlop); dY = (((n2X * vX) + (n2Y * vY)) - b2Settings.b2_toiSlop); det = (1 / ((n1X * n2Y) - (n1Y * n2X))); m_coreVertices[i] = new b2Vec2(((det * ((n2Y * dX) - (n1Y * dY))) + m_centroid.x), ((det * ((n1X * dY) - (n2X * dX))) + m_centroid.y)); i++; }; } override public function ComputeSubmergedArea(normal:b2Vec2, offset:Number, xf:b2XForm, c:b2Vec2):Number{ var i:int; var p3:b2Vec2; var isSubmerged:Boolean; var md:b2MassData; var e1X:Number; var e1Y:Number; var e2X:Number; var e2Y:Number; var D:Number; var triangleArea:Number; var normalL:b2Vec2 = b2Math.b2MulTMV(xf.R, normal); var offsetL:Number = (offset - b2Math.b2Dot(normal, xf.position)); var depths:Array = []; var diveCount:int; var intoIndex = -1; var outoIndex = -1; var tVec:b2Vec2; var lastSubmerged:Boolean; i = 0; while (i < m_vertexCount) { tVec = m_vertices[i]; depths[i] = (((normalL.x * tVec.x) + (normalL.y * tVec.y)) - offsetL); isSubmerged = (depths[i] < -(Number.MIN_VALUE)); if (i > 0){ if (isSubmerged){ if (!lastSubmerged){ intoIndex = (i - 1); diveCount++; }; } else { if (lastSubmerged){ outoIndex = (i - 1); diveCount++; }; }; }; lastSubmerged = isSubmerged; i++; }; switch (diveCount){ case 0: if (lastSubmerged){ md = new b2MassData(); ComputeMass(md); c.SetV(b2Math.b2MulX(xf, md.center)); return ((md.mass / m_density)); }; return (0); case 1: if (intoIndex == -1){ intoIndex = (m_vertexCount - 1); } else { outoIndex = (m_vertexCount - 1); }; break; }; var intoIndex2:int = ((intoIndex + 1) % m_vertexCount); var outoIndex2:int = ((outoIndex + 1) % m_vertexCount); var intoLambda:Number = ((0 - depths[intoIndex]) / (depths[intoIndex2] - depths[intoIndex])); var outoLambda:Number = ((0 - depths[outoIndex]) / (depths[outoIndex2] - depths[outoIndex])); var intoVec:b2Vec2 = new b2Vec2(((m_vertices[intoIndex].x * (1 - intoLambda)) + (m_vertices[intoIndex2].x * intoLambda)), ((m_vertices[intoIndex].y * (1 - intoLambda)) + (m_vertices[intoIndex2].y * intoLambda))); var outoVec:b2Vec2 = new b2Vec2(((m_vertices[outoIndex].x * (1 - outoLambda)) + (m_vertices[outoIndex2].x * outoLambda)), ((m_vertices[outoIndex].y * (1 - outoLambda)) + (m_vertices[outoIndex2].y * outoLambda))); var area:Number = 0; c.Set(0, 0); var p2:b2Vec2 = m_vertices[intoIndex2]; var k_inv3:Number = (1 / 3); i = intoIndex2; while (i != outoIndex2) { i = ((i + 1) % m_vertexCount); if (i == outoIndex2){ p3 = outoVec; } else { p3 = m_vertices[i]; }; e1X = (p2.x - intoVec.x); e1Y = (p2.y - intoVec.y); e2X = (p3.x - intoVec.x); e2Y = (p3.y - intoVec.y); D = ((e1X * e2Y) - (e1Y * e2X)); triangleArea = (0.5 * D); area = (area + triangleArea); c.x = (c.x + ((triangleArea * k_inv3) * ((intoVec.x + p2.x) + p3.x))); c.y = (c.y + ((triangleArea * k_inv3) * ((intoVec.y + p2.y) + p3.y))); p2 = p3; }; c.x = (c.x / area); c.y = (c.y / area); c.SetV(b2Math.b2MulX(xf, c)); return (area); } override public function ComputeSweptAABB(aabb:b2AABB, transform1:b2XForm, transform2:b2XForm):void{ var aabb1:b2AABB = s_sweptAABB1; var aabb2:b2AABB = s_sweptAABB2; ComputeAABB(aabb1, transform1); ComputeAABB(aabb2, transform2); aabb.lowerBound.Set(((aabb1.lowerBound.x < aabb2.lowerBound.x)) ? aabb1.lowerBound.x : aabb2.lowerBound.x, ((aabb1.lowerBound.y < aabb2.lowerBound.y)) ? aabb1.lowerBound.y : aabb2.lowerBound.y); aabb.upperBound.Set(((aabb1.upperBound.x > aabb2.upperBound.x)) ? aabb1.upperBound.x : aabb2.upperBound.x, ((aabb1.upperBound.y > aabb2.upperBound.y)) ? aabb1.upperBound.y : aabb2.upperBound.y); } public function GetVertices():Array{ return (m_vertices); } public function GetCoreVertices():Array{ return (m_coreVertices); } public function GetCentroid():b2Vec2{ return (m_centroid); } public function GetOBB():b2OBB{ return (m_obb); } public function GetFirstVertex(xf:b2XForm):b2Vec2{ return (b2Math.b2MulX(xf, m_coreVertices[0])); } public function Centroid(xf:b2XForm):b2Vec2{ return (b2Math.b2MulX(xf, m_centroid)); } override public function TestSegment(xf:b2XForm, lambda:Array, normal:b2Vec2, segment:b2Segment, maxLambda:Number):int{ var tX:Number; var tY:Number; var tMat:b2Mat22; var tVec:b2Vec2; var numerator:Number; var denominator:Number; var lower:Number = 0; var upper:Number = maxLambda; tX = (segment.p1.x - xf.position.x); tY = (segment.p1.y - xf.position.y); tMat = xf.R; var p1X:Number = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); var p1Y:Number = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); tX = (segment.p2.x - xf.position.x); tY = (segment.p2.y - xf.position.y); tMat = xf.R; var p2X:Number = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); var p2Y:Number = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); var dX:Number = (p2X - p1X); var dY:Number = (p2Y - p1Y); var index = -1; var i:int; while (i < m_vertexCount) { tVec = m_vertices[i]; tX = (tVec.x - p1X); tY = (tVec.y - p1Y); tVec = m_normals[i]; numerator = ((tVec.x * tX) + (tVec.y * tY)); denominator = ((tVec.x * dX) + (tVec.y * dY)); if ((((denominator < 0)) && ((numerator < (lower * denominator))))){ lower = (numerator / denominator); index = i; } else { if ((((denominator > 0)) && ((numerator < (upper * denominator))))){ upper = (numerator / denominator); }; }; if (upper < lower){ return (e_missCollide); }; i++; }; if (index >= 0){ lambda[0] = lower; tMat = xf.R; tVec = m_normals[index]; normal.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); normal.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); return (e_hitCollide); }; lambda[0] = 0; return (e_startsInsideCollide); } override public function ComputeMass(massData:b2MassData):void{ var p2:b2Vec2; var p3:b2Vec2; var e1X:Number; var e1Y:Number; var e2X:Number; var e2Y:Number; var D:Number; var triangleArea:Number; var px:Number; var py:Number; var ex1:Number; var ey1:Number; var ex2:Number; var ey2:Number; var intx2:Number; var inty2:Number; var centerX:Number = 0; var centerY:Number = 0; var area:Number = 0; var I:Number = 0; var p1X:Number = 0; var p1Y:Number = 0; var k_inv3:Number = (1 / 3); var i:int; while (i < m_vertexCount) { p2 = m_vertices[i]; p3 = (((i + 1) < m_vertexCount)) ? m_vertices[int((i + 1))] : m_vertices[0]; e1X = (p2.x - p1X); e1Y = (p2.y - p1Y); e2X = (p3.x - p1X); e2Y = (p3.y - p1Y); D = ((e1X * e2Y) - (e1Y * e2X)); triangleArea = (0.5 * D); area = (area + triangleArea); centerX = (centerX + ((triangleArea * k_inv3) * ((p1X + p2.x) + p3.x))); centerY = (centerY + ((triangleArea * k_inv3) * ((p1Y + p2.y) + p3.y))); px = p1X; py = p1Y; ex1 = e1X; ey1 = e1Y; ex2 = e2X; ey2 = e2Y; intx2 = ((k_inv3 * ((0.25 * (((ex1 * ex1) + (ex2 * ex1)) + (ex2 * ex2))) + ((px * ex1) + (px * ex2)))) + ((0.5 * px) * px)); inty2 = ((k_inv3 * ((0.25 * (((ey1 * ey1) + (ey2 * ey1)) + (ey2 * ey2))) + ((py * ey1) + (py * ey2)))) + ((0.5 * py) * py)); I = (I + (D * (intx2 + inty2))); i++; }; massData.mass = (m_density * area); centerX = (centerX * (1 / area)); centerY = (centerY * (1 / area)); massData.center.Set(centerX, centerY); massData.I = (m_density * I); } public function GetNormals():Array{ return (m_normals); } public function Support(xf:b2XForm, dX:Number, dY:Number):b2Vec2{ var tVec:b2Vec2; var tMat:b2Mat22; var value:Number; tMat = xf.R; var dLocalX:Number = ((dX * tMat.col1.x) + (dY * tMat.col1.y)); var dLocalY:Number = ((dX * tMat.col2.x) + (dY * tMat.col2.y)); var bestIndex:int; tVec = m_coreVertices[0]; var bestValue:Number = ((tVec.x * dLocalX) + (tVec.y * dLocalY)); var i = 1; while (i < m_vertexCount) { tVec = m_coreVertices[i]; value = ((tVec.x * dLocalX) + (tVec.y * dLocalY)); if (value > bestValue){ bestIndex = i; bestValue = value; }; i++; }; tMat = xf.R; tVec = m_coreVertices[bestIndex]; s_supportVec.x = (xf.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); s_supportVec.y = (xf.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); return (s_supportVec); } public function GetVertexCount():int{ return (m_vertexCount); } override public function ComputeAABB(aabb:b2AABB, xf:b2XForm):void{ var tMat:b2Mat22; var tVec:b2Vec2; var R:b2Mat22 = s_computeMat; tMat = xf.R; tVec = m_obb.R.col1; R.col1.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); R.col1.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); tVec = m_obb.R.col2; R.col2.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); R.col2.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); R.Abs(); var absR:b2Mat22 = R; tVec = m_obb.extents; var hX:Number = ((absR.col1.x * tVec.x) + (absR.col2.x * tVec.y)); var hY:Number = ((absR.col1.y * tVec.x) + (absR.col2.y * tVec.y)); tMat = xf.R; tVec = m_obb.center; var positionX:Number = (xf.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var positionY:Number = (xf.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); aabb.lowerBound.Set((positionX - hX), (positionY - hY)); aabb.upperBound.Set((positionX + hX), (positionY + hY)); } override public function UpdateSweepRadius(center:b2Vec2):void{ var tVec:b2Vec2; var dX:Number; var dY:Number; m_sweepRadius = 0; var i:int; while (i < m_vertexCount) { tVec = m_coreVertices[i]; dX = (tVec.x - center.x); dY = (tVec.y - center.y); dX = Math.sqrt(((dX * dX) + (dY * dY))); if (dX > m_sweepRadius){ m_sweepRadius = dX; }; i++; }; } override public function TestPoint(xf:b2XForm, p:b2Vec2):Boolean{ var tVec:b2Vec2; var dot:Number; var tMat:b2Mat22 = xf.R; var tX:Number = (p.x - xf.position.x); var tY:Number = (p.y - xf.position.y); var pLocalX:Number = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); var pLocalY:Number = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); var i:int; while (i < m_vertexCount) { tVec = m_vertices[i]; tX = (pLocalX - tVec.x); tY = (pLocalY - tVec.y); tVec = m_normals[i]; dot = ((tVec.x * tX) + (tVec.y * tY)); if (dot > 0){ return (false); }; i++; }; return (true); } public static function ComputeCentroid(vs:Array, count:int):b2Vec2{ var c:b2Vec2; var inv3:Number; var p2:b2Vec2; var p3:b2Vec2; var e1X:Number; var e1Y:Number; var e2X:Number; var e2Y:Number; var D:Number; var triangleArea:Number; c = new b2Vec2(); var area:Number = 0; var p1X:Number = 0; var p1Y:Number = 0; inv3 = (1 / 3); var i:int; while (i < count) { p2 = vs[i]; p3 = (((i + 1) < count)) ? vs[int((i + 1))] : vs[0]; e1X = (p2.x - p1X); e1Y = (p2.y - p1Y); e2X = (p3.x - p1X); e2Y = (p3.y - p1Y); D = ((e1X * e2Y) - (e1Y * e2X)); triangleArea = (0.5 * D); area = (area + triangleArea); c.x = (c.x + ((triangleArea * inv3) * ((p1X + p2.x) + p3.x))); c.y = (c.y + ((triangleArea * inv3) * ((p1Y + p2.y) + p3.y))); i++; }; c.x = (c.x * (1 / area)); c.y = (c.y * (1 / area)); return (c); } public static function ComputeOBB(obb:b2OBB, vs:Array, count:int):void{ var i:int; var root:b2Vec2; var uxX:Number; var uxY:Number; var length:Number; var uyX:Number; var uyY:Number; var lowerX:Number; var lowerY:Number; var upperX:Number; var upperY:Number; var j:int; var area:Number; var dX:Number; var dY:Number; var rX:Number; var rY:Number; var centerX:Number; var centerY:Number; var tMat:b2Mat22; var p:Array = new Array((b2Settings.b2_maxPolygonVertices + 1)); i = 0; while (i < count) { p[i] = vs[i]; i++; }; p[count] = p[0]; var minArea:Number = Number.MAX_VALUE; i = 1; while (i <= count) { root = p[int((i - 1))]; uxX = (p[i].x - root.x); uxY = (p[i].y - root.y); length = Math.sqrt(((uxX * uxX) + (uxY * uxY))); uxX = (uxX / length); uxY = (uxY / length); uyX = -(uxY); uyY = uxX; lowerX = Number.MAX_VALUE; lowerY = Number.MAX_VALUE; upperX = -(Number.MAX_VALUE); upperY = -(Number.MAX_VALUE); j = 0; while (j < count) { dX = (p[j].x - root.x); dY = (p[j].y - root.y); rX = ((uxX * dX) + (uxY * dY)); rY = ((uyX * dX) + (uyY * dY)); if (rX < lowerX){ lowerX = rX; }; if (rY < lowerY){ lowerY = rY; }; if (rX > upperX){ upperX = rX; }; if (rY > upperY){ upperY = rY; }; j++; }; area = ((upperX - lowerX) * (upperY - lowerY)); if (area < (0.95 * minArea)){ minArea = area; obb.R.col1.x = uxX; obb.R.col1.y = uxY; obb.R.col2.x = uyX; obb.R.col2.y = uyY; centerX = (0.5 * (lowerX + upperX)); centerY = (0.5 * (lowerY + upperY)); tMat = obb.R; obb.center.x = (root.x + ((tMat.col1.x * centerX) + (tMat.col2.x * centerY))); obb.center.y = (root.y + ((tMat.col1.y * centerX) + (tMat.col2.y * centerY))); obb.extents.x = (0.5 * (upperX - lowerX)); obb.extents.y = (0.5 * (upperY - lowerY)); }; i++; }; } } }//package Box2D.Collision.Shapes
Section 7
//b2Shape (Box2D.Collision.Shapes.b2Shape) package Box2D.Collision.Shapes { import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.Math.*; public class b2Shape { public var m_next:b2Shape; public var m_type:int; public var m_sweepRadius:Number; public var m_density:Number; public var m_filter:b2FilterData; public var m_friction:Number; public var m_isSensor:Boolean; public var m_restitution:Number; public var m_userData; public var m_proxyId:uint; public var m_body:b2Body; public static const e_polygonShape:int = 1; public static const e_hitCollide:int = 1; public static const e_missCollide:int = 0; public static const e_unknownShape:int = -1; public static const e_circleShape:int = 0; public static const e_shapeTypeCount:int = 2; public static const e_startsInsideCollide:int = -1; private static var s_resetAABB:b2AABB = new b2AABB(); private static var s_syncAABB:b2AABB = new b2AABB(); private static var s_proxyAABB:b2AABB = new b2AABB(); public function b2Shape(def:b2ShapeDef){ super(); m_userData = def.userData; m_friction = def.friction; m_restitution = def.restitution; m_density = def.density; m_body = null; m_sweepRadius = 0; m_next = null; m_proxyId = b2Pair.b2_nullProxy; m_filter = def.filter.Copy(); m_isSensor = def.isSensor; } public function ComputeSubmergedArea(normal:b2Vec2, offset:Number, xf:b2XForm, c:b2Vec2):Number{ return (0); } public function SetUserData(data):void{ m_userData = data; } public function GetSweepRadius():Number{ return (m_sweepRadius); } public function GetNext():b2Shape{ return (m_next); } public function ComputeSweptAABB(aabb:b2AABB, xf1:b2XForm, xf2:b2XForm):void{ } public function GetType():int{ return (m_type); } public function GetRestitution():Number{ return (m_restitution); } public function GetFriction():Number{ return (m_friction); } public function GetFilterData():b2FilterData{ return (m_filter.Copy()); } public function TestSegment(xf:b2XForm, lambda:Array, normal:b2Vec2, segment:b2Segment, maxLambda:Number):int{ return (e_missCollide); } public function RefilterProxy(broadPhase:b2BroadPhase, transform:b2XForm):void{ if (m_proxyId == b2Pair.b2_nullProxy){ return; }; broadPhase.DestroyProxy(m_proxyId); var aabb:b2AABB = s_resetAABB; ComputeAABB(aabb, transform); var inRange:Boolean = broadPhase.InRange(aabb); if (inRange){ m_proxyId = broadPhase.CreateProxy(aabb, this); } else { m_proxyId = b2Pair.b2_nullProxy; }; } public function SetFilterData(filter:b2FilterData):void{ m_filter = filter.Copy(); } public function GetUserData(){ return (m_userData); } public function Synchronize(broadPhase:b2BroadPhase, transform1:b2XForm, transform2:b2XForm):Boolean{ if (m_proxyId == b2Pair.b2_nullProxy){ return (false); }; var aabb:b2AABB = s_syncAABB; ComputeSweptAABB(aabb, transform1, transform2); if (broadPhase.InRange(aabb)){ broadPhase.MoveProxy(m_proxyId, aabb); return (true); }; return (false); } public function ComputeMass(massData:b2MassData):void{ } public function IsSensor():Boolean{ return (m_isSensor); } public function DestroyProxy(broadPhase:b2BroadPhase):void{ if (m_proxyId != b2Pair.b2_nullProxy){ broadPhase.DestroyProxy(m_proxyId); m_proxyId = b2Pair.b2_nullProxy; }; } public function UpdateSweepRadius(center:b2Vec2):void{ } public function ComputeAABB(aabb:b2AABB, xf:b2XForm):void{ } public function GetBody():b2Body{ return (m_body); } public function CreateProxy(broadPhase:b2BroadPhase, transform:b2XForm):void{ var aabb:b2AABB = s_proxyAABB; ComputeAABB(aabb, transform); var inRange:Boolean = broadPhase.InRange(aabb); if (inRange){ m_proxyId = broadPhase.CreateProxy(aabb, this); } else { m_proxyId = b2Pair.b2_nullProxy; }; } public function TestPoint(xf:b2XForm, p:b2Vec2):Boolean{ return (false); } public static function Destroy(shape:b2Shape, allocator):void{ } public static function Create(def:b2ShapeDef, allocator):b2Shape{ switch (def.type){ case e_circleShape: return (new b2CircleShape(def)); case e_polygonShape: return (new b2PolygonShape(def)); default: return (null); }; } } }//package Box2D.Collision.Shapes
Section 8
//b2ShapeDef (Box2D.Collision.Shapes.b2ShapeDef) package Box2D.Collision.Shapes { public class b2ShapeDef { public var friction:Number;// = 0.2 public var isSensor:Boolean;// = false public var density:Number;// = 0 public var restitution:Number;// = 0 public var userData;// = null public var filter:b2FilterData; public var type:int;// = -1 public function b2ShapeDef(){ filter = new b2FilterData(); super(); } } }//package Box2D.Collision.Shapes
Section 9
//b2AABB (Box2D.Collision.b2AABB) package Box2D.Collision { import Box2D.Common.Math.*; public class b2AABB { public var upperBound:b2Vec2; public var lowerBound:b2Vec2; public function b2AABB(){ lowerBound = new b2Vec2(); upperBound = new b2Vec2(); super(); } public function IsValid():Boolean{ var dX:Number = (upperBound.x - lowerBound.x); var dY:Number = (upperBound.y - lowerBound.y); var valid:Boolean = (((dX >= 0)) && ((dY >= 0))); valid = ((((valid) && (lowerBound.IsValid()))) && (upperBound.IsValid())); return (valid); } } }//package Box2D.Collision
Section 10
//b2Bound (Box2D.Collision.b2Bound) package Box2D.Collision { public class b2Bound { public var value:uint; public var proxyId:uint; public var stabbingCount:uint; public function b2Bound(){ super(); } public function Swap(b:b2Bound):void{ var tempValue:uint = value; var tempProxyId:uint = proxyId; var tempStabbingCount:uint = stabbingCount; value = b.value; proxyId = b.proxyId; stabbingCount = b.stabbingCount; b.value = tempValue; b.proxyId = tempProxyId; b.stabbingCount = tempStabbingCount; } public function IsLower():Boolean{ return (((value & 1) == 0)); } public function IsUpper():Boolean{ return (((value & 1) == 1)); } } }//package Box2D.Collision
Section 11
//b2BoundValues (Box2D.Collision.b2BoundValues) package Box2D.Collision { public class b2BoundValues { public var lowerValues:Array; public var upperValues:Array; public function b2BoundValues(){ lowerValues = [0, 0]; upperValues = [0, 0]; super(); } } }//package Box2D.Collision
Section 12
//b2BroadPhase (Box2D.Collision.b2BroadPhase) package Box2D.Collision { import Box2D.Common.Math.*; import Box2D.Common.*; public class b2BroadPhase { public var m_bounds:Array; public var m_worldAABB:b2AABB; public var m_querySortKeys:Array; public var m_freeProxy:uint; public var m_quantizationFactor:b2Vec2; public var m_proxyCount:int; public var m_proxyPool:Array; public var m_queryResultCount:int; public var m_pairManager:b2PairManager; public var m_timeStamp:uint; public var m_queryResults:Array; public static const b2_nullEdge:uint = 0xFFFF; public static const b2_invalid:uint = 0xFFFF; public static var s_validate:Boolean = false; public function b2BroadPhase(worldAABB:b2AABB, callback:b2PairCallback){ var i:int; var tProxy:b2Proxy; var j:int; m_pairManager = new b2PairManager(); m_proxyPool = new Array(b2Settings.b2_maxPairs); m_bounds = new Array((2 * b2Settings.b2_maxProxies)); m_querySortKeys = new Array(b2Settings.b2_maxProxies); m_queryResults = new Array(b2Settings.b2_maxProxies); m_quantizationFactor = new b2Vec2(); super(); m_pairManager.Initialize(this, callback); m_worldAABB = worldAABB; m_proxyCount = 0; i = 0; while (i < b2Settings.b2_maxProxies) { m_queryResults[i] = 0; m_querySortKeys[i] = 0; i++; }; m_bounds = new Array(2); i = 0; while (i < 2) { m_bounds[i] = new Array((2 * b2Settings.b2_maxProxies)); j = 0; while (j < (2 * b2Settings.b2_maxProxies)) { m_bounds[i][j] = new b2Bound(); j++; }; i++; }; var dX:Number = (worldAABB.upperBound.x - worldAABB.lowerBound.x); var dY:Number = (worldAABB.upperBound.y - worldAABB.lowerBound.y); m_quantizationFactor.x = (b2Settings.USHRT_MAX / dX); m_quantizationFactor.y = (b2Settings.USHRT_MAX / dY); i = 0; while (i < (b2Settings.b2_maxProxies - 1)) { tProxy = new b2Proxy(); m_proxyPool[i] = tProxy; tProxy.SetNext((i + 1)); tProxy.timeStamp = 0; tProxy.overlapCount = b2_invalid; tProxy.userData = null; i++; }; tProxy = new b2Proxy(); m_proxyPool[int((b2Settings.b2_maxProxies - 1))] = tProxy; tProxy.SetNext(b2Pair.b2_nullProxy); tProxy.timeStamp = 0; tProxy.overlapCount = b2_invalid; tProxy.userData = null; m_freeProxy = 0; m_timeStamp = 1; m_queryResultCount = 0; } public function QueryAABB(aabb:b2AABB, userData, maxCount:int):int{ var lowerIndex:uint; var upperIndex:uint; var proxy:b2Proxy; var lowerValues:Array = new Array(); var upperValues:Array = new Array(); ComputeBounds(lowerValues, upperValues, aabb); var lowerIndexOut:Array = [lowerIndex]; var upperIndexOut:Array = [upperIndex]; Query(lowerIndexOut, upperIndexOut, lowerValues[0], upperValues[0], m_bounds[0], (2 * m_proxyCount), 0); Query(lowerIndexOut, upperIndexOut, lowerValues[1], upperValues[1], m_bounds[1], (2 * m_proxyCount), 1); var count:int; var i:int; while ((((i < m_queryResultCount)) && ((count < maxCount)))) { proxy = m_proxyPool[m_queryResults[i]]; userData[i] = proxy.userData; i++; count++; }; m_queryResultCount = 0; IncrementTimeStamp(); return (count); } public function Commit():void{ m_pairManager.Commit(); } public function GetProxy(proxyId:int):b2Proxy{ var proxy:b2Proxy = m_proxyPool[proxyId]; if ((((proxyId == b2Pair.b2_nullProxy)) || ((proxy.IsValid() == false)))){ return (null); }; return (proxy); } private function IncrementTimeStamp():void{ var i:uint; if (m_timeStamp == b2Settings.USHRT_MAX){ i = 0; while (i < b2Settings.b2_maxProxies) { (m_proxyPool[i] as b2Proxy).timeStamp = 0; i++; }; m_timeStamp = 1; } else { m_timeStamp++; }; } private function Query(lowerQueryOut:Array, upperQueryOut:Array, lowerValue:uint, upperValue:uint, bounds:Array, boundCount:uint, axis:int):void{ var bound:b2Bound; var i:int; var s:int; var proxy:b2Proxy; var lowerQuery:uint = BinarySearch(bounds, boundCount, lowerValue); var upperQuery:uint = BinarySearch(bounds, boundCount, upperValue); var j:uint = lowerQuery; while (j < upperQuery) { bound = bounds[j]; if (bound.IsLower()){ IncrementOverlapCount(bound.proxyId); }; j++; }; if (lowerQuery > 0){ i = (lowerQuery - 1); bound = bounds[i]; s = bound.stabbingCount; while (s) { bound = bounds[i]; if (bound.IsLower()){ proxy = m_proxyPool[bound.proxyId]; if (lowerQuery <= proxy.upperBounds[axis]){ IncrementOverlapCount(bound.proxyId); s--; }; }; i--; }; }; lowerQueryOut[0] = lowerQuery; upperQueryOut[0] = upperQuery; } private function AddProxyResult(proxyId:uint, proxy:b2Proxy, maxCount:Number, sortKey:Function):void{ var tempKey2:Number; var tempId2:uint; var key:Number = sortKey(proxy.userData); if (key < 0){ return; }; var i:Number = 0; while ((((i < m_queryResultCount)) && ((m_querySortKeys[i] < key)))) { i++; }; var tempKey:Number = key; var tempId:uint = proxyId; m_queryResultCount = (m_queryResultCount + 1); if (m_queryResultCount > maxCount){ m_queryResultCount = maxCount; }; while (i < m_queryResultCount) { tempKey2 = m_querySortKeys[i]; tempId2 = m_queryResults[i]; m_querySortKeys[i] = tempKey; m_queryResults[i] = tempId; tempKey = tempKey2; tempId = tempId2; i++; }; } private function TestOverlapValidate(p1:b2Proxy, p2:b2Proxy):Boolean{ var bounds:Array; var bound1:b2Bound; var bound2:b2Bound; var axis:int; while (axis < 2) { bounds = m_bounds[axis]; bound1 = bounds[p1.lowerBounds[axis]]; bound2 = bounds[p2.upperBounds[axis]]; if (bound1.value > bound2.value){ return (false); }; bound1 = bounds[p1.upperBounds[axis]]; bound2 = bounds[p2.lowerBounds[axis]]; if (bound1.value < bound2.value){ return (false); }; axis++; }; return (true); } private function ComputeBounds(lowerValues:Array, upperValues:Array, aabb:b2AABB):void{ var minVertexX:Number = aabb.lowerBound.x; var minVertexY:Number = aabb.lowerBound.y; minVertexX = b2Math.b2Min(minVertexX, m_worldAABB.upperBound.x); minVertexY = b2Math.b2Min(minVertexY, m_worldAABB.upperBound.y); minVertexX = b2Math.b2Max(minVertexX, m_worldAABB.lowerBound.x); minVertexY = b2Math.b2Max(minVertexY, m_worldAABB.lowerBound.y); var maxVertexX:Number = aabb.upperBound.x; var maxVertexY:Number = aabb.upperBound.y; maxVertexX = b2Math.b2Min(maxVertexX, m_worldAABB.upperBound.x); maxVertexY = b2Math.b2Min(maxVertexY, m_worldAABB.upperBound.y); maxVertexX = b2Math.b2Max(maxVertexX, m_worldAABB.lowerBound.x); maxVertexY = b2Math.b2Max(maxVertexY, m_worldAABB.lowerBound.y); lowerValues[0] = (uint((m_quantizationFactor.x * (minVertexX - m_worldAABB.lowerBound.x))) & (b2Settings.USHRT_MAX - 1)); upperValues[0] = ((uint((m_quantizationFactor.x * (maxVertexX - m_worldAABB.lowerBound.x))) & 0xFFFF) | 1); lowerValues[1] = (uint((m_quantizationFactor.y * (minVertexY - m_worldAABB.lowerBound.y))) & (b2Settings.USHRT_MAX - 1)); upperValues[1] = ((uint((m_quantizationFactor.y * (maxVertexY - m_worldAABB.lowerBound.y))) & 0xFFFF) | 1); } public function CreateProxy(aabb:b2AABB, userData):uint{ var index:uint; var proxy:b2Proxy; var bounds:Array; var lowerIndex:uint; var upperIndex:uint; var lowerIndexOut:Array; var upperIndexOut:Array; var tArr:Array; var j:int; var tEnd:int; var tBound1:b2Bound; var tBound2:b2Bound; var tBoundAS3:b2Bound; var tIndex:int; var proxy2:b2Proxy; var proxyId:uint = m_freeProxy; proxy = m_proxyPool[proxyId]; m_freeProxy = proxy.GetNext(); proxy.overlapCount = 0; proxy.userData = userData; var boundCount:uint = (2 * m_proxyCount); var lowerValues:Array = new Array(); var upperValues:Array = new Array(); ComputeBounds(lowerValues, upperValues, aabb); var axis:int; while (axis < 2) { bounds = m_bounds[axis]; lowerIndexOut = [lowerIndex]; upperIndexOut = [upperIndex]; Query(lowerIndexOut, upperIndexOut, lowerValues[axis], upperValues[axis], bounds, boundCount, axis); lowerIndex = lowerIndexOut[0]; upperIndex = upperIndexOut[0]; tArr = new Array(); tEnd = (boundCount - upperIndex); j = 0; while (j < tEnd) { tArr[j] = new b2Bound(); tBound1 = tArr[j]; tBound2 = bounds[int((upperIndex + j))]; tBound1.value = tBound2.value; tBound1.proxyId = tBound2.proxyId; tBound1.stabbingCount = tBound2.stabbingCount; j++; }; tEnd = tArr.length; tIndex = (upperIndex + 2); j = 0; while (j < tEnd) { tBound2 = tArr[j]; tBound1 = bounds[int((tIndex + j))]; tBound1.value = tBound2.value; tBound1.proxyId = tBound2.proxyId; tBound1.stabbingCount = tBound2.stabbingCount; j++; }; tArr = new Array(); tEnd = (upperIndex - lowerIndex); j = 0; while (j < tEnd) { tArr[j] = new b2Bound(); tBound1 = tArr[j]; tBound2 = bounds[int((lowerIndex + j))]; tBound1.value = tBound2.value; tBound1.proxyId = tBound2.proxyId; tBound1.stabbingCount = tBound2.stabbingCount; j++; }; tEnd = tArr.length; tIndex = (lowerIndex + 1); j = 0; while (j < tEnd) { tBound2 = tArr[j]; tBound1 = bounds[int((tIndex + j))]; tBound1.value = tBound2.value; tBound1.proxyId = tBound2.proxyId; tBound1.stabbingCount = tBound2.stabbingCount; j++; }; upperIndex++; tBound1 = bounds[lowerIndex]; tBound2 = bounds[upperIndex]; tBound1.value = lowerValues[axis]; tBound1.proxyId = proxyId; tBound2.value = upperValues[axis]; tBound2.proxyId = proxyId; tBoundAS3 = bounds[int((lowerIndex - 1))]; tBound1.stabbingCount = ((lowerIndex == 0)) ? 0 : tBoundAS3.stabbingCount; tBoundAS3 = bounds[int((upperIndex - 1))]; tBound2.stabbingCount = tBoundAS3.stabbingCount; index = lowerIndex; while (index < upperIndex) { tBoundAS3 = bounds[index]; tBoundAS3.stabbingCount++; index++; }; index = lowerIndex; while (index < (boundCount + 2)) { tBound1 = bounds[index]; proxy2 = m_proxyPool[tBound1.proxyId]; if (tBound1.IsLower()){ proxy2.lowerBounds[axis] = index; } else { proxy2.upperBounds[axis] = index; }; index++; }; axis++; }; m_proxyCount++; var i:int; while (i < m_queryResultCount) { m_pairManager.AddBufferedPair(proxyId, m_queryResults[i]); i++; }; m_pairManager.Commit(); m_queryResultCount = 0; IncrementTimeStamp(); return (proxyId); } public function DestroyProxy(proxyId:uint):void{ var tBound1:b2Bound; var tBound2:b2Bound; var bounds:Array; var lowerIndex:uint; var upperIndex:uint; var lowerValue:uint; var upperValue:uint; var tArr:Array; var j:int; var tEnd:int; var tIndex:int; var index:uint; var index2:int; var proxy2:b2Proxy; var proxy:b2Proxy = m_proxyPool[proxyId]; var boundCount:int = (2 * m_proxyCount); var axis:int; while (axis < 2) { bounds = m_bounds[axis]; lowerIndex = proxy.lowerBounds[axis]; upperIndex = proxy.upperBounds[axis]; tBound1 = bounds[lowerIndex]; lowerValue = tBound1.value; tBound2 = bounds[upperIndex]; upperValue = tBound2.value; tArr = new Array(); tEnd = ((upperIndex - lowerIndex) - 1); j = 0; while (j < tEnd) { tArr[j] = new b2Bound(); tBound1 = tArr[j]; tBound2 = bounds[int(((lowerIndex + 1) + j))]; tBound1.value = tBound2.value; tBound1.proxyId = tBound2.proxyId; tBound1.stabbingCount = tBound2.stabbingCount; j++; }; tEnd = tArr.length; tIndex = lowerIndex; j = 0; while (j < tEnd) { tBound2 = tArr[j]; tBound1 = bounds[int((tIndex + j))]; tBound1.value = tBound2.value; tBound1.proxyId = tBound2.proxyId; tBound1.stabbingCount = tBound2.stabbingCount; j++; }; tArr = new Array(); tEnd = ((boundCount - upperIndex) - 1); j = 0; while (j < tEnd) { tArr[j] = new b2Bound(); tBound1 = tArr[j]; tBound2 = bounds[int(((upperIndex + 1) + j))]; tBound1.value = tBound2.value; tBound1.proxyId = tBound2.proxyId; tBound1.stabbingCount = tBound2.stabbingCount; j++; }; tEnd = tArr.length; tIndex = (upperIndex - 1); j = 0; while (j < tEnd) { tBound2 = tArr[j]; tBound1 = bounds[int((tIndex + j))]; tBound1.value = tBound2.value; tBound1.proxyId = tBound2.proxyId; tBound1.stabbingCount = tBound2.stabbingCount; j++; }; tEnd = (boundCount - 2); index = lowerIndex; while (index < tEnd) { tBound1 = bounds[index]; proxy2 = m_proxyPool[tBound1.proxyId]; if (tBound1.IsLower()){ proxy2.lowerBounds[axis] = index; } else { proxy2.upperBounds[axis] = index; }; index++; }; tEnd = (upperIndex - 1); index2 = lowerIndex; while (index2 < tEnd) { tBound1 = bounds[index2]; tBound1.stabbingCount--; index2++; }; Query([0], [0], lowerValue, upperValue, bounds, (boundCount - 2), axis); axis++; }; var i:int; while (i < m_queryResultCount) { m_pairManager.RemoveBufferedPair(proxyId, m_queryResults[i]); i++; }; m_pairManager.Commit(); m_queryResultCount = 0; IncrementTimeStamp(); proxy.userData = null; proxy.overlapCount = b2_invalid; proxy.lowerBounds[0] = b2_invalid; proxy.lowerBounds[1] = b2_invalid; proxy.upperBounds[0] = b2_invalid; proxy.upperBounds[1] = b2_invalid; proxy.SetNext(m_freeProxy); m_freeProxy = proxyId; m_proxyCount--; } public function TestOverlap(b:b2BoundValues, p:b2Proxy):Boolean{ var bounds:Array; var bound:b2Bound; var axis:int; while (axis < 2) { bounds = m_bounds[axis]; bound = bounds[p.upperBounds[axis]]; if (b.lowerValues[axis] > bound.value){ return (false); }; bound = bounds[p.lowerBounds[axis]]; if (b.upperValues[axis] < bound.value){ return (false); }; axis++; }; return (true); } public function Validate():void{ var pair:b2Pair; var proxy1:b2Proxy; var proxy2:b2Proxy; var overlap:Boolean; var bounds:b2Bound; var boundCount:uint; var stabbingCount:uint; var i:uint; var bound:b2Bound; var axis:int; while (axis < 2) { bounds = m_bounds[axis]; boundCount = (2 * m_proxyCount); stabbingCount = 0; i = 0; while (i < boundCount) { bound = bounds[i]; if (bound.IsLower() == true){ stabbingCount++; } else { stabbingCount--; }; i++; }; axis++; }; } private function IncrementOverlapCount(proxyId:uint):void{ var proxy:b2Proxy = m_proxyPool[proxyId]; if (proxy.timeStamp < m_timeStamp){ proxy.timeStamp = m_timeStamp; proxy.overlapCount = 1; } else { proxy.overlapCount = 2; m_queryResults[m_queryResultCount] = proxyId; m_queryResultCount++; }; } public function InRange(aabb:b2AABB):Boolean{ var dX:Number; var dY:Number; var d2X:Number; var d2Y:Number; dX = aabb.lowerBound.x; dY = aabb.lowerBound.y; dX = (dX - m_worldAABB.upperBound.x); dY = (dY - m_worldAABB.upperBound.y); d2X = m_worldAABB.lowerBound.x; d2Y = m_worldAABB.lowerBound.y; d2X = (d2X - aabb.upperBound.x); d2Y = (d2Y - aabb.upperBound.y); dX = b2Math.b2Max(dX, d2X); dY = b2Math.b2Max(dY, d2Y); return ((b2Math.b2Max(dX, dY) < 0)); } public function QuerySegment(segment:b2Segment, userData, maxCount:int, sortKey:Function):int{ var xIndex:int; var yIndex:int; var proxyId:uint; var proxy:b2Proxy; var lowerIndex:uint; var upperIndex:uint; var xProgress:Number; var yProgress:Number; var i:Number; var A:Number; var B:Number; var tempValue:uint; var maxLamda:Number = 1; var dx:Number = ((segment.p2.x - segment.p1.x) * m_quantizationFactor.x); var dy:Number = ((segment.p2.y - segment.p1.y) * m_quantizationFactor.y); var sx:int = ((dx < -(Number.MIN_VALUE))) ? -1 : ((dx > Number.MIN_VALUE)) ? 1 : 0; var sy:int = ((dy < -(Number.MIN_VALUE))) ? -1 : ((dy > Number.MIN_VALUE)) ? 1 : 0; var p1x:Number = (m_quantizationFactor.x * (segment.p1.x - m_worldAABB.lowerBound.x)); var p1y:Number = (m_quantizationFactor.y * (segment.p1.y - m_worldAABB.lowerBound.y)); var startValues:Array = new Array(); var startValues2:Array = new Array(); startValues[0] = (uint(p1x) & (b2Settings.USHRT_MAX - 1)); startValues[1] = (uint(p1y) & (b2Settings.USHRT_MAX - 1)); startValues2[0] = (startValues[0] + 1); startValues2[1] = (startValues[1] + 1); var startIndices:Array = new Array(); var lowerIndexOut:Array = [lowerIndex]; var upperIndexOut:Array = [upperIndex]; Query(lowerIndexOut, upperIndexOut, startValues[0], startValues2[0], m_bounds[0], (2 * m_proxyCount), 0); if (sx >= 0){ xIndex = (upperIndexOut[0] - 1); } else { xIndex = lowerIndexOut[0]; }; Query(lowerIndexOut, upperIndexOut, startValues[1], startValues2[1], m_bounds[1], (2 * m_proxyCount), 1); if (sy >= 0){ yIndex = (upperIndexOut[0] - 1); } else { yIndex = lowerIndexOut[0]; }; if (sortKey != null){ i = 0; while (i < m_queryResultCount) { m_querySortKeys[i] = sortKey(m_proxyPool[m_queryResults[i]].userData); i++; }; i = 0; while (i < (m_queryResultCount - 1)) { A = m_querySortKeys[i]; B = m_querySortKeys[(i + 1)]; if (((A)<0) ? (B >= 0) : (((A > B)) && ((B >= 0)))){ m_querySortKeys[(i + 1)] = A; m_querySortKeys[i] = B; tempValue = m_queryResults[(i + 1)]; m_queryResults[(i + 1)] = m_queryResults[i]; m_queryResults[i] = tempValue; i--; if (i == -1){ i = 1; }; } else { i++; }; }; while ((((m_queryResultCount > 0)) && ((m_querySortKeys[(m_queryResultCount - 1)] < 0)))) { m_queryResultCount--; }; }; var b:Boolean; if ((((xIndex < 0)) || ((xIndex >= (m_proxyCount * 2))))){ b = false; }; if ((((yIndex < 0)) || ((yIndex >= (m_proxyCount * 2))))){ b = false; }; if (b){ if (sx != 0){ if (sx > 0){ xIndex++; if (xIndex == (m_proxyCount * 2)){ b = false; }; } else { xIndex--; if (xIndex < 0){ b = false; }; }; xProgress = ((m_bounds[0][xIndex].value - p1x) / dx); }; if (sy != 0){ if (sy > 0){ yIndex++; if (yIndex == (m_proxyCount * 2)){ b = false; }; } else { yIndex--; if (yIndex < 0){ b = false; }; }; yProgress = ((m_bounds[1][yIndex].value - p1y) / dy); }; }; while (b) { if ((((sy == 0)) || (((!((sx == 0))) && ((xProgress < yProgress)))))){ if (xProgress > maxLamda){ break; }; if (((sx > 0)) ? m_bounds[0][xIndex].IsLower() : m_bounds[0][xIndex].IsUpper()){ proxyId = m_bounds[0][xIndex].proxyId; proxy = m_proxyPool[proxyId]; if (sy >= 0){ if ((((proxy.lowerBounds[1] <= (yIndex - 1))) && ((proxy.upperBounds[1] >= yIndex)))){ if (sortKey != null){ AddProxyResult(proxyId, proxy, maxCount, sortKey); } else { m_queryResults[m_queryResultCount] = proxyId; m_queryResultCount++; }; }; } else { if ((((proxy.lowerBounds[1] <= yIndex)) && ((proxy.upperBounds[1] >= (yIndex + 1))))){ if (sortKey != null){ AddProxyResult(proxyId, proxy, maxCount, sortKey); } else { m_queryResults[m_queryResultCount] = proxyId; m_queryResultCount++; }; }; }; }; if (((((((!((sortKey == null))) && ((m_queryResultCount == maxCount)))) && ((m_queryResultCount > 0)))) && ((xProgress > m_querySortKeys[(m_queryResultCount - 1)])))){ break; }; if (sx > 0){ xIndex++; if (xIndex == (m_proxyCount * 2)){ break; }; } else { xIndex--; if (xIndex < 0){ break; }; }; xProgress = ((m_bounds[0][xIndex].value - p1x) / dx); } else { if (yProgress > maxLamda){ break; }; if (((sy > 0)) ? m_bounds[1][yIndex].IsLower() : m_bounds[1][yIndex].IsUpper()){ proxyId = m_bounds[1][yIndex].proxyId; proxy = m_proxyPool[proxyId]; if (sx >= 0){ if ((((proxy.lowerBounds[0] <= (xIndex - 1))) && ((proxy.upperBounds[0] >= xIndex)))){ if (sortKey != null){ AddProxyResult(proxyId, proxy, maxCount, sortKey); } else { m_queryResults[m_queryResultCount] = proxyId; m_queryResultCount++; }; }; } else { if ((((proxy.lowerBounds[0] <= xIndex)) && ((proxy.upperBounds[0] >= (xIndex + 1))))){ if (sortKey != null){ AddProxyResult(proxyId, proxy, maxCount, sortKey); } else { m_queryResults[m_queryResultCount] = proxyId; m_queryResultCount++; }; }; }; }; if (((((((!((sortKey == null))) && ((m_queryResultCount == maxCount)))) && ((m_queryResultCount > 0)))) && ((yProgress > m_querySortKeys[(m_queryResultCount - 1)])))){ break; }; if (sy > 0){ yIndex++; if (yIndex == (m_proxyCount * 2)){ break; }; } else { yIndex--; if (yIndex < 0){ break; }; }; yProgress = ((m_bounds[1][yIndex].value - p1y) / dy); }; }; var count:int; i = 0; while ((((i < m_queryResultCount)) && ((count < maxCount)))) { proxy = m_proxyPool[m_queryResults[i]]; userData[i] = proxy.userData; i++; count++; }; m_queryResultCount = 0; IncrementTimeStamp(); return (count); } public function MoveProxy(proxyId:uint, aabb:b2AABB):void{ var as3arr:Array; var as3int:int; var axis:uint; var index:uint; var bound:b2Bound; var prevBound:b2Bound; var nextBound:b2Bound; var nextProxyId:uint; var nextProxy:b2Proxy; var bounds:Array; var lowerIndex:uint; var upperIndex:uint; var lowerValue:uint; var upperValue:uint; var deltaLower:int; var deltaUpper:int; var prevProxyId:uint; var prevProxy:b2Proxy; if ((((proxyId == b2Pair.b2_nullProxy)) || ((b2Settings.b2_maxProxies <= proxyId)))){ return; }; if (aabb.IsValid() == false){ return; }; var boundCount:uint = (2 * m_proxyCount); var proxy:b2Proxy = m_proxyPool[proxyId]; var newValues:b2BoundValues = new b2BoundValues(); ComputeBounds(newValues.lowerValues, newValues.upperValues, aabb); var oldValues:b2BoundValues = new b2BoundValues(); axis = 0; while (axis < 2) { bound = m_bounds[axis][proxy.lowerBounds[axis]]; oldValues.lowerValues[axis] = bound.value; bound = m_bounds[axis][proxy.upperBounds[axis]]; oldValues.upperValues[axis] = bound.value; axis++; }; axis = 0; while (axis < 2) { bounds = m_bounds[axis]; lowerIndex = proxy.lowerBounds[axis]; upperIndex = proxy.upperBounds[axis]; lowerValue = newValues.lowerValues[axis]; upperValue = newValues.upperValues[axis]; bound = bounds[lowerIndex]; deltaLower = (lowerValue - bound.value); bound.value = lowerValue; bound = bounds[upperIndex]; deltaUpper = (upperValue - bound.value); bound.value = upperValue; if (deltaLower < 0){ index = lowerIndex; while ((((index > 0)) && ((lowerValue < (bounds[int((index - 1))] as b2Bound).value)))) { bound = bounds[index]; prevBound = bounds[int((index - 1))]; prevProxyId = prevBound.proxyId; prevProxy = m_proxyPool[prevBound.proxyId]; prevBound.stabbingCount++; if (prevBound.IsUpper() == true){ if (TestOverlap(newValues, prevProxy)){ m_pairManager.AddBufferedPair(proxyId, prevProxyId); }; as3arr = prevProxy.upperBounds; as3int = as3arr[axis]; as3int++; as3arr[axis] = as3int; bound.stabbingCount++; } else { as3arr = prevProxy.lowerBounds; as3int = as3arr[axis]; as3int++; as3arr[axis] = as3int; bound.stabbingCount--; }; as3arr = proxy.lowerBounds; as3int = as3arr[axis]; as3int--; as3arr[axis] = as3int; bound.Swap(prevBound); index--; }; }; if (deltaUpper > 0){ index = upperIndex; while ((((index < (boundCount - 1))) && (((bounds[int((index + 1))] as b2Bound).value <= upperValue)))) { bound = bounds[index]; nextBound = bounds[int((index + 1))]; nextProxyId = nextBound.proxyId; nextProxy = m_proxyPool[nextProxyId]; nextBound.stabbingCount++; if (nextBound.IsLower() == true){ if (TestOverlap(newValues, nextProxy)){ m_pairManager.AddBufferedPair(proxyId, nextProxyId); }; as3arr = nextProxy.lowerBounds; as3int = as3arr[axis]; as3int--; as3arr[axis] = as3int; bound.stabbingCount++; } else { as3arr = nextProxy.upperBounds; as3int = as3arr[axis]; as3int--; as3arr[axis] = as3int; bound.stabbingCount--; }; as3arr = proxy.upperBounds; as3int = as3arr[axis]; as3int++; as3arr[axis] = as3int; bound.Swap(nextBound); index++; }; }; if (deltaLower > 0){ index = lowerIndex; while ((((index < (boundCount - 1))) && (((bounds[int((index + 1))] as b2Bound).value <= lowerValue)))) { bound = bounds[index]; nextBound = bounds[int((index + 1))]; nextProxyId = nextBound.proxyId; nextProxy = m_proxyPool[nextProxyId]; nextBound.stabbingCount--; if (nextBound.IsUpper()){ if (TestOverlap(oldValues, nextProxy)){ m_pairManager.RemoveBufferedPair(proxyId, nextProxyId); }; as3arr = nextProxy.upperBounds; as3int = as3arr[axis]; as3int--; as3arr[axis] = as3int; bound.stabbingCount--; } else { as3arr = nextProxy.lowerBounds; as3int = as3arr[axis]; as3int--; as3arr[axis] = as3int; bound.stabbingCount++; }; as3arr = proxy.lowerBounds; as3int = as3arr[axis]; as3int++; as3arr[axis] = as3int; bound.Swap(nextBound); index++; }; }; if (deltaUpper < 0){ index = upperIndex; while ((((index > 0)) && ((upperValue < (bounds[int((index - 1))] as b2Bound).value)))) { bound = bounds[index]; prevBound = bounds[int((index - 1))]; prevProxyId = prevBound.proxyId; prevProxy = m_proxyPool[prevProxyId]; prevBound.stabbingCount--; if (prevBound.IsLower() == true){ if (TestOverlap(oldValues, prevProxy)){ m_pairManager.RemoveBufferedPair(proxyId, prevProxyId); }; as3arr = prevProxy.lowerBounds; as3int = as3arr[axis]; as3int++; as3arr[axis] = as3int; bound.stabbingCount--; } else { as3arr = prevProxy.upperBounds; as3int = as3arr[axis]; as3int++; as3arr[axis] = as3int; bound.stabbingCount++; }; as3arr = proxy.upperBounds; as3int = as3arr[axis]; as3int--; as3arr[axis] = as3int; bound.Swap(prevBound); index--; }; }; axis++; }; } public static function BinarySearch(bounds:Array, count:int, value:uint):uint{ var mid:int; var bound:b2Bound; var low:int; var high:int = (count - 1); while (low <= high) { mid = ((low + high) / 2); bound = bounds[mid]; if (bound.value > value){ high = (mid - 1); } else { if (bound.value < value){ low = (mid + 1); } else { return (uint(mid)); }; }; }; return (uint(low)); } } }//package Box2D.Collision
Section 13
//b2BufferedPair (Box2D.Collision.b2BufferedPair) package Box2D.Collision { public class b2BufferedPair { public var proxyId1:uint; public var proxyId2:uint; public function b2BufferedPair(){ super(); } } }//package Box2D.Collision
Section 14
//b2Collision (Box2D.Collision.b2Collision) package Box2D.Collision { import Box2D.Common.Math.*; import Box2D.Collision.Shapes.*; import Box2D.Common.*; public class b2Collision { public static const b2_nullFeature:uint = 0xFF; private static var b2CollidePolyTempVec:b2Vec2 = new b2Vec2(); public function b2Collision(){ super(); } public static function EdgeSeparation(poly1:b2PolygonShape, xf1:b2XForm, edge1:int, poly2:b2PolygonShape, xf2:b2XForm):Number{ var tMat:b2Mat22; var tVec:b2Vec2; var dot:Number; var count1:int = poly1.m_vertexCount; var vertices1:Array = poly1.m_vertices; var normals1:Array = poly1.m_normals; var count2:int = poly2.m_vertexCount; var vertices2:Array = poly2.m_vertices; tMat = xf1.R; tVec = normals1[edge1]; var normal1WorldX:Number = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); var normal1WorldY:Number = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); tMat = xf2.R; var normal1X:Number = ((tMat.col1.x * normal1WorldX) + (tMat.col1.y * normal1WorldY)); var normal1Y:Number = ((tMat.col2.x * normal1WorldX) + (tMat.col2.y * normal1WorldY)); var index:int; var minDot:Number = Number.MAX_VALUE; var i:int; while (i < count2) { tVec = vertices2[i]; dot = ((tVec.x * normal1X) + (tVec.y * normal1Y)); if (dot < minDot){ minDot = dot; index = i; }; i++; }; tVec = vertices1[edge1]; tMat = xf1.R; var v1X:Number = (xf1.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var v1Y:Number = (xf1.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); tVec = vertices2[index]; tMat = xf2.R; var v2X:Number = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var v2Y:Number = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); v2X = (v2X - v1X); v2Y = (v2Y - v1Y); var separation:Number = ((v2X * normal1WorldX) + (v2Y * normal1WorldY)); return (separation); } public static function b2TestOverlap(a:b2AABB, b:b2AABB):Boolean{ var t1:b2Vec2 = b.lowerBound; var t2:b2Vec2 = a.upperBound; var d1X:Number = (t1.x - t2.x); var d1Y:Number = (t1.y - t2.y); t1 = a.lowerBound; t2 = b.upperBound; var d2X:Number = (t1.x - t2.x); var d2Y:Number = (t1.y - t2.y); if ((((d1X > 0)) || ((d1Y > 0)))){ return (false); }; if ((((d2X > 0)) || ((d2Y > 0)))){ return (false); }; return (true); } public static function FindIncidentEdge(c:Array, poly1:b2PolygonShape, xf1:b2XForm, edge1:int, poly2:b2PolygonShape, xf2:b2XForm):void{ var tMat:b2Mat22; var tVec:b2Vec2; var tClip:ClipVertex; var dot:Number; var count1:int = poly1.m_vertexCount; var normals1:Array = poly1.m_normals; var count2:int = poly2.m_vertexCount; var vertices2:Array = poly2.m_vertices; var normals2:Array = poly2.m_normals; tMat = xf1.R; tVec = normals1[edge1]; var normal1X:Number = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); var normal1Y:Number = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); tMat = xf2.R; var tX:Number = ((tMat.col1.x * normal1X) + (tMat.col1.y * normal1Y)); normal1Y = ((tMat.col2.x * normal1X) + (tMat.col2.y * normal1Y)); normal1X = tX; var index:int; var minDot:Number = Number.MAX_VALUE; var i:int; while (i < count2) { tVec = normals2[i]; dot = ((normal1X * tVec.x) + (normal1Y * tVec.y)); if (dot < minDot){ minDot = dot; index = i; }; i++; }; var i1:int = index; var i2:int = (((i1 + 1) < count2)) ? (i1 + 1) : 0; tClip = c[0]; tVec = vertices2[i1]; tMat = xf2.R; tClip.v.x = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); tClip.v.y = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); tClip.id.features.referenceEdge = edge1; tClip.id.features.incidentEdge = i1; tClip.id.features.incidentVertex = 0; tClip = c[1]; tVec = vertices2[i2]; tMat = xf2.R; tClip.v.x = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); tClip.v.y = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); tClip.id.features.referenceEdge = edge1; tClip.id.features.incidentEdge = i2; tClip.id.features.incidentVertex = 1; } public static function b2CollidePolygons(manifold:b2Manifold, polyA:b2PolygonShape, xfA:b2XForm, polyB:b2PolygonShape, xfB:b2XForm):void{ var cv:ClipVertex; var poly1:b2PolygonShape; var poly2:b2PolygonShape; var edge1:int; var flip:uint; var np:int; var v12:b2Vec2; var separation:Number; var cp:b2ManifoldPoint; manifold.pointCount = 0; var edgeA:int; var edgeAO:Array = [edgeA]; var separationA:Number = FindMaxSeparation(edgeAO, polyA, xfA, polyB, xfB); edgeA = edgeAO[0]; if (separationA > 0){ return; }; var edgeB:int; var edgeBO:Array = [edgeB]; var separationB:Number = FindMaxSeparation(edgeBO, polyB, xfB, polyA, xfA); edgeB = edgeBO[0]; if (separationB > 0){ return; }; var xf1:b2XForm = new b2XForm(); var xf2:b2XForm = new b2XForm(); var k_relativeTol:Number = 0.98; var k_absoluteTol:Number = 0.001; if (separationB > ((k_relativeTol * separationA) + k_absoluteTol)){ poly1 = polyB; poly2 = polyA; xf1.Set(xfB); xf2.Set(xfA); edge1 = edgeB; flip = 1; } else { poly1 = polyA; poly2 = polyB; xf1.Set(xfA); xf2.Set(xfB); edge1 = edgeA; flip = 0; }; var incidentEdge:Array = [new ClipVertex(), new ClipVertex()]; FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); var count1:int = poly1.m_vertexCount; var vertices1:Array = poly1.m_vertices; var tVec:b2Vec2 = vertices1[edge1]; var v11:b2Vec2 = tVec.Copy(); if ((edge1 + 1) < count1){ tVec = vertices1[int((edge1 + 1))]; v12 = tVec.Copy(); } else { tVec = vertices1[0]; v12 = tVec.Copy(); }; var dv:b2Vec2 = b2Math.SubtractVV(v12, v11); var sideNormal:b2Vec2 = b2Math.b2MulMV(xf1.R, b2Math.SubtractVV(v12, v11)); sideNormal.Normalize(); var frontNormal:b2Vec2 = b2Math.b2CrossVF(sideNormal, 1); v11 = b2Math.b2MulX(xf1, v11); v12 = b2Math.b2MulX(xf1, v12); var frontOffset:Number = b2Math.b2Dot(frontNormal, v11); var sideOffset1:Number = -(b2Math.b2Dot(sideNormal, v11)); var sideOffset2:Number = b2Math.b2Dot(sideNormal, v12); var clipPoints1:Array = [new ClipVertex(), new ClipVertex()]; var clipPoints2:Array = [new ClipVertex(), new ClipVertex()]; np = ClipSegmentToLine(clipPoints1, incidentEdge, sideNormal.Negative(), sideOffset1); if (np < 2){ return; }; np = ClipSegmentToLine(clipPoints2, clipPoints1, sideNormal, sideOffset2); if (np < 2){ return; }; manifold.normal = (flip) ? frontNormal.Negative() : frontNormal.Copy(); var pointCount:int; var i:int; while (i < b2Settings.b2_maxManifoldPoints) { cv = clipPoints2[i]; separation = (b2Math.b2Dot(frontNormal, cv.v) - frontOffset); if (separation <= 0){ cp = manifold.points[pointCount]; cp.separation = separation; cp.localPoint1 = b2Math.b2MulXT(xfA, cv.v); cp.localPoint2 = b2Math.b2MulXT(xfB, cv.v); cp.id.key = cv.id._key; cp.id.features.flip = flip; pointCount++; }; i++; }; manifold.pointCount = pointCount; } public static function FindMaxSeparation(edgeIndex:Array, poly1:b2PolygonShape, xf1:b2XForm, poly2:b2PolygonShape, xf2:b2XForm):Number{ var tVec:b2Vec2; var tMat:b2Mat22; var bestEdge:int; var bestSeparation:Number; var increment:int; var dot:Number; var count1:int = poly1.m_vertexCount; var normals1:Array = poly1.m_normals; tMat = xf2.R; tVec = poly2.m_centroid; var dX:Number = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var dY:Number = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); tMat = xf1.R; tVec = poly1.m_centroid; dX = (dX - (xf1.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)))); dY = (dY - (xf1.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)))); var dLocal1X:Number = ((dX * xf1.R.col1.x) + (dY * xf1.R.col1.y)); var dLocal1Y:Number = ((dX * xf1.R.col2.x) + (dY * xf1.R.col2.y)); var edge:int; var maxDot:Number = -(Number.MAX_VALUE); var i:int; while (i < count1) { tVec = normals1[i]; dot = ((tVec.x * dLocal1X) + (tVec.y * dLocal1Y)); if (dot > maxDot){ maxDot = dot; edge = i; }; i++; }; var s:Number = EdgeSeparation(poly1, xf1, edge, poly2, xf2); if (s > 0){ return (s); }; var prevEdge:int = (((edge - 1) >= 0)) ? (edge - 1) : (count1 - 1); var sPrev:Number = EdgeSeparation(poly1, xf1, prevEdge, poly2, xf2); if (sPrev > 0){ return (sPrev); }; var nextEdge:int = (((edge + 1) < count1)) ? (edge + 1) : 0; var sNext:Number = EdgeSeparation(poly1, xf1, nextEdge, poly2, xf2); if (sNext > 0){ return (sNext); }; if ((((sPrev > s)) && ((sPrev > sNext)))){ increment = -1; bestEdge = prevEdge; bestSeparation = sPrev; } else { if (sNext > s){ increment = 1; bestEdge = nextEdge; bestSeparation = sNext; } else { edgeIndex[0] = edge; return (s); }; }; while (true) { if (increment == -1){ edge = (((bestEdge - 1) >= 0)) ? (bestEdge - 1) : (count1 - 1); } else { edge = (((bestEdge + 1) < count1)) ? (bestEdge + 1) : 0; }; s = EdgeSeparation(poly1, xf1, edge, poly2, xf2); if (s > 0){ return (s); }; if (s > bestSeparation){ bestEdge = edge; bestSeparation = s; } else { break; }; }; edgeIndex[0] = bestEdge; return (bestSeparation); } public static function ClipSegmentToLine(vOut:Array, vIn:Array, normal:b2Vec2, offset:Number):int{ var cv:ClipVertex; var numOut:int; var vIn0:b2Vec2; var vIn1:b2Vec2; var distance0:Number; var interp:Number; var tVec:b2Vec2; var cv2:ClipVertex; numOut = 0; cv = vIn[0]; vIn0 = cv.v; cv = vIn[1]; vIn1 = cv.v; distance0 = (b2Math.b2Dot(normal, vIn0) - offset); var distance1:Number = (b2Math.b2Dot(normal, vIn1) - offset); if (distance0 <= 0){ var _temp1 = numOut; numOut = (numOut + 1); var _local14 = _temp1; vOut[_local14] = vIn[0]; }; if (distance1 <= 0){ var _temp2 = numOut; numOut = (numOut + 1); _local14 = _temp2; vOut[_local14] = vIn[1]; }; if ((distance0 * distance1) < 0){ interp = (distance0 / (distance0 - distance1)); cv = vOut[numOut]; tVec = cv.v; tVec.x = (vIn0.x + (interp * (vIn1.x - vIn0.x))); tVec.y = (vIn0.y + (interp * (vIn1.y - vIn0.y))); cv = vOut[numOut]; if (distance0 > 0){ cv2 = vIn[0]; cv.id = cv2.id; } else { cv2 = vIn[1]; cv.id = cv2.id; }; numOut++; }; return (numOut); } public static function b2CollideCircles(manifold:b2Manifold, circle1:b2CircleShape, xf1:b2XForm, circle2:b2CircleShape, xf2:b2XForm):void{ var tMat:b2Mat22; var tVec:b2Vec2; var separation:Number; var dist:Number; var a:Number; manifold.pointCount = 0; tMat = xf1.R; tVec = circle1.m_localPosition; var p1X:Number = (xf1.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var p1Y:Number = (xf1.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); tMat = xf2.R; tVec = circle2.m_localPosition; var p2X:Number = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var p2Y:Number = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); var dX:Number = (p2X - p1X); var dY:Number = (p2Y - p1Y); var distSqr:Number = ((dX * dX) + (dY * dY)); var r1:Number = circle1.m_radius; var r2:Number = circle2.m_radius; var radiusSum:Number = (r1 + r2); if (distSqr > (radiusSum * radiusSum)){ return; }; if (distSqr < Number.MIN_VALUE){ separation = -(radiusSum); manifold.normal.Set(0, 1); } else { dist = Math.sqrt(distSqr); separation = (dist - radiusSum); a = (1 / dist); manifold.normal.x = (a * dX); manifold.normal.y = (a * dY); }; manifold.pointCount = 1; var tPoint:b2ManifoldPoint = manifold.points[0]; tPoint.id.key = 0; tPoint.separation = separation; p1X = (p1X + (r1 * manifold.normal.x)); p1Y = (p1Y + (r1 * manifold.normal.y)); p2X = (p2X - (r2 * manifold.normal.x)); p2Y = (p2Y - (r2 * manifold.normal.y)); var pX:Number = (0.5 * (p1X + p2X)); var pY:Number = (0.5 * (p1Y + p2Y)); var tX:Number = (pX - xf1.position.x); var tY:Number = (pY - xf1.position.y); tPoint.localPoint1.x = ((tX * xf1.R.col1.x) + (tY * xf1.R.col1.y)); tPoint.localPoint1.y = ((tX * xf1.R.col2.x) + (tY * xf1.R.col2.y)); tX = (pX - xf2.position.x); tY = (pY - xf2.position.y); tPoint.localPoint2.x = ((tX * xf2.R.col1.x) + (tY * xf2.R.col1.y)); tPoint.localPoint2.y = ((tX * xf2.R.col2.x) + (tY * xf2.R.col2.y)); } public static function b2CollidePolygonAndCircle(manifold:b2Manifold, polygon:b2PolygonShape, xf1:b2XForm, circle:b2CircleShape, xf2:b2XForm):void{ var tPoint:b2ManifoldPoint; var dX:Number; var dY:Number; var positionX:Number; var positionY:Number; var tVec:b2Vec2; var tMat:b2Mat22; var dist:Number; var pX:Number; var pY:Number; var s:Number; manifold.pointCount = 0; tMat = xf2.R; tVec = circle.m_localPosition; var cX:Number = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var cY:Number = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); dX = (cX - xf1.position.x); dY = (cY - xf1.position.y); tMat = xf1.R; var cLocalX:Number = ((dX * tMat.col1.x) + (dY * tMat.col1.y)); var cLocalY:Number = ((dX * tMat.col2.x) + (dY * tMat.col2.y)); var normalIndex:int; var separation:Number = -(Number.MAX_VALUE); var radius:Number = circle.m_radius; var vertexCount:int = polygon.m_vertexCount; var vertices:Array = polygon.m_vertices; var normals:Array = polygon.m_normals; var i:int; while (i < vertexCount) { tVec = vertices[i]; dX = (cLocalX - tVec.x); dY = (cLocalY - tVec.y); tVec = normals[i]; s = ((tVec.x * dX) + (tVec.y * dY)); if (s > radius){ return; }; if (s > separation){ separation = s; normalIndex = i; }; i++; }; if (separation < Number.MIN_VALUE){ manifold.pointCount = 1; tVec = normals[normalIndex]; tMat = xf1.R; manifold.normal.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); manifold.normal.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); tPoint = manifold.points[0]; tPoint.id.features.incidentEdge = normalIndex; tPoint.id.features.incidentVertex = b2_nullFeature; tPoint.id.features.referenceEdge = 0; tPoint.id.features.flip = 0; positionX = (cX - (radius * manifold.normal.x)); positionY = (cY - (radius * manifold.normal.y)); dX = (positionX - xf1.position.x); dY = (positionY - xf1.position.y); tMat = xf1.R; tPoint.localPoint1.x = ((dX * tMat.col1.x) + (dY * tMat.col1.y)); tPoint.localPoint1.y = ((dX * tMat.col2.x) + (dY * tMat.col2.y)); dX = (positionX - xf2.position.x); dY = (positionY - xf2.position.y); tMat = xf2.R; tPoint.localPoint2.x = ((dX * tMat.col1.x) + (dY * tMat.col1.y)); tPoint.localPoint2.y = ((dX * tMat.col2.x) + (dY * tMat.col2.y)); tPoint.separation = (separation - radius); return; }; var vertIndex1:int = normalIndex; var vertIndex2:int = (((vertIndex1 + 1) < vertexCount)) ? (vertIndex1 + 1) : 0; tVec = vertices[vertIndex1]; var tVec2:b2Vec2 = vertices[vertIndex2]; var eX:Number = (tVec2.x - tVec.x); var eY:Number = (tVec2.y - tVec.y); var length:Number = Math.sqrt(((eX * eX) + (eY * eY))); eX = (eX / length); eY = (eY / length); dX = (cLocalX - tVec.x); dY = (cLocalY - tVec.y); var u:Number = ((dX * eX) + (dY * eY)); tPoint = manifold.points[0]; if (u <= 0){ pX = tVec.x; pY = tVec.y; tPoint.id.features.incidentEdge = b2_nullFeature; tPoint.id.features.incidentVertex = vertIndex1; } else { if (u >= length){ pX = tVec2.x; pY = tVec2.y; tPoint.id.features.incidentEdge = b2_nullFeature; tPoint.id.features.incidentVertex = vertIndex2; } else { pX = ((eX * u) + tVec.x); pY = ((eY * u) + tVec.y); tPoint.id.features.incidentEdge = normalIndex; tPoint.id.features.incidentVertex = 0; }; }; dX = (cLocalX - pX); dY = (cLocalY - pY); dist = Math.sqrt(((dX * dX) + (dY * dY))); dX = (dX / dist); dY = (dY / dist); if (dist > radius){ return; }; manifold.pointCount = 1; tMat = xf1.R; manifold.normal.x = ((tMat.col1.x * dX) + (tMat.col2.x * dY)); manifold.normal.y = ((tMat.col1.y * dX) + (tMat.col2.y * dY)); positionX = (cX - (radius * manifold.normal.x)); positionY = (cY - (radius * manifold.normal.y)); dX = (positionX - xf1.position.x); dY = (positionY - xf1.position.y); tMat = xf1.R; tPoint.localPoint1.x = ((dX * tMat.col1.x) + (dY * tMat.col1.y)); tPoint.localPoint1.y = ((dX * tMat.col2.x) + (dY * tMat.col2.y)); dX = (positionX - xf2.position.x); dY = (positionY - xf2.position.y); tMat = xf2.R; tPoint.localPoint2.x = ((dX * tMat.col1.x) + (dY * tMat.col1.y)); tPoint.localPoint2.y = ((dX * tMat.col2.x) + (dY * tMat.col2.y)); tPoint.separation = (dist - radius); tPoint.id.features.referenceEdge = 0; tPoint.id.features.flip = 0; } } }//package Box2D.Collision
Section 15
//b2ContactID (Box2D.Collision.b2ContactID) package Box2D.Collision { public class b2ContactID { public var _key:uint; public var features:Features; public function b2ContactID(){ features = new Features(); super(); features._m_id = this; } public function Set(id:b2ContactID):void{ key = id._key; } public function Copy():b2ContactID{ var id:b2ContactID = new b2ContactID(); id.key = key; return (id); } public function set key(value:uint):void{ _key = value; features._referenceEdge = (_key & 0xFF); features._incidentEdge = (((_key & 0xFF00) >> 8) & 0xFF); features._incidentVertex = (((_key & 0xFF0000) >> 16) & 0xFF); features._flip = (((_key & 4278190080) >> 24) & 0xFF); } public function get key():uint{ return (_key); } } }//package Box2D.Collision
Section 16
//b2ContactPoint (Box2D.Collision.b2ContactPoint) package Box2D.Collision { import Box2D.Common.Math.*; import Box2D.Collision.Shapes.*; public class b2ContactPoint { public var friction:Number; public var separation:Number; public var normal:b2Vec2; public var position:b2Vec2; public var restitution:Number; public var shape1:b2Shape; public var shape2:b2Shape; public var id:b2ContactID; public var velocity:b2Vec2; public function b2ContactPoint(){ position = new b2Vec2(); velocity = new b2Vec2(); normal = new b2Vec2(); id = new b2ContactID(); super(); } } }//package Box2D.Collision
Section 17
//b2Distance (Box2D.Collision.b2Distance) package Box2D.Collision { import Box2D.Common.Math.*; import Box2D.Collision.Shapes.*; import Box2D.Common.*; public class b2Distance { private static var s_p2s:Array = [new b2Vec2(), new b2Vec2(), new b2Vec2()]; private static var s_p1s:Array = [new b2Vec2(), new b2Vec2(), new b2Vec2()]; private static var s_points:Array = [new b2Vec2(), new b2Vec2(), new b2Vec2()]; private static var gPoint:b2Point = new b2Point(); public static var g_GJK_Iterations:int = 0; public function b2Distance(){ super(); } public static function InPoints(w:b2Vec2, points:Array, pointCount:int):Boolean{ var points_i:b2Vec2; var dX:Number; var dY:Number; var mX:Number; var mY:Number; var k_tolerance:Number = (100 * Number.MIN_VALUE); var i:int; while (i < pointCount) { points_i = points[i]; dX = Math.abs((w.x - points_i.x)); dY = Math.abs((w.y - points_i.y)); mX = Math.max(Math.abs(w.x), Math.abs(points_i.x)); mY = Math.max(Math.abs(w.y), Math.abs(points_i.y)); if ((((dX < (k_tolerance * (mX + 1)))) && ((dY < (k_tolerance * (mY + 1)))))){ return (true); }; i++; }; return (false); } public static function DistanceGeneric(x1:b2Vec2, x2:b2Vec2, shape1, xf1:b2XForm, shape2, xf2:b2XForm):Number{ var tVec:b2Vec2; var vX:Number; var vY:Number; var w1:b2Vec2; var w2:b2Vec2; var wX:Number; var wY:Number; var vw:Number; var maxSqr:Number; var i:int; var p1s:Array = s_p1s; var p2s:Array = s_p2s; var points:Array = s_points; var pointCount:int; x1.SetV(shape1.GetFirstVertex(xf1)); x2.SetV(shape2.GetFirstVertex(xf2)); var vSqr:Number = 0; var maxIterations = 20; var iter:int; while (iter < maxIterations) { vX = (x2.x - x1.x); vY = (x2.y - x1.y); w1 = shape1.Support(xf1, vX, vY); w2 = shape2.Support(xf2, -(vX), -(vY)); vSqr = ((vX * vX) + (vY * vY)); wX = (w2.x - w1.x); wY = (w2.y - w1.y); vw = ((vX * wX) + (vY * wY)); if ((vSqr - ((vX * wX) + (vY * wY))) <= (0.01 * vSqr)){ if (pointCount == 0){ x1.SetV(w1); x2.SetV(w2); }; g_GJK_Iterations = iter; return (Math.sqrt(vSqr)); }; switch (pointCount){ case 0: tVec = p1s[0]; tVec.SetV(w1); tVec = p2s[0]; tVec.SetV(w2); tVec = points[0]; tVec.x = wX; tVec.y = wY; x1.SetV(p1s[0]); x2.SetV(p2s[0]); pointCount++; break; case 1: tVec = p1s[1]; tVec.SetV(w1); tVec = p2s[1]; tVec.SetV(w2); tVec = points[1]; tVec.x = wX; tVec.y = wY; pointCount = ProcessTwo(x1, x2, p1s, p2s, points); break; case 2: tVec = p1s[2]; tVec.SetV(w1); tVec = p2s[2]; tVec.SetV(w2); tVec = points[2]; tVec.x = wX; tVec.y = wY; pointCount = ProcessThree(x1, x2, p1s, p2s, points); break; }; if (pointCount == 3){ g_GJK_Iterations = iter; return (0); }; maxSqr = -(Number.MAX_VALUE); i = 0; while (i < pointCount) { tVec = points[i]; maxSqr = b2Math.b2Max(maxSqr, ((tVec.x * tVec.x) + (tVec.y * tVec.y))); i++; }; if ((((pointCount == 3)) || ((vSqr <= ((100 * Number.MIN_VALUE) * maxSqr))))){ g_GJK_Iterations = iter; vX = (x2.x - x1.x); vY = (x2.y - x1.y); vSqr = ((vX * vX) + (vY * vY)); return (Math.sqrt(vSqr)); }; iter++; }; g_GJK_Iterations = maxIterations; return (Math.sqrt(vSqr)); } public static function DistanceCC(x1:b2Vec2, x2:b2Vec2, circle1:b2CircleShape, xf1:b2XForm, circle2:b2CircleShape, xf2:b2XForm):Number{ var tMat:b2Mat22; var tVec:b2Vec2; var dLen:Number; var distance:Number; tMat = xf1.R; tVec = circle1.m_localPosition; var p1X:Number = (xf1.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var p1Y:Number = (xf1.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); tMat = xf2.R; tVec = circle2.m_localPosition; var p2X:Number = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var p2Y:Number = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); var dX:Number = (p2X - p1X); var dY:Number = (p2Y - p1Y); var dSqr:Number = ((dX * dX) + (dY * dY)); var r1:Number = (circle1.m_radius - b2Settings.b2_toiSlop); var r2:Number = (circle2.m_radius - b2Settings.b2_toiSlop); var r:Number = (r1 + r2); if (dSqr > (r * r)){ dLen = Math.sqrt(((dX * dX) + (dY * dY))); dX = (dX / dLen); dY = (dY / dLen); distance = (dLen - r); x1.x = (p1X + (r1 * dX)); x1.y = (p1Y + (r1 * dY)); x2.x = (p2X - (r2 * dX)); x2.y = (p2Y - (r2 * dY)); return (distance); }; if (dSqr > (Number.MIN_VALUE * Number.MIN_VALUE)){ dLen = Math.sqrt(((dX * dX) + (dY * dY))); dX = (dX / dLen); dY = (dY / dLen); x1.x = (p1X + (r1 * dX)); x1.y = (p1Y + (r1 * dY)); x2.x = x1.x; x2.y = x1.y; return (0); }; x1.x = p1X; x1.y = p1Y; x2.x = x1.x; x2.y = x1.y; return (0); } public static function ProcessThree(x1:b2Vec2, x2:b2Vec2, p1s:Array, p2s:Array, points:Array):int{ var points_0:b2Vec2; var points_1:b2Vec2; var points_2:b2Vec2; var p1s_0:b2Vec2; var p1s_1:b2Vec2; var p1s_2:b2Vec2; var p2s_0:b2Vec2; var p2s_1:b2Vec2; var lambda:Number; points_0 = points[0]; points_1 = points[1]; points_2 = points[2]; p1s_0 = p1s[0]; p1s_1 = p1s[1]; p1s_2 = p1s[2]; p2s_0 = p2s[0]; p2s_1 = p2s[1]; var p2s_2:b2Vec2 = p2s[2]; var aX:Number = points_0.x; var aY:Number = points_0.y; var bX:Number = points_1.x; var bY:Number = points_1.y; var cX:Number = points_2.x; var cY:Number = points_2.y; var abX:Number = (bX - aX); var abY:Number = (bY - aY); var acX:Number = (cX - aX); var acY:Number = (cY - aY); var bcX:Number = (cX - bX); var bcY:Number = (cY - bY); var sn:Number = -(((aX * abX) + (aY * abY))); var sd:Number = ((bX * abX) + (bY * abY)); var tn:Number = -(((aX * acX) + (aY * acY))); var td:Number = ((cX * acX) + (cY * acY)); var un:Number = -(((bX * bcX) + (bY * bcY))); var ud:Number = ((cX * bcX) + (cY * bcY)); if ((((td <= 0)) && ((ud <= 0)))){ x1.SetV(p1s_2); x2.SetV(p2s_2); p1s_0.SetV(p1s_2); p2s_0.SetV(p2s_2); points_0.SetV(points_2); return (1); }; var n:Number = ((abX * acY) - (abY * acX)); var vc:Number = (n * ((aX * bY) - (aY * bX))); var va:Number = (n * ((bX * cY) - (bY * cX))); if ((((((((va <= 0)) && ((un >= 0)))) && ((ud >= 0)))) && (((un + ud) > 0)))){ lambda = (un / (un + ud)); x1.x = (p1s_1.x + (lambda * (p1s_2.x - p1s_1.x))); x1.y = (p1s_1.y + (lambda * (p1s_2.y - p1s_1.y))); x2.x = (p2s_1.x + (lambda * (p2s_2.x - p2s_1.x))); x2.y = (p2s_1.y + (lambda * (p2s_2.y - p2s_1.y))); p1s_0.SetV(p1s_2); p2s_0.SetV(p2s_2); points_0.SetV(points_2); return (2); }; var vb:Number = (n * ((cX * aY) - (cY * aX))); if ((((((((vb <= 0)) && ((tn >= 0)))) && ((td >= 0)))) && (((tn + td) > 0)))){ lambda = (tn / (tn + td)); x1.x = (p1s_0.x + (lambda * (p1s_2.x - p1s_0.x))); x1.y = (p1s_0.y + (lambda * (p1s_2.y - p1s_0.y))); x2.x = (p2s_0.x + (lambda * (p2s_2.x - p2s_0.x))); x2.y = (p2s_0.y + (lambda * (p2s_2.y - p2s_0.y))); p1s_1.SetV(p1s_2); p2s_1.SetV(p2s_2); points_1.SetV(points_2); return (2); }; var denom:Number = ((va + vb) + vc); denom = (1 / denom); var u:Number = (va * denom); var v:Number = (vb * denom); var w:Number = ((1 - u) - v); x1.x = (((u * p1s_0.x) + (v * p1s_1.x)) + (w * p1s_2.x)); x1.y = (((u * p1s_0.y) + (v * p1s_1.y)) + (w * p1s_2.y)); x2.x = (((u * p2s_0.x) + (v * p2s_1.x)) + (w * p2s_2.x)); x2.y = (((u * p2s_0.y) + (v * p2s_1.y)) + (w * p2s_2.y)); return (3); } public static function DistancePC(x1:b2Vec2, x2:b2Vec2, polygon:b2PolygonShape, xf1:b2XForm, circle:b2CircleShape, xf2:b2XForm):Number{ var tMat:b2Mat22; var tVec:b2Vec2; var dX:Number; var dY:Number; var dLen:Number; var point:b2Point = gPoint; tVec = circle.m_localPosition; tMat = xf2.R; point.p.x = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); point.p.y = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); var distance:Number = DistanceGeneric(x1, x2, polygon, xf1, point, b2Math.b2XForm_identity); var r:Number = (circle.m_radius - b2Settings.b2_toiSlop); if (distance > r){ distance = (distance - r); dX = (x2.x - x1.x); dY = (x2.y - x1.y); dLen = Math.sqrt(((dX * dX) + (dY * dY))); dX = (dX / dLen); dY = (dY / dLen); x2.x = (x2.x - (r * dX)); x2.y = (x2.y - (r * dY)); } else { distance = 0; x2.x = x1.x; x2.y = x1.y; }; return (distance); } public static function Distance(x1:b2Vec2, x2:b2Vec2, shape1:b2Shape, xf1:b2XForm, shape2:b2Shape, xf2:b2XForm):Number{ var type1:int = shape1.m_type; var type2:int = shape2.m_type; if ((((type1 == b2Shape.e_circleShape)) && ((type2 == b2Shape.e_circleShape)))){ return (DistanceCC(x1, x2, (shape1 as b2CircleShape), xf1, (shape2 as b2CircleShape), xf2)); }; if ((((type1 == b2Shape.e_polygonShape)) && ((type2 == b2Shape.e_circleShape)))){ return (DistancePC(x1, x2, (shape1 as b2PolygonShape), xf1, (shape2 as b2CircleShape), xf2)); }; if ((((type1 == b2Shape.e_circleShape)) && ((type2 == b2Shape.e_polygonShape)))){ return (DistancePC(x2, x1, (shape2 as b2PolygonShape), xf2, (shape1 as b2CircleShape), xf1)); }; if ((((type1 == b2Shape.e_polygonShape)) && ((type2 == b2Shape.e_polygonShape)))){ return (DistanceGeneric(x1, x2, (shape1 as b2PolygonShape), xf1, (shape2 as b2PolygonShape), xf2)); }; return (0); } public static function ProcessTwo(x1:b2Vec2, x2:b2Vec2, p1s:Array, p2s:Array, points:Array):int{ var p1s_1:b2Vec2; var p2s_0:b2Vec2; var p2s_1:b2Vec2; var lambda:Number; var points_0:b2Vec2 = points[0]; var points_1:b2Vec2 = points[1]; var p1s_0:b2Vec2 = p1s[0]; p1s_1 = p1s[1]; p2s_0 = p2s[0]; p2s_1 = p2s[1]; var rX:Number = -(points_1.x); var rY:Number = -(points_1.y); var dX:Number = (points_0.x - points_1.x); var dY:Number = (points_0.y - points_1.y); var length:Number = Math.sqrt(((dX * dX) + (dY * dY))); dX = (dX / length); dY = (dY / length); lambda = ((rX * dX) + (rY * dY)); if ((((lambda <= 0)) || ((length < Number.MIN_VALUE)))){ x1.SetV(p1s_1); x2.SetV(p2s_1); p1s_0.SetV(p1s_1); p2s_0.SetV(p2s_1); points_0.SetV(points_1); return (1); }; lambda = (lambda / length); x1.x = (p1s_1.x + (lambda * (p1s_0.x - p1s_1.x))); x1.y = (p1s_1.y + (lambda * (p1s_0.y - p1s_1.y))); x2.x = (p2s_1.x + (lambda * (p2s_0.x - p2s_1.x))); x2.y = (p2s_1.y + (lambda * (p2s_0.y - p2s_1.y))); return (2); } } }//package Box2D.Collision
Section 18
//b2Manifold (Box2D.Collision.b2Manifold) package Box2D.Collision { import Box2D.Common.Math.*; import Box2D.Common.*; public class b2Manifold { public var pointCount:int;// = 0 public var normal:b2Vec2; public var points:Array; public function b2Manifold(){ super(); points = new Array(b2Settings.b2_maxManifoldPoints); var i:int; while (i < b2Settings.b2_maxManifoldPoints) { points[i] = new b2ManifoldPoint(); i++; }; normal = new b2Vec2(); } public function Set(m:b2Manifold):void{ pointCount = m.pointCount; var i:int; while (i < b2Settings.b2_maxManifoldPoints) { (points[i] as b2ManifoldPoint).Set(m.points[i]); i++; }; normal.SetV(m.normal); } public function Reset():void{ var i:int; while (i < b2Settings.b2_maxManifoldPoints) { (points[i] as b2ManifoldPoint).Reset(); i++; }; normal.SetZero(); pointCount = 0; } } }//package Box2D.Collision
Section 19
//b2ManifoldPoint (Box2D.Collision.b2ManifoldPoint) package Box2D.Collision { import Box2D.Common.Math.*; public class b2ManifoldPoint { public var separation:Number; public var localPoint2:b2Vec2; public var normalImpulse:Number; public var tangentImpulse:Number; public var localPoint1:b2Vec2; public var id:b2ContactID; public function b2ManifoldPoint(){ localPoint1 = new b2Vec2(); localPoint2 = new b2Vec2(); id = new b2ContactID(); super(); } public function Set(m:b2ManifoldPoint):void{ localPoint1.SetV(m.localPoint1); localPoint2.SetV(m.localPoint2); separation = m.separation; normalImpulse = m.normalImpulse; tangentImpulse = m.tangentImpulse; id.key = m.id.key; } public function Reset():void{ localPoint1.SetZero(); localPoint2.SetZero(); separation = 0; normalImpulse = 0; tangentImpulse = 0; id.key = 0; } } }//package Box2D.Collision
Section 20
//b2OBB (Box2D.Collision.b2OBB) package Box2D.Collision { import Box2D.Common.Math.*; public class b2OBB { public var R:b2Mat22; public var center:b2Vec2; public var extents:b2Vec2; public function b2OBB(){ R = new b2Mat22(); center = new b2Vec2(); extents = new b2Vec2(); super(); } } }//package Box2D.Collision
Section 21
//b2Pair (Box2D.Collision.b2Pair) package Box2D.Collision { import Box2D.Common.*; public class b2Pair { public var proxyId1:uint; public var userData;// = null public var proxyId2:uint; public var status:uint; public var next:uint; public static var e_pairFinal:uint = 4; public static var b2_tableMask:int = (b2_tableCapacity - 1); public static var e_pairRemoved:uint = 2; public static var b2_nullPair:uint = b2Settings.USHRT_MAX; public static var e_pairBuffered:uint = 1; public static var b2_nullProxy:uint = b2Settings.USHRT_MAX; public static var b2_tableCapacity:int = b2Settings.b2_maxPairs; public function b2Pair(){ super(); } public function SetBuffered():void{ status = (status | e_pairBuffered); } public function IsBuffered():Boolean{ return (((status & e_pairBuffered) == e_pairBuffered)); } public function IsFinal():Boolean{ return (((status & e_pairFinal) == e_pairFinal)); } public function ClearRemoved():void{ status = (status & ~(e_pairRemoved)); } public function SetFinal():void{ status = (status | e_pairFinal); } public function IsRemoved():Boolean{ return (((status & e_pairRemoved) == e_pairRemoved)); } public function ClearBuffered():void{ status = (status & ~(e_pairBuffered)); } public function SetRemoved():void{ status = (status | e_pairRemoved); } } }//package Box2D.Collision
Section 22
//b2PairCallback (Box2D.Collision.b2PairCallback) package Box2D.Collision { public class b2PairCallback { public function b2PairCallback(){ super(); } public function PairRemoved(proxyUserData1, proxyUserData2, pairUserData):void{ } public function PairAdded(proxyUserData1, proxyUserData2){ return (null); } } }//package Box2D.Collision
Section 23
//b2PairManager (Box2D.Collision.b2PairManager) package Box2D.Collision { import Box2D.Common.Math.*; import Box2D.Common.*; public class b2PairManager { public var m_pairCount:int; public var m_pairBuffer:Array; public var m_hashTable:Array; public var m_callback:b2PairCallback; public var m_pairs:Array; public var m_pairBufferCount:int; public var m_broadPhase:b2BroadPhase; public var m_freePair:uint; public function b2PairManager(){ var i:uint; super(); m_hashTable = new Array(b2Pair.b2_tableCapacity); i = 0; while (i < b2Pair.b2_tableCapacity) { m_hashTable[i] = b2Pair.b2_nullPair; i++; }; m_pairs = new Array(b2Settings.b2_maxPairs); i = 0; while (i < b2Settings.b2_maxPairs) { m_pairs[i] = new b2Pair(); i++; }; m_pairBuffer = new Array(b2Settings.b2_maxPairs); i = 0; while (i < b2Settings.b2_maxPairs) { m_pairBuffer[i] = new b2BufferedPair(); i++; }; i = 0; while (i < b2Settings.b2_maxPairs) { m_pairs[i].proxyId1 = b2Pair.b2_nullProxy; m_pairs[i].proxyId2 = b2Pair.b2_nullProxy; m_pairs[i].userData = null; m_pairs[i].status = 0; m_pairs[i].next = (i + 1); i++; }; m_pairs[int((b2Settings.b2_maxPairs - 1))].next = b2Pair.b2_nullPair; m_pairCount = 0; m_pairBufferCount = 0; } private function FindHash(proxyId1:uint, proxyId2:uint, hash:uint):b2Pair{ var pair:b2Pair; var index:uint = m_hashTable[hash]; pair = m_pairs[index]; while (((!((index == b2Pair.b2_nullPair))) && ((Equals(pair, proxyId1, proxyId2) == false)))) { index = pair.next; pair = m_pairs[index]; }; if (index == b2Pair.b2_nullPair){ return (null); }; return (pair); } private function Find(proxyId1:uint, proxyId2:uint):b2Pair{ var temp:uint; if (proxyId1 > proxyId2){ temp = proxyId1; proxyId1 = proxyId2; proxyId2 = temp; }; var hash:uint = (Hash(proxyId1, proxyId2) & b2Pair.b2_tableMask); return (FindHash(proxyId1, proxyId2, hash)); } private function ValidateBuffer():void{ } public function Commit():void{ var bufferedPair:b2BufferedPair; var i:int; var pair:b2Pair; var proxy1:b2Proxy; var proxy2:b2Proxy; var removeCount:int; var proxies:Array = m_broadPhase.m_proxyPool; i = 0; while (i < m_pairBufferCount) { bufferedPair = m_pairBuffer[i]; pair = Find(bufferedPair.proxyId1, bufferedPair.proxyId2); pair.ClearBuffered(); proxy1 = proxies[pair.proxyId1]; proxy2 = proxies[pair.proxyId2]; if (pair.IsRemoved()){ if (pair.IsFinal() == true){ m_callback.PairRemoved(proxy1.userData, proxy2.userData, pair.userData); }; bufferedPair = m_pairBuffer[removeCount]; bufferedPair.proxyId1 = pair.proxyId1; bufferedPair.proxyId2 = pair.proxyId2; removeCount++; } else { if (pair.IsFinal() == false){ pair.userData = m_callback.PairAdded(proxy1.userData, proxy2.userData); pair.SetFinal(); }; }; i++; }; i = 0; while (i < removeCount) { bufferedPair = m_pairBuffer[i]; RemovePair(bufferedPair.proxyId1, bufferedPair.proxyId2); i++; }; m_pairBufferCount = 0; if (b2BroadPhase.s_validate){ ValidateTable(); }; } public function RemoveBufferedPair(proxyId1:int, proxyId2:int):void{ var bufferedPair:b2BufferedPair; var pair:b2Pair = Find(proxyId1, proxyId2); if (pair == null){ return; }; if (pair.IsBuffered() == false){ pair.SetBuffered(); bufferedPair = m_pairBuffer[m_pairBufferCount]; bufferedPair.proxyId1 = pair.proxyId1; bufferedPair.proxyId2 = pair.proxyId2; m_pairBufferCount++; }; pair.SetRemoved(); if (b2BroadPhase.s_validate){ ValidateBuffer(); }; } private function RemovePair(proxyId1:uint, proxyId2:uint){ var pair:b2Pair; var temp:uint; var index:uint; var userData:*; if (proxyId1 > proxyId2){ temp = proxyId1; proxyId1 = proxyId2; proxyId2 = temp; }; var hash:uint = (Hash(proxyId1, proxyId2) & b2Pair.b2_tableMask); var node:uint = m_hashTable[hash]; var pNode:b2Pair; while (node != b2Pair.b2_nullPair) { if (Equals(m_pairs[node], proxyId1, proxyId2)){ index = node; pair = m_pairs[node]; if (pNode){ pNode.next = pair.next; } else { m_hashTable[hash] = pair.next; }; pair = m_pairs[index]; userData = pair.userData; pair.next = m_freePair; pair.proxyId1 = b2Pair.b2_nullProxy; pair.proxyId2 = b2Pair.b2_nullProxy; pair.userData = null; pair.status = 0; m_freePair = index; m_pairCount--; return (userData); } else { pNode = m_pairs[node]; node = pNode.next; }; }; return (null); } public function Initialize(broadPhase:b2BroadPhase, callback:b2PairCallback):void{ m_broadPhase = broadPhase; m_callback = callback; } public function AddBufferedPair(proxyId1:int, proxyId2:int):void{ var bufferedPair:b2BufferedPair; var pair:b2Pair = AddPair(proxyId1, proxyId2); if (pair.IsBuffered() == false){ pair.SetBuffered(); bufferedPair = m_pairBuffer[m_pairBufferCount]; bufferedPair.proxyId1 = pair.proxyId1; bufferedPair.proxyId2 = pair.proxyId2; m_pairBufferCount++; }; pair.ClearRemoved(); if (b2BroadPhase.s_validate){ ValidateBuffer(); }; } private function AddPair(proxyId1:uint, proxyId2:uint):b2Pair{ var temp:uint; if (proxyId1 > proxyId2){ temp = proxyId1; proxyId1 = proxyId2; proxyId2 = temp; }; var hash:uint = (Hash(proxyId1, proxyId2) & b2Pair.b2_tableMask); var pair = FindHash(proxyId1, proxyId2, hash); if (pair != null){ return (pair); }; var pIndex:uint = m_freePair; pair = m_pairs[pIndex]; m_freePair = pair.next; pair.proxyId1 = proxyId1; pair.proxyId2 = proxyId2; pair.status = 0; pair.userData = null; pair.next = m_hashTable[hash]; m_hashTable[hash] = pIndex; m_pairCount++; return (pair); } private function ValidateTable():void{ } public static function EqualsPair(pair1:b2BufferedPair, pair2:b2BufferedPair):Boolean{ return ((((pair1.proxyId1 == pair2.proxyId1)) && ((pair1.proxyId2 == pair2.proxyId2)))); } public static function Hash(proxyId1:uint, proxyId2:uint):uint{ var key:uint = (((proxyId2 << 16) & 4294901760) | proxyId1); key = (~(key) + ((key << 15) & 4294934528)); key = (key ^ ((key >> 12) & 1048575)); key = (key + ((key << 2) & 4294967292)); key = (key ^ ((key >> 4) & 268435455)); key = (key * 2057); key = (key ^ ((key >> 16) & 0xFFFF)); return (key); } public static function Equals(pair:b2Pair, proxyId1:uint, proxyId2:uint):Boolean{ return ((((pair.proxyId1 == proxyId1)) && ((pair.proxyId2 == proxyId2)))); } } }//package Box2D.Collision
Section 24
//b2Point (Box2D.Collision.b2Point) package Box2D.Collision { import Box2D.Common.Math.*; public class b2Point { public var p:b2Vec2; public function b2Point(){ p = new b2Vec2(); super(); } public function GetFirstVertex(xf:b2XForm):b2Vec2{ return (p); } public function Support(xf:b2XForm, vX:Number, vY:Number):b2Vec2{ return (p); } } }//package Box2D.Collision
Section 25
//b2Proxy (Box2D.Collision.b2Proxy) package Box2D.Collision { public class b2Proxy { public var overlapCount:uint; public var userData;// = null public var lowerBounds:Array; public var upperBounds:Array; public var timeStamp:uint; public function b2Proxy(){ lowerBounds = [uint(0), uint(0)]; upperBounds = [uint(0), uint(0)]; super(); } public function GetNext():uint{ return (lowerBounds[0]); } public function IsValid():Boolean{ return (!((overlapCount == b2BroadPhase.b2_invalid))); } public function SetNext(next:uint):void{ lowerBounds[0] = (next & 0xFFFF); } } }//package Box2D.Collision
Section 26
//b2Segment (Box2D.Collision.b2Segment) package Box2D.Collision { import Box2D.Common.Math.*; public class b2Segment { public var p1:b2Vec2; public var p2:b2Vec2; public function b2Segment(){ p1 = new b2Vec2(); p2 = new b2Vec2(); super(); } public function TestSegment(lambda:Array, normal:b2Vec2, segment:b2Segment, maxLambda:Number):Boolean{ var bX:Number; var bY:Number; var a:Number; var mu2:Number; var nLen:Number; var s:b2Vec2 = segment.p1; var rX:Number = (segment.p2.x - s.x); var rY:Number = (segment.p2.y - s.y); var dX:Number = (p2.x - p1.x); var dY:Number = (p2.y - p1.y); var nX:Number = dY; var nY:Number = -(dX); var k_slop:Number = (100 * Number.MIN_VALUE); var denom:Number = -(((rX * nX) + (rY * nY))); if (denom > k_slop){ bX = (s.x - p1.x); bY = (s.y - p1.y); a = ((bX * nX) + (bY * nY)); if ((((0 <= a)) && ((a <= (maxLambda * denom))))){ mu2 = ((-(rY) * bY) + (rY * bX)); if (((((-(k_slop) * denom) <= mu2)) && ((mu2 <= (denom * (1 + k_slop)))))){ a = (a / denom); nLen = Math.sqrt(((nX * nX) + (nY * nY))); nX = (nX / nLen); nY = (nY / nLen); lambda[0] = a; normal.Set(nX, nY); return (true); }; }; }; return (false); } } }//package Box2D.Collision
Section 27
//b2TimeOfImpact (Box2D.Collision.b2TimeOfImpact) package Box2D.Collision { import Box2D.Common.Math.*; import Box2D.Collision.Shapes.*; import Box2D.Common.*; public class b2TimeOfImpact { public static var s_xf1:b2XForm = new b2XForm(); public static var s_xf2:b2XForm = new b2XForm(); public static var s_p1:b2Vec2 = new b2Vec2(); public static var s_p2:b2Vec2 = new b2Vec2(); public function b2TimeOfImpact(){ super(); } public static function TimeOfImpact(shape1:b2Shape, sweep1:b2Sweep, shape2:b2Shape, sweep2:b2Sweep):Number{ var math1:Number; var math2:Number; var t:Number; var xf1:b2XForm; var xf2:b2XForm; var nLen:Number; var approachVelocityBound:Number; var dAlpha:Number; var newAlpha:Number; var r1:Number = shape1.m_sweepRadius; var r2:Number = shape2.m_sweepRadius; var t0:Number = sweep1.t0; var v1X:Number = (sweep1.c.x - sweep1.c0.x); var v1Y:Number = (sweep1.c.y - sweep1.c0.y); var v2X:Number = (sweep2.c.x - sweep2.c0.x); var v2Y:Number = (sweep2.c.y - sweep2.c0.y); var omega1:Number = (sweep1.a - sweep1.a0); var omega2:Number = (sweep2.a - sweep2.a0); var alpha:Number = 0; var p1:b2Vec2 = s_p1; var p2:b2Vec2 = s_p2; var k_maxIterations = 20; var iter:int; var normalX:Number = 0; var normalY:Number = 0; var distance:Number = 0; var targetDistance:Number = 0; while (true) { t = (((1 - alpha) * t0) + alpha); xf1 = s_xf1; xf2 = s_xf2; sweep1.GetXForm(xf1, t); sweep2.GetXForm(xf2, t); distance = b2Distance.Distance(p1, p2, shape1, xf1, shape2, xf2); if (iter == 0){ if (distance > (2 * b2Settings.b2_toiSlop)){ targetDistance = (1.5 * b2Settings.b2_toiSlop); } else { math1 = (0.05 * b2Settings.b2_toiSlop); math2 = (distance - (0.5 * b2Settings.b2_toiSlop)); targetDistance = ((math1 > math2)) ? math1 : math2; }; }; if (((((distance - targetDistance) < (0.05 * b2Settings.b2_toiSlop))) || ((iter == k_maxIterations)))){ break; }; normalX = (p2.x - p1.x); normalY = (p2.y - p1.y); nLen = Math.sqrt(((normalX * normalX) + (normalY * normalY))); normalX = (normalX / nLen); normalY = (normalY / nLen); approachVelocityBound = ((((normalX * (v1X - v2X)) + (normalY * (v1Y - v2Y))) + (((omega1 < 0)) ? -(omega1) : omega1 * r1)) + (((omega2 < 0)) ? -(omega2) : omega2 * r2)); if (approachVelocityBound == 0){ alpha = 1; break; }; dAlpha = ((distance - targetDistance) / approachVelocityBound); newAlpha = (alpha + dAlpha); if ((((newAlpha < 0)) || ((1 < newAlpha)))){ alpha = 1; break; }; if (newAlpha < ((1 + (100 * Number.MIN_VALUE)) * alpha)){ break; }; alpha = newAlpha; iter++; }; return (alpha); } } }//package Box2D.Collision
Section 28
//ClipVertex (Box2D.Collision.ClipVertex) package Box2D.Collision { import Box2D.Common.Math.*; public class ClipVertex { public var id:b2ContactID; public var v:b2Vec2; public function ClipVertex(){ v = new b2Vec2(); id = new b2ContactID(); super(); } } }//package Box2D.Collision
Section 29
//Features (Box2D.Collision.Features) package Box2D.Collision { public class Features { public var _referenceEdge:int; public var _incidentEdge:int; public var _flip:int; public var _incidentVertex:int; public var _m_id:b2ContactID; public function Features(){ super(); } public function get referenceEdge():int{ return (_referenceEdge); } public function set incidentVertex(value:int):void{ _incidentVertex = value; _m_id._key = ((_m_id._key & 4278255615) | ((_incidentVertex << 16) & 0xFF0000)); } public function get flip():int{ return (_flip); } public function get incidentEdge():int{ return (_incidentEdge); } public function set referenceEdge(value:int):void{ _referenceEdge = value; _m_id._key = ((_m_id._key & 4294967040) | (_referenceEdge & 0xFF)); } public function get incidentVertex():int{ return (_incidentVertex); } public function set flip(value:int):void{ _flip = value; _m_id._key = ((_m_id._key & 0xFFFFFF) | ((_flip << 24) & 4278190080)); } public function set incidentEdge(value:int):void{ _incidentEdge = value; _m_id._key = ((_m_id._key & 4294902015) | ((_incidentEdge << 8) & 0xFF00)); } } }//package Box2D.Collision
Section 30
//b2Mat22 (Box2D.Common.Math.b2Mat22) package Box2D.Common.Math { public class b2Mat22 { public var col1:b2Vec2; public var col2:b2Vec2; public function b2Mat22(angle:Number=0, c1:b2Vec2=null, c2:b2Vec2=null){ var c:Number; var s:Number; col1 = new b2Vec2(); col2 = new b2Vec2(); super(); if (((!((c1 == null))) && (!((c2 == null))))){ col1.SetV(c1); col2.SetV(c2); } else { c = Math.cos(angle); s = Math.sin(angle); col1.x = c; col2.x = -(s); col1.y = s; col2.y = c; }; } public function SetIdentity():void{ col1.x = 1; col2.x = 0; col1.y = 0; col2.y = 1; } public function SetVV(c1:b2Vec2, c2:b2Vec2):void{ col1.SetV(c1); col2.SetV(c2); } public function Set(angle:Number):void{ var c:Number; c = Math.cos(angle); var s:Number = Math.sin(angle); col1.x = c; col2.x = -(s); col1.y = s; col2.y = c; } public function SetZero():void{ col1.x = 0; col2.x = 0; col1.y = 0; col2.y = 0; } public function SetM(m:b2Mat22):void{ col1.SetV(m.col1); col2.SetV(m.col2); } public function AddM(m:b2Mat22):void{ col1.x = (col1.x + m.col1.x); col1.y = (col1.y + m.col1.y); col2.x = (col2.x + m.col2.x); col2.y = (col2.y + m.col2.y); } public function Abs():void{ col1.Abs(); col2.Abs(); } public function Copy():b2Mat22{ return (new b2Mat22(0, col1, col2)); } public function Invert(out:b2Mat22):b2Mat22{ var a:Number; var c:Number; var det:Number; a = col1.x; var b:Number = col2.x; c = col1.y; var d:Number = col2.y; det = ((a * d) - (b * c)); det = (1 / det); out.col1.x = (det * d); out.col2.x = (-(det) * b); out.col1.y = (-(det) * c); out.col2.y = (det * a); return (out); } public function GetAngle():Number{ return (Math.atan2(col1.y, col1.x)); } public function Solve(out:b2Vec2, bX:Number, bY:Number):b2Vec2{ var a11:Number = col1.x; var a12:Number = col2.x; var a21:Number = col1.y; var a22:Number = col2.y; var det:Number = ((a11 * a22) - (a12 * a21)); det = (1 / det); out.x = (det * ((a22 * bX) - (a12 * bY))); out.y = (det * ((a11 * bY) - (a21 * bX))); return (out); } } }//package Box2D.Common.Math
Section 31
//b2Math (Box2D.Common.Math.b2Math) package Box2D.Common.Math { public class b2Math { public static const b2Mat22_identity:b2Mat22 = new b2Mat22(0, new b2Vec2(1, 0), new b2Vec2(0, 1)); public static const b2XForm_identity:b2XForm = new b2XForm(b2Vec2_zero, b2Mat22_identity); public static const b2Vec2_zero:b2Vec2 = new b2Vec2(0, 0); public function b2Math(){ super(); } public static function b2CrossVF(a:b2Vec2, s:Number):b2Vec2{ var v:b2Vec2 = new b2Vec2((s * a.y), (-(s) * a.x)); return (v); } public static function AddVV(a:b2Vec2, b:b2Vec2):b2Vec2{ var v:b2Vec2 = new b2Vec2((a.x + b.x), (a.y + b.y)); return (v); } public static function b2IsValid(x:Number):Boolean{ return (isFinite(x)); } public static function b2MinV(a:b2Vec2, b:b2Vec2):b2Vec2{ var c:b2Vec2 = new b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y)); return (c); } public static function b2MulX(T:b2XForm, v:b2Vec2):b2Vec2{ var a:b2Vec2; a = b2MulMV(T.R, v); a.x = (a.x + T.position.x); a.y = (a.y + T.position.y); return (a); } public static function b2DistanceSquared(a:b2Vec2, b:b2Vec2):Number{ var cX:Number = (a.x - b.x); var cY:Number = (a.y - b.y); return (((cX * cX) + (cY * cY))); } public static function b2Swap(a:Array, b:Array):void{ var tmp:* = a[0]; a[0] = b[0]; b[0] = tmp; } public static function b2AbsM(A:b2Mat22):b2Mat22{ var B:b2Mat22 = new b2Mat22(0, b2AbsV(A.col1), b2AbsV(A.col2)); return (B); } public static function SubtractVV(a:b2Vec2, b:b2Vec2):b2Vec2{ var v:b2Vec2 = new b2Vec2((a.x - b.x), (a.y - b.y)); return (v); } public static function b2MulXT(T:b2XForm, v:b2Vec2):b2Vec2{ var a:b2Vec2; var tX:Number; a = SubtractVV(v, T.position); tX = ((a.x * T.R.col1.x) + (a.y * T.R.col1.y)); a.y = ((a.x * T.R.col2.x) + (a.y * T.R.col2.y)); a.x = tX; return (a); } public static function b2Abs(a:Number):Number{ return (((a > 0)) ? a : -(a)); } public static function b2Clamp(a:Number, low:Number, high:Number):Number{ return (b2Max(low, b2Min(a, high))); } public static function b2AbsV(a:b2Vec2):b2Vec2{ var b:b2Vec2 = new b2Vec2(b2Abs(a.x), b2Abs(a.y)); return (b); } public static function MulFV(s:Number, a:b2Vec2):b2Vec2{ var v:b2Vec2 = new b2Vec2((s * a.x), (s * a.y)); return (v); } public static function b2CrossVV(a:b2Vec2, b:b2Vec2):Number{ return (((a.x * b.y) - (a.y * b.x))); } public static function b2Dot(a:b2Vec2, b:b2Vec2):Number{ return (((a.x * b.x) + (a.y * b.y))); } public static function b2CrossFV(s:Number, a:b2Vec2):b2Vec2{ var v:b2Vec2 = new b2Vec2((-(s) * a.y), (s * a.x)); return (v); } public static function AddMM(A:b2Mat22, B:b2Mat22):b2Mat22{ var C:b2Mat22 = new b2Mat22(0, AddVV(A.col1, B.col1), AddVV(A.col2, B.col2)); return (C); } public static function b2Distance(a:b2Vec2, b:b2Vec2):Number{ var cX:Number = (a.x - b.x); var cY:Number = (a.y - b.y); return (Math.sqrt(((cX * cX) + (cY * cY)))); } public static function b2MulTMM(A:b2Mat22, B:b2Mat22):b2Mat22{ var c1:b2Vec2 = new b2Vec2(b2Dot(A.col1, B.col1), b2Dot(A.col2, B.col1)); var c2:b2Vec2 = new b2Vec2(b2Dot(A.col1, B.col2), b2Dot(A.col2, B.col2)); var C:b2Mat22 = new b2Mat22(0, c1, c2); return (C); } public static function b2MaxV(a:b2Vec2, b:b2Vec2):b2Vec2{ var c:b2Vec2 = new b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y)); return (c); } public static function b2IsPowerOfTwo(x:uint):Boolean{ var result:Boolean = (((x > 0)) && (((x & (x - 1)) == 0))); return (result); } public static function b2ClampV(a:b2Vec2, low:b2Vec2, high:b2Vec2):b2Vec2{ return (b2MaxV(low, b2MinV(a, high))); } public static function b2RandomRange(lo:Number, hi:Number):Number{ var r:Number = Math.random(); r = (((hi - lo) * r) + lo); return (r); } public static function b2MulTMV(A:b2Mat22, v:b2Vec2):b2Vec2{ var u:b2Vec2 = new b2Vec2(b2Dot(v, A.col1), b2Dot(v, A.col2)); return (u); } public static function b2Min(a:Number, b:Number):Number{ return (((a < b)) ? a : b); } public static function b2Random():Number{ return (((Math.random() * 2) - 1)); } public static function b2MulMM(A:b2Mat22, B:b2Mat22):b2Mat22{ var C:b2Mat22 = new b2Mat22(0, b2MulMV(A, B.col1), b2MulMV(A, B.col2)); return (C); } public static function b2NextPowerOfTwo(x:uint):uint{ x = (x | ((x >> 1) & 2147483647)); x = (x | ((x >> 2) & 1073741823)); x = (x | ((x >> 4) & 268435455)); x = (x | ((x >> 8) & 0xFFFFFF)); x = (x | ((x >> 16) & 0xFFFF)); return ((x + 1)); } public static function b2Max(a:Number, b:Number):Number{ return (((a > b)) ? a : b); } public static function b2MulMV(A:b2Mat22, v:b2Vec2):b2Vec2{ var u:b2Vec2 = new b2Vec2(((A.col1.x * v.x) + (A.col2.x * v.y)), ((A.col1.y * v.x) + (A.col2.y * v.y))); return (u); } } }//package Box2D.Common.Math
Section 32
//b2Sweep (Box2D.Common.Math.b2Sweep) package Box2D.Common.Math { public class b2Sweep { public var localCenter:b2Vec2; public var a:Number; public var c:b2Vec2; public var a0:Number; public var c0:b2Vec2; public var t0:Number; public function b2Sweep(){ localCenter = new b2Vec2(); c0 = new b2Vec2(); c = new b2Vec2(); super(); } public function Advance(t:Number):void{ var alpha:Number; if ((((t0 < t)) && (((1 - t0) > Number.MIN_VALUE)))){ alpha = ((t - t0) / (1 - t0)); c0.x = (((1 - alpha) * c0.x) + (alpha * c.x)); c0.y = (((1 - alpha) * c0.y) + (alpha * c.y)); a0 = (((1 - alpha) * a0) + (alpha * a)); t0 = t; }; } public function GetXForm(xf:b2XForm, t:Number):void{ var alpha:Number; var angle:Number; if ((1 - t0) > Number.MIN_VALUE){ alpha = ((t - t0) / (1 - t0)); xf.position.x = (((1 - alpha) * c0.x) + (alpha * c.x)); xf.position.y = (((1 - alpha) * c0.y) + (alpha * c.y)); angle = (((1 - alpha) * a0) + (alpha * a)); xf.R.Set(angle); } else { xf.position.SetV(c); xf.R.Set(a); }; var tMat:b2Mat22 = xf.R; xf.position.x = (xf.position.x - ((tMat.col1.x * localCenter.x) + (tMat.col2.x * localCenter.y))); xf.position.y = (xf.position.y - ((tMat.col1.y * localCenter.x) + (tMat.col2.y * localCenter.y))); } } }//package Box2D.Common.Math
Section 33
//b2Vec2 (Box2D.Common.Math.b2Vec2) package Box2D.Common.Math { public class b2Vec2 { public var y:Number; public var x:Number; public function b2Vec2(x_:Number=0, y_:Number=0):void{ super(); x = x_; y = y_; } public function Add(v:b2Vec2):void{ x = (x + v.x); y = (y + v.y); } public function Set(x_:Number=0, y_:Number=0):void{ x = x_; y = y_; } public function Multiply(a:Number):void{ x = (x * a); y = (y * a); } public function Length():Number{ return (Math.sqrt(((x * x) + (y * y)))); } public function LengthSquared():Number{ return (((x * x) + (y * y))); } public function MulM(A:b2Mat22):void{ var tX:Number = x; x = ((A.col1.x * tX) + (A.col2.x * y)); y = ((A.col1.y * tX) + (A.col2.y * y)); } public function SetZero():void{ x = 0; y = 0; } public function MinV(b:b2Vec2):void{ x = ((x < b.x)) ? x : b.x; y = ((y < b.y)) ? y : b.y; } public function Normalize():Number{ var length:Number = Math.sqrt(((x * x) + (y * y))); if (length < Number.MIN_VALUE){ return (0); }; var invLength:Number = (1 / length); x = (x * invLength); y = (y * invLength); return (length); } public function CrossVF(s:Number):void{ var tX:Number = x; x = (s * y); y = (-(s) * tX); } public function MaxV(b:b2Vec2):void{ x = ((x > b.x)) ? x : b.x; y = ((y > b.y)) ? y : b.y; } public function SetV(v:b2Vec2):void{ x = v.x; y = v.y; } public function Negative():b2Vec2{ return (new b2Vec2(-(x), -(y))); } public function CrossFV(s:Number):void{ var tX:Number = x; x = (-(s) * y); y = (s * tX); } public function Abs():void{ if (x < 0){ x = -(x); }; if (y < 0){ y = -(y); }; } public function Subtract(v:b2Vec2):void{ x = (x - v.x); y = (y - v.y); } public function Copy():b2Vec2{ return (new b2Vec2(x, y)); } public function MulTM(A:b2Mat22):void{ var tX:Number = b2Math.b2Dot(this, A.col1); y = b2Math.b2Dot(this, A.col2); x = tX; } public function IsValid():Boolean{ return (((b2Math.b2IsValid(x)) && (b2Math.b2IsValid(y)))); } public static function Make(x_:Number, y_:Number):b2Vec2{ return (new b2Vec2(x_, y_)); } } }//package Box2D.Common.Math
Section 34
//b2XForm (Box2D.Common.Math.b2XForm) package Box2D.Common.Math { public class b2XForm { public var position:b2Vec2; public var R:b2Mat22; public function b2XForm(pos:b2Vec2=null, r:b2Mat22=null):void{ position = new b2Vec2(); R = new b2Mat22(); super(); if (pos){ position.SetV(pos); R.SetM(r); }; } public function Initialize(pos:b2Vec2, r:b2Mat22):void{ position.SetV(pos); R.SetM(r); } public function Set(x:b2XForm):void{ position.SetV(x.position); R.SetM(x.R); } public function SetIdentity():void{ position.SetZero(); R.SetIdentity(); } } }//package Box2D.Common.Math
Section 35
//b2Color (Box2D.Common.b2Color) package Box2D.Common { import Box2D.Common.Math.*; public class b2Color { private var _r:uint;// = 0 private var _g:uint;// = 0 private var _b:uint;// = 0 public function b2Color(rr:Number, gg:Number, bb:Number){ super(); _r = uint((0xFF * b2Math.b2Clamp(rr, 0, 1))); _g = uint((0xFF * b2Math.b2Clamp(gg, 0, 1))); _b = uint((0xFF * b2Math.b2Clamp(bb, 0, 1))); } public function Set(rr:Number, gg:Number, bb:Number):void{ _r = uint((0xFF * b2Math.b2Clamp(rr, 0, 1))); _g = uint((0xFF * b2Math.b2Clamp(gg, 0, 1))); _b = uint((0xFF * b2Math.b2Clamp(bb, 0, 1))); } public function set b(bb:Number):void{ _b = uint((0xFF * b2Math.b2Clamp(bb, 0, 1))); } public function get color():uint{ return (((_r | (_g << 8)) | (_b << 16))); } public function set r(rr:Number):void{ _r = uint((0xFF * b2Math.b2Clamp(rr, 0, 1))); } public function set g(gg:Number):void{ _g = uint((0xFF * b2Math.b2Clamp(gg, 0, 1))); } } }//package Box2D.Common
Section 36
//b2Settings (Box2D.Common.b2Settings) package Box2D.Common { import Box2D.Common.Math.*; public class b2Settings { public static const b2_angularSleepTolerance:Number = 0.0111111111111111; public static const b2_linearSleepTolerance:Number = 0.01; public static const b2_angularSlop:Number = 0.0349065850398866; public static const b2_linearSlop:Number = 0.005; public static const b2_pi:Number = 3.14159265358979; public static const b2_maxProxies:int = 0x0200; public static const b2_maxAngularVelocitySquared:Number = 62500; public static const b2_maxPolygonVertices:int = 8; public static const b2_velocityThreshold:Number = 1; public static const b2_contactBaumgarte:Number = 0.2; public static const b2_maxPairs:int = 4096; public static const b2_maxTOIContactsPerIsland:int = 32; public static const b2_timeToSleep:Number = 0.5; public static const b2_maxManifoldPoints:int = 2; public static const b2_maxAngularVelocity:Number = 250; public static const b2_maxAngularCorrection:Number = 0.139626340159546; public static const USHRT_MAX:int = 0xFFFF; public static const b2_maxLinearVelocity:Number = 200; public static const b2_maxLinearCorrection:Number = 0.2; public static const b2_toiSlop:Number = 0.04; public static const b2_maxLinearVelocitySquared:Number = 40000; public function b2Settings(){ super(); } public static function b2Assert(a:Boolean):void{ var nullVec:b2Vec2; if (!a){ nullVec.x++; }; } } }//package Box2D.Common
Section 37
//b2CircleContact (Box2D.Dynamics.Contacts.b2CircleContact) package Box2D.Dynamics.Contacts { import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.Math.*; import Box2D.Collision.Shapes.*; public class b2CircleContact extends b2Contact { private var m_manifolds:Array; public var m_manifold:b2Manifold; private var m0:b2Manifold; private static const s_evalCP:b2ContactPoint = new b2ContactPoint(); public function b2CircleContact(shape1:b2Shape, shape2:b2Shape){ m_manifolds = [new b2Manifold()]; m0 = new b2Manifold(); super(shape1, shape2); m_manifold = m_manifolds[0]; m_manifold.pointCount = 0; var point:b2ManifoldPoint = m_manifold.points[0]; point.normalImpulse = 0; point.tangentImpulse = 0; } override public function Evaluate(listener:b2ContactListener):void{ var v1:b2Vec2; var v2:b2Vec2; var mp0:b2ManifoldPoint; var mp:b2ManifoldPoint; var b1:b2Body = m_shape1.m_body; var b2:b2Body = m_shape2.m_body; m0.Set(m_manifold); b2Collision.b2CollideCircles(m_manifold, (m_shape1 as b2CircleShape), b1.m_xf, (m_shape2 as b2CircleShape), b2.m_xf); var cp:b2ContactPoint = s_evalCP; cp.shape1 = m_shape1; cp.shape2 = m_shape2; cp.friction = m_friction; cp.restitution = m_restitution; if (m_manifold.pointCount > 0){ m_manifoldCount = 1; mp = m_manifold.points[0]; if (m0.pointCount == 0){ mp.normalImpulse = 0; mp.tangentImpulse = 0; if (listener){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = mp.id._key; listener.Add(cp); }; } else { mp0 = m0.points[0]; mp.normalImpulse = mp0.normalImpulse; mp.tangentImpulse = mp0.tangentImpulse; if (listener){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = mp.id._key; listener.Persist(cp); }; }; } else { m_manifoldCount = 0; if ((((m0.pointCount > 0)) && (listener))){ mp0 = m0.points[0]; cp.position = b1.GetWorldPoint(mp0.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp0.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp0.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m0.normal); cp.separation = mp0.separation; cp.id.key = mp0.id._key; listener.Remove(cp); }; }; } override public function GetManifolds():Array{ return (m_manifolds); } public static function Destroy(contact:b2Contact, allocator):void{ } public static function Create(shape1:b2Shape, shape2:b2Shape, allocator):b2Contact{ return (new b2CircleContact(shape1, shape2)); } } }//package Box2D.Dynamics.Contacts
Section 38
//b2Contact (Box2D.Dynamics.Contacts.b2Contact) package Box2D.Dynamics.Contacts { import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.Math.*; import Box2D.Collision.Shapes.*; import Box2D.Common.*; public class b2Contact { public var m_shape1:b2Shape; public var m_shape2:b2Shape; public var m_prev:b2Contact; public var m_toi:Number; public var m_next:b2Contact; public var m_friction:Number; public var m_manifoldCount:int; public var m_node1:b2ContactEdge; public var m_node2:b2ContactEdge; public var m_restitution:Number; public var m_flags:uint; public static var e_toiFlag:uint = 8; public static var e_nonSolidFlag:uint = 1; public static var e_slowFlag:uint = 2; public static var e_islandFlag:uint = 4; public static var s_registers:Array; public static var s_initialized:Boolean = false; public function b2Contact(s1:b2Shape=null, s2:b2Shape=null){ m_node1 = new b2ContactEdge(); m_node2 = new b2ContactEdge(); super(); m_flags = 0; if (((!(s1)) || (!(s2)))){ m_shape1 = null; m_shape2 = null; return; }; if (((s1.IsSensor()) || (s2.IsSensor()))){ m_flags = (m_flags | e_nonSolidFlag); }; m_shape1 = s1; m_shape2 = s2; m_manifoldCount = 0; m_friction = Math.sqrt((m_shape1.m_friction * m_shape2.m_friction)); m_restitution = b2Math.b2Max(m_shape1.m_restitution, m_shape2.m_restitution); m_prev = null; m_next = null; m_node1.contact = null; m_node1.prev = null; m_node1.next = null; m_node1.other = null; m_node2.contact = null; m_node2.prev = null; m_node2.next = null; m_node2.other = null; } public function IsSolid():Boolean{ return (((m_flags & e_nonSolidFlag) == 0)); } public function GetShape1():b2Shape{ return (m_shape1); } public function GetShape2():b2Shape{ return (m_shape2); } public function GetNext():b2Contact{ return (m_next); } public function GetManifoldCount():int{ return (m_manifoldCount); } public function GetManifolds():Array{ return (null); } public function Update(listener:b2ContactListener):void{ var oldCount:int = m_manifoldCount; Evaluate(listener); var newCount:int = m_manifoldCount; var body1:b2Body = m_shape1.m_body; var body2:b2Body = m_shape2.m_body; if ((((newCount == 0)) && ((oldCount > 0)))){ body1.WakeUp(); body2.WakeUp(); }; if (((((((body1.IsStatic()) || (body1.IsBullet()))) || (body2.IsStatic()))) || (body2.IsBullet()))){ m_flags = (m_flags & ~(e_slowFlag)); } else { m_flags = (m_flags | e_slowFlag); }; } public function Evaluate(listener:b2ContactListener):void{ } public static function InitializeRegisters():void{ var j:int; s_registers = new Array(b2Shape.e_shapeTypeCount); var i:int; while (i < b2Shape.e_shapeTypeCount) { s_registers[i] = new Array(b2Shape.e_shapeTypeCount); j = 0; while (j < b2Shape.e_shapeTypeCount) { s_registers[i][j] = new b2ContactRegister(); j++; }; i++; }; AddType(b2CircleContact.Create, b2CircleContact.Destroy, b2Shape.e_circleShape, b2Shape.e_circleShape); AddType(b2PolyAndCircleContact.Create, b2PolyAndCircleContact.Destroy, b2Shape.e_polygonShape, b2Shape.e_circleShape); AddType(b2PolygonContact.Create, b2PolygonContact.Destroy, b2Shape.e_polygonShape, b2Shape.e_polygonShape); } public static function Destroy(contact:b2Contact, allocator):void{ if (contact.m_manifoldCount > 0){ contact.m_shape1.m_body.WakeUp(); contact.m_shape2.m_body.WakeUp(); }; var type1:int = contact.m_shape1.m_type; var type2:int = contact.m_shape2.m_type; var reg:b2ContactRegister = s_registers[type1][type2]; var destroyFcn:Function = reg.destroyFcn; destroyFcn(contact, allocator); } public static function AddType(createFcn:Function, destroyFcn:Function, type1:int, type2:int):void{ s_registers[type1][type2].createFcn = createFcn; s_registers[type1][type2].destroyFcn = destroyFcn; s_registers[type1][type2].primary = true; if (type1 != type2){ s_registers[type2][type1].createFcn = createFcn; s_registers[type2][type1].destroyFcn = destroyFcn; s_registers[type2][type1].primary = false; }; } public static function Create(shape1:b2Shape, shape2:b2Shape, allocator):b2Contact{ var c:b2Contact; var i:int; var m:b2Manifold; if (s_initialized == false){ InitializeRegisters(); s_initialized = true; }; var type1:int = shape1.m_type; var type2:int = shape2.m_type; var reg:b2ContactRegister = s_registers[type1][type2]; var createFcn:Function = reg.createFcn; if (createFcn != null){ if (reg.primary){ return (createFcn(shape1, shape2, allocator)); }; c = createFcn(shape2, shape1, allocator); i = 0; while (i < c.m_manifoldCount) { m = c.GetManifolds()[i]; m.normal = m.normal.Negative(); i++; }; return (c); //unresolved jump }; return (null); } } }//package Box2D.Dynamics.Contacts
Section 39
//b2ContactConstraint (Box2D.Dynamics.Contacts.b2ContactConstraint) package Box2D.Dynamics.Contacts { import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.Math.*; import Box2D.Common.*; public class b2ContactConstraint { public var points:Array; public var normal:b2Vec2; public var restitution:Number; public var body1:b2Body; public var manifold:b2Manifold; public var body2:b2Body; public var friction:Number; public var pointCount:int; public function b2ContactConstraint(){ normal = new b2Vec2(); super(); points = new Array(b2Settings.b2_maxManifoldPoints); var i:int; while (i < b2Settings.b2_maxManifoldPoints) { points[i] = new b2ContactConstraintPoint(); i++; }; } } }//package Box2D.Dynamics.Contacts
Section 40
//b2ContactConstraintPoint (Box2D.Dynamics.Contacts.b2ContactConstraintPoint) package Box2D.Dynamics.Contacts { import Box2D.Common.Math.*; public class b2ContactConstraintPoint { public var r2:b2Vec2; public var separation:Number; public var positionImpulse:Number; public var normalImpulse:Number; public var tangentMass:Number; public var equalizedMass:Number; public var tangentImpulse:Number; public var localAnchor1:b2Vec2; public var localAnchor2:b2Vec2; public var normalMass:Number; public var velocityBias:Number; public var r1:b2Vec2; public function b2ContactConstraintPoint(){ localAnchor1 = new b2Vec2(); localAnchor2 = new b2Vec2(); r1 = new b2Vec2(); r2 = new b2Vec2(); super(); } } }//package Box2D.Dynamics.Contacts
Section 41
//b2ContactEdge (Box2D.Dynamics.Contacts.b2ContactEdge) package Box2D.Dynamics.Contacts { import Box2D.Dynamics.*; public class b2ContactEdge { public var other:b2Body; public var prev:b2ContactEdge; public var contact:b2Contact; public var next:b2ContactEdge; public function b2ContactEdge(){ super(); } } }//package Box2D.Dynamics.Contacts
Section 42
//b2ContactRegister (Box2D.Dynamics.Contacts.b2ContactRegister) package Box2D.Dynamics.Contacts { public class b2ContactRegister { public var primary:Boolean; public var createFcn:Function; public var destroyFcn:Function; public function b2ContactRegister(){ super(); } } }//package Box2D.Dynamics.Contacts
Section 43
//b2ContactResult (Box2D.Dynamics.Contacts.b2ContactResult) package Box2D.Dynamics.Contacts { import Box2D.Collision.*; import Box2D.Common.Math.*; import Box2D.Collision.Shapes.*; public class b2ContactResult { public var position:b2Vec2; public var shape1:b2Shape; public var shape2:b2Shape; public var normalImpulse:Number; public var normal:b2Vec2; public var tangentImpulse:Number; public var id:b2ContactID; public function b2ContactResult(){ position = new b2Vec2(); normal = new b2Vec2(); id = new b2ContactID(); super(); } } }//package Box2D.Dynamics.Contacts
Section 44
//b2ContactSolver (Box2D.Dynamics.Contacts.b2ContactSolver) package Box2D.Dynamics.Contacts { import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.Math.*; import Box2D.Common.*; public class b2ContactSolver { public var m_constraintCount:int; public var m_constraints:Array; public var m_allocator; public var m_step:b2TimeStep; public function b2ContactSolver(step:b2TimeStep, contacts:Array, contactCount:int, allocator){ var contact:b2Contact; var i:int; var tVec:b2Vec2; var tMat:b2Mat22; var b1:b2Body; var b2:b2Body; var manifoldCount:int; var manifolds:Array; var friction:Number; var restitution:Number; var v1X:Number; var v1Y:Number; var v2X:Number; var v2Y:Number; var w1:Number; var w2:Number; var j:int; var manifold:b2Manifold; var normalX:Number; var normalY:Number; var c:b2ContactConstraint; var k:uint; var cp:b2ManifoldPoint; var ccp:b2ContactConstraintPoint; var tX:Number; var tY:Number; var r1X:Number; var r1Y:Number; var r2X:Number; var r2Y:Number; var r1Sqr:Number; var r2Sqr:Number; var rn1:Number; var rn2:Number; var kNormal:Number; var kEqualized:Number; var tangentX:Number; var tangentY:Number; var rt1:Number; var rt2:Number; var kTangent:Number; var vRel:Number; m_step = new b2TimeStep(); m_constraints = new Array(); super(); m_step.dt = step.dt; m_step.inv_dt = step.inv_dt; m_step.maxIterations = step.maxIterations; m_allocator = allocator; m_constraintCount = 0; i = 0; while (i < contactCount) { contact = contacts[i]; m_constraintCount = (m_constraintCount + contact.m_manifoldCount); i++; }; i = 0; while (i < m_constraintCount) { m_constraints[i] = new b2ContactConstraint(); i++; }; var count:int; i = 0; while (i < contactCount) { contact = contacts[i]; b1 = contact.m_shape1.m_body; b2 = contact.m_shape2.m_body; manifoldCount = contact.m_manifoldCount; manifolds = contact.GetManifolds(); friction = contact.m_friction; restitution = contact.m_restitution; v1X = b1.m_linearVelocity.x; v1Y = b1.m_linearVelocity.y; v2X = b2.m_linearVelocity.x; v2Y = b2.m_linearVelocity.y; w1 = b1.m_angularVelocity; w2 = b2.m_angularVelocity; j = 0; while (j < manifoldCount) { manifold = manifolds[j]; normalX = manifold.normal.x; normalY = manifold.normal.y; c = m_constraints[count]; c.body1 = b1; c.body2 = b2; c.manifold = manifold; c.normal.x = normalX; c.normal.y = normalY; c.pointCount = manifold.pointCount; c.friction = friction; c.restitution = restitution; k = 0; while (k < c.pointCount) { cp = manifold.points[k]; ccp = c.points[k]; ccp.normalImpulse = cp.normalImpulse; ccp.tangentImpulse = cp.tangentImpulse; ccp.separation = cp.separation; ccp.positionImpulse = 0; ccp.localAnchor1.SetV(cp.localPoint1); ccp.localAnchor2.SetV(cp.localPoint2); tMat = b1.m_xf.R; r1X = (cp.localPoint1.x - b1.m_sweep.localCenter.x); r1Y = (cp.localPoint1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; ccp.r1.Set(r1X, r1Y); tMat = b2.m_xf.R; r2X = (cp.localPoint2.x - b2.m_sweep.localCenter.x); r2Y = (cp.localPoint2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; ccp.r2.Set(r2X, r2Y); r1Sqr = ((r1X * r1X) + (r1Y * r1Y)); r2Sqr = ((r2X * r2X) + (r2Y * r2Y)); rn1 = ((r1X * normalX) + (r1Y * normalY)); rn2 = ((r2X * normalX) + (r2Y * normalY)); kNormal = (b1.m_invMass + b2.m_invMass); kNormal = (kNormal + ((b1.m_invI * (r1Sqr - (rn1 * rn1))) + (b2.m_invI * (r2Sqr - (rn2 * rn2))))); ccp.normalMass = (1 / kNormal); kEqualized = ((b1.m_mass * b1.m_invMass) + (b2.m_mass * b2.m_invMass)); kEqualized = (kEqualized + (((b1.m_mass * b1.m_invI) * (r1Sqr - (rn1 * rn1))) + ((b2.m_mass * b2.m_invI) * (r2Sqr - (rn2 * rn2))))); ccp.equalizedMass = (1 / kEqualized); tangentX = normalY; tangentY = -(normalX); rt1 = ((r1X * tangentX) + (r1Y * tangentY)); rt2 = ((r2X * tangentX) + (r2Y * tangentY)); kTangent = (b1.m_invMass + b2.m_invMass); kTangent = (kTangent + ((b1.m_invI * (r1Sqr - (rt1 * rt1))) + (b2.m_invI * (r2Sqr - (rt2 * rt2))))); ccp.tangentMass = (1 / kTangent); ccp.velocityBias = 0; if (ccp.separation > 0){ ccp.velocityBias = (-60 * ccp.separation); }; tX = (((v2X + (-(w2) * r2Y)) - v1X) - (-(w1) * r1Y)); tY = (((v2Y + (w2 * r2X)) - v1Y) - (w1 * r1X)); vRel = ((c.normal.x * tX) + (c.normal.y * tY)); if (vRel < -(b2Settings.b2_velocityThreshold)){ ccp.velocityBias = (ccp.velocityBias + (-(c.restitution) * vRel)); }; k++; }; count++; j++; }; i++; }; } public function InitVelocityConstraints(step:b2TimeStep):void{ var tVec:b2Vec2; var tVec2:b2Vec2; var tMat:b2Mat22; var c:b2ContactConstraint; var b1:b2Body; var b2:b2Body; var invMass1:Number; var invI1:Number; var invMass2:Number; var invI2:Number; var normalX:Number; var normalY:Number; var tangentX:Number; var tangentY:Number; var tX:Number; var j:int; var tCount:int; var ccp:b2ContactConstraintPoint; var PX:Number; var PY:Number; var ccp2:b2ContactConstraintPoint; var i:int; while (i < m_constraintCount) { c = m_constraints[i]; b1 = c.body1; b2 = c.body2; invMass1 = b1.m_invMass; invI1 = b1.m_invI; invMass2 = b2.m_invMass; invI2 = b2.m_invI; normalX = c.normal.x; normalY = c.normal.y; tangentX = normalY; tangentY = -(normalX); if (step.warmStarting){ tCount = c.pointCount; j = 0; while (j < tCount) { ccp = c.points[j]; ccp.normalImpulse = (ccp.normalImpulse * step.dtRatio); ccp.tangentImpulse = (ccp.tangentImpulse * step.dtRatio); PX = ((ccp.normalImpulse * normalX) + (ccp.tangentImpulse * tangentX)); PY = ((ccp.normalImpulse * normalY) + (ccp.tangentImpulse * tangentY)); b1.m_angularVelocity = (b1.m_angularVelocity - (invI1 * ((ccp.r1.x * PY) - (ccp.r1.y * PX)))); b1.m_linearVelocity.x = (b1.m_linearVelocity.x - (invMass1 * PX)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y - (invMass1 * PY)); b2.m_angularVelocity = (b2.m_angularVelocity + (invI2 * ((ccp.r2.x * PY) - (ccp.r2.y * PX)))); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (invMass2 * PX)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (invMass2 * PY)); j++; }; } else { tCount = c.pointCount; j = 0; while (j < tCount) { ccp2 = c.points[j]; ccp2.normalImpulse = 0; ccp2.tangentImpulse = 0; j++; }; }; i++; }; } public function SolvePositionConstraints(baumgarte:Number):Boolean{ var tMat:b2Mat22; var tVec:b2Vec2; var c:b2ContactConstraint; var b1:b2Body; var b2:b2Body; var b1_sweep_c:b2Vec2; var b1_sweep_a:Number; var b2_sweep_c:b2Vec2; var b2_sweep_a:Number; var invMass1:Number; var invI1:Number; var invMass2:Number; var invI2:Number; var normalX:Number; var normalY:Number; var tCount:int; var j:int; var ccp:b2ContactConstraintPoint; var r1X:Number; var r1Y:Number; var r2X:Number; var r2Y:Number; var tX:Number; var p1X:Number; var p1Y:Number; var p2X:Number; var p2Y:Number; var dpX:Number; var dpY:Number; var separation:Number; var C:Number; var dImpulse:Number; var impulse0:Number; var impulseX:Number; var impulseY:Number; var minSeparation:Number = 0; var i:int; while (i < m_constraintCount) { c = m_constraints[i]; b1 = c.body1; b2 = c.body2; b1_sweep_c = b1.m_sweep.c; b1_sweep_a = b1.m_sweep.a; b2_sweep_c = b2.m_sweep.c; b2_sweep_a = b2.m_sweep.a; invMass1 = (b1.m_mass * b1.m_invMass); invI1 = (b1.m_mass * b1.m_invI); invMass2 = (b2.m_mass * b2.m_invMass); invI2 = (b2.m_mass * b2.m_invI); normalX = c.normal.x; normalY = c.normal.y; tCount = c.pointCount; j = 0; while (j < tCount) { ccp = c.points[j]; tMat = b1.m_xf.R; tVec = b1.m_sweep.localCenter; r1X = (ccp.localAnchor1.x - tVec.x); r1Y = (ccp.localAnchor1.y - tVec.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; tVec = b2.m_sweep.localCenter; r2X = (ccp.localAnchor2.x - tVec.x); r2Y = (ccp.localAnchor2.y - tVec.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; p1X = (b1_sweep_c.x + r1X); p1Y = (b1_sweep_c.y + r1Y); p2X = (b2_sweep_c.x + r2X); p2Y = (b2_sweep_c.y + r2Y); dpX = (p2X - p1X); dpY = (p2Y - p1Y); separation = (((dpX * normalX) + (dpY * normalY)) + ccp.separation); minSeparation = b2Math.b2Min(minSeparation, separation); C = (baumgarte * b2Math.b2Clamp((separation + b2Settings.b2_linearSlop), -(b2Settings.b2_maxLinearCorrection), 0)); dImpulse = (-(ccp.equalizedMass) * C); impulse0 = ccp.positionImpulse; ccp.positionImpulse = b2Math.b2Max((impulse0 + dImpulse), 0); dImpulse = (ccp.positionImpulse - impulse0); impulseX = (dImpulse * normalX); impulseY = (dImpulse * normalY); b1_sweep_c.x = (b1_sweep_c.x - (invMass1 * impulseX)); b1_sweep_c.y = (b1_sweep_c.y - (invMass1 * impulseY)); b1_sweep_a = (b1_sweep_a - (invI1 * ((r1X * impulseY) - (r1Y * impulseX)))); b1.m_sweep.a = b1_sweep_a; b1.SynchronizeTransform(); b2_sweep_c.x = (b2_sweep_c.x + (invMass2 * impulseX)); b2_sweep_c.y = (b2_sweep_c.y + (invMass2 * impulseY)); b2_sweep_a = (b2_sweep_a + (invI2 * ((r2X * impulseY) - (r2Y * impulseX)))); b2.m_sweep.a = b2_sweep_a; b2.SynchronizeTransform(); j++; }; i++; }; return ((minSeparation >= (-1.5 * b2Settings.b2_linearSlop))); } public function SolveVelocityConstraints():void{ var j:int; var ccp:b2ContactConstraintPoint; var r1X:Number; var r1Y:Number; var r2X:Number; var r2Y:Number; var dvX:Number; var dvY:Number; var vn:Number; var vt:Number; var lambda_n:Number; var lambda_t:Number; var newImpulse_n:Number; var newImpulse_t:Number; var PX:Number; var PY:Number; var tMat:b2Mat22; var tVec:b2Vec2; var c:b2ContactConstraint; var b1:b2Body; var b2:b2Body; var w1:Number; var w2:Number; var v1:b2Vec2; var v2:b2Vec2; var invMass1:Number; var invI1:Number; var invMass2:Number; var invI2:Number; var normalX:Number; var normalY:Number; var tangentX:Number; var tangentY:Number; var friction:Number; var tX:Number; var tCount:int; var maxFriction:Number; var i:int; while (i < m_constraintCount) { c = m_constraints[i]; b1 = c.body1; b2 = c.body2; w1 = b1.m_angularVelocity; w2 = b2.m_angularVelocity; v1 = b1.m_linearVelocity; v2 = b2.m_linearVelocity; invMass1 = b1.m_invMass; invI1 = b1.m_invI; invMass2 = b2.m_invMass; invI2 = b2.m_invI; normalX = c.normal.x; normalY = c.normal.y; tangentX = normalY; tangentY = -(normalX); friction = c.friction; tCount = c.pointCount; j = 0; while (j < tCount) { ccp = c.points[j]; dvX = (((v2.x + (-(w2) * ccp.r2.y)) - v1.x) - (-(w1) * ccp.r1.y)); dvY = (((v2.y + (w2 * ccp.r2.x)) - v1.y) - (w1 * ccp.r1.x)); vn = ((dvX * normalX) + (dvY * normalY)); lambda_n = (-(ccp.normalMass) * (vn - ccp.velocityBias)); vt = ((dvX * tangentX) + (dvY * tangentY)); lambda_t = (ccp.tangentMass * -(vt)); newImpulse_n = b2Math.b2Max((ccp.normalImpulse + lambda_n), 0); lambda_n = (newImpulse_n - ccp.normalImpulse); maxFriction = (friction * ccp.normalImpulse); newImpulse_t = b2Math.b2Clamp((ccp.tangentImpulse + lambda_t), -(maxFriction), maxFriction); lambda_t = (newImpulse_t - ccp.tangentImpulse); PX = ((lambda_n * normalX) + (lambda_t * tangentX)); PY = ((lambda_n * normalY) + (lambda_t * tangentY)); v1.x = (v1.x - (invMass1 * PX)); v1.y = (v1.y - (invMass1 * PY)); w1 = (w1 - (invI1 * ((ccp.r1.x * PY) - (ccp.r1.y * PX)))); v2.x = (v2.x + (invMass2 * PX)); v2.y = (v2.y + (invMass2 * PY)); w2 = (w2 + (invI2 * ((ccp.r2.x * PY) - (ccp.r2.y * PX)))); ccp.normalImpulse = newImpulse_n; ccp.tangentImpulse = newImpulse_t; j++; }; b1.m_angularVelocity = w1; b2.m_angularVelocity = w2; i++; }; } public function FinalizeVelocityConstraints():void{ var c:b2ContactConstraint; var m:b2Manifold; var j:int; var point1:b2ManifoldPoint; var point2:b2ContactConstraintPoint; var i:int; while (i < m_constraintCount) { c = m_constraints[i]; m = c.manifold; j = 0; while (j < c.pointCount) { point1 = m.points[j]; point2 = c.points[j]; point1.normalImpulse = point2.normalImpulse; point1.tangentImpulse = point2.tangentImpulse; j++; }; i++; }; } } }//package Box2D.Dynamics.Contacts
Section 45
//b2NullContact (Box2D.Dynamics.Contacts.b2NullContact) package Box2D.Dynamics.Contacts { import Box2D.Dynamics.*; public class b2NullContact extends b2Contact { public function b2NullContact(){ super(); } override public function Evaluate(l:b2ContactListener):void{ } override public function GetManifolds():Array{ return (null); } } }//package Box2D.Dynamics.Contacts
Section 46
//b2PolyAndCircleContact (Box2D.Dynamics.Contacts.b2PolyAndCircleContact) package Box2D.Dynamics.Contacts { import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.Math.*; import Box2D.Collision.Shapes.*; import Box2D.Common.*; public class b2PolyAndCircleContact extends b2Contact { private var m_manifolds:Array; public var m_manifold:b2Manifold; private var m0:b2Manifold; private static const s_evalCP:b2ContactPoint = new b2ContactPoint(); public function b2PolyAndCircleContact(shape1:b2Shape, shape2:b2Shape){ m_manifolds = [new b2Manifold()]; m0 = new b2Manifold(); super(shape1, shape2); m_manifold = m_manifolds[0]; b2Settings.b2Assert((m_shape1.m_type == b2Shape.e_polygonShape)); b2Settings.b2Assert((m_shape2.m_type == b2Shape.e_circleShape)); m_manifold.pointCount = 0; var point:b2ManifoldPoint = m_manifold.points[0]; point.normalImpulse = 0; point.tangentImpulse = 0; } override public function Evaluate(listener:b2ContactListener):void{ var i:int; var v1:b2Vec2; var v2:b2Vec2; var mp0:b2ManifoldPoint; var mp:b2ManifoldPoint; var found:Boolean; var idKey:uint; var j:int; var b1:b2Body = m_shape1.m_body; var b2:b2Body = m_shape2.m_body; m0.Set(m_manifold); b2Collision.b2CollidePolygonAndCircle(m_manifold, (m_shape1 as b2PolygonShape), b1.m_xf, (m_shape2 as b2CircleShape), b2.m_xf); var persisted:Array = [false, false]; var cp:b2ContactPoint = s_evalCP; cp.shape1 = m_shape1; cp.shape2 = m_shape2; cp.friction = m_friction; cp.restitution = m_restitution; if (m_manifold.pointCount > 0){ i = 0; while (i < m_manifold.pointCount) { mp = m_manifold.points[i]; mp.normalImpulse = 0; mp.tangentImpulse = 0; found = false; idKey = mp.id._key; j = 0; while (j < m0.pointCount) { if (persisted[j] == true){ } else { mp0 = m0.points[j]; if (mp0.id._key == idKey){ persisted[j] = true; mp.normalImpulse = mp0.normalImpulse; mp.tangentImpulse = mp0.tangentImpulse; found = true; if (listener != null){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = idKey; listener.Persist(cp); }; break; }; }; j++; }; if ((((found == false)) && (!((listener == null))))){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = idKey; listener.Add(cp); }; i++; }; m_manifoldCount = 1; } else { m_manifoldCount = 0; }; if (listener == null){ return; }; i = 0; while (i < m0.pointCount) { if (persisted[i]){ } else { mp0 = m0.points[i]; cp.position = b1.GetWorldPoint(mp0.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp0.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp0.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m0.normal); cp.separation = mp0.separation; cp.id.key = mp0.id._key; listener.Remove(cp); }; i++; }; } override public function GetManifolds():Array{ return (m_manifolds); } public static function Destroy(contact:b2Contact, allocator):void{ } public static function Create(shape1:b2Shape, shape2:b2Shape, allocator):b2Contact{ return (new b2PolyAndCircleContact(shape1, shape2)); } } }//package Box2D.Dynamics.Contacts
Section 47
//b2PolygonContact (Box2D.Dynamics.Contacts.b2PolygonContact) package Box2D.Dynamics.Contacts { import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.Math.*; import Box2D.Collision.Shapes.*; public class b2PolygonContact extends b2Contact { private var m_manifolds:Array; private var m0:b2Manifold; public var m_manifold:b2Manifold; private static const s_evalCP:b2ContactPoint = new b2ContactPoint(); public function b2PolygonContact(shape1:b2Shape, shape2:b2Shape):void{ m0 = new b2Manifold(); m_manifolds = [new b2Manifold()]; super(shape1, shape2); m_manifold = m_manifolds[0]; m_manifold.pointCount = 0; } override public function Evaluate(listener:b2ContactListener):void{ var v1:b2Vec2; var v2:b2Vec2; var mp0:b2ManifoldPoint; var cp:b2ContactPoint; var i:int; var mp:b2ManifoldPoint; var found:Boolean; var idKey:uint; var j:int; var b1:b2Body = m_shape1.m_body; var b2:b2Body = m_shape2.m_body; m0.Set(m_manifold); b2Collision.b2CollidePolygons(m_manifold, (m_shape1 as b2PolygonShape), b1.m_xf, (m_shape2 as b2PolygonShape), b2.m_xf); var persisted:Array = [false, false]; cp = s_evalCP; cp.shape1 = m_shape1; cp.shape2 = m_shape2; cp.friction = m_friction; cp.restitution = m_restitution; if (m_manifold.pointCount > 0){ i = 0; while (i < m_manifold.pointCount) { mp = m_manifold.points[i]; mp.normalImpulse = 0; mp.tangentImpulse = 0; found = false; idKey = mp.id._key; j = 0; while (j < m0.pointCount) { if (persisted[j] == true){ } else { mp0 = m0.points[j]; if (mp0.id._key == idKey){ persisted[j] = true; mp.normalImpulse = mp0.normalImpulse; mp.tangentImpulse = mp0.tangentImpulse; found = true; if (listener != null){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = idKey; listener.Persist(cp); }; break; }; }; j++; }; if ((((found == false)) && (!((listener == null))))){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = idKey; listener.Add(cp); }; i++; }; m_manifoldCount = 1; } else { m_manifoldCount = 0; }; if (listener == null){ return; }; i = 0; while (i < m0.pointCount) { if (persisted[i]){ } else { mp0 = m0.points[i]; cp.position = b1.GetWorldPoint(mp0.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp0.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp0.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m0.normal); cp.separation = mp0.separation; cp.id.key = mp0.id._key; listener.Remove(cp); }; i++; }; } override public function GetManifolds():Array{ return (m_manifolds); } public static function Destroy(contact:b2Contact, allocator):void{ } public static function Create(shape1:b2Shape, shape2:b2Shape, allocator):b2Contact{ return (new b2PolygonContact(shape1, shape2)); } } }//package Box2D.Dynamics.Contacts
Section 48
//b2DistanceJoint (Box2D.Dynamics.Joints.b2DistanceJoint) package Box2D.Dynamics.Joints { import Box2D.Dynamics.*; import Box2D.Common.Math.*; import Box2D.Common.*; public class b2DistanceJoint extends b2Joint { public var m_localAnchor1:b2Vec2; public var m_localAnchor2:b2Vec2; public var m_bias:Number; public var m_gamma:Number; public var m_u:b2Vec2; public var m_mass:Number; public var m_impulse:Number; public var m_dampingRatio:Number; public var m_frequencyHz:Number; public var m_length:Number; public function b2DistanceJoint(def:b2DistanceJointDef){ var tMat:b2Mat22; var tX:Number; var tY:Number; m_localAnchor1 = new b2Vec2(); m_localAnchor2 = new b2Vec2(); m_u = new b2Vec2(); super(def); m_localAnchor1.SetV(def.localAnchor1); m_localAnchor2.SetV(def.localAnchor2); m_length = def.length; m_frequencyHz = def.frequencyHz; m_dampingRatio = def.dampingRatio; m_impulse = 0; m_gamma = 0; m_bias = 0; m_inv_dt = 0; } override public function GetAnchor1():b2Vec2{ return (m_body1.GetWorldPoint(m_localAnchor1)); } override public function GetAnchor2():b2Vec2{ return (m_body2.GetWorldPoint(m_localAnchor2)); } override public function InitVelocityConstraints(step:b2TimeStep):void{ var tMat:b2Mat22; var tX:Number; var b1:b2Body; var b2:b2Body; var r1X:Number; var r2X:Number; var C:Number; var omega:Number; var d:Number; var k:Number; var PX:Number; var PY:Number; m_inv_dt = step.inv_dt; b1 = m_body1; b2 = m_body2; tMat = b1.m_xf.R; r1X = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; r2X = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; m_u.x = (((b2.m_sweep.c.x + r2X) - b1.m_sweep.c.x) - r1X); m_u.y = (((b2.m_sweep.c.y + r2Y) - b1.m_sweep.c.y) - r1Y); var length:Number = Math.sqrt(((m_u.x * m_u.x) + (m_u.y * m_u.y))); if (length > b2Settings.b2_linearSlop){ m_u.Multiply((1 / length)); } else { m_u.SetZero(); }; var cr1u:Number = ((r1X * m_u.y) - (r1Y * m_u.x)); var cr2u:Number = ((r2X * m_u.y) - (r2Y * m_u.x)); var invMass:Number = (((b1.m_invMass + ((b1.m_invI * cr1u) * cr1u)) + b2.m_invMass) + ((b2.m_invI * cr2u) * cr2u)); m_mass = (1 / invMass); if (m_frequencyHz > 0){ C = (length - m_length); omega = ((2 * Math.PI) * m_frequencyHz); d = (((2 * m_mass) * m_dampingRatio) * omega); k = ((m_mass * omega) * omega); m_gamma = (1 / (step.dt * (d + (step.dt * k)))); m_bias = (((C * step.dt) * k) * m_gamma); m_mass = (1 / (invMass + m_gamma)); }; if (step.warmStarting){ m_impulse = (m_impulse * step.dtRatio); PX = (m_impulse * m_u.x); PY = (m_impulse * m_u.y); b1.m_linearVelocity.x = (b1.m_linearVelocity.x - (b1.m_invMass * PX)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y - (b1.m_invMass * PY)); b1.m_angularVelocity = (b1.m_angularVelocity - (b1.m_invI * ((r1X * PY) - (r1Y * PX)))); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (b2.m_invMass * PX)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (b2.m_invMass * PY)); b2.m_angularVelocity = (b2.m_angularVelocity + (b2.m_invI * ((r2X * PY) - (r2Y * PX)))); } else { m_impulse = 0; }; } override public function GetReactionTorque():Number{ return (0); } override public function GetReactionForce():b2Vec2{ var F:b2Vec2 = new b2Vec2(); F.SetV(m_u); F.Multiply((m_inv_dt * m_impulse)); return (F); } override public function SolvePositionConstraints():Boolean{ var tMat:b2Mat22; if (m_frequencyHz > 0){ return (true); }; var b1:b2Body = m_body1; var b2:b2Body = m_body2; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var dX:Number = (((b2.m_sweep.c.x + r2X) - b1.m_sweep.c.x) - r1X); var dY:Number = (((b2.m_sweep.c.y + r2Y) - b1.m_sweep.c.y) - r1Y); var length:Number = Math.sqrt(((dX * dX) + (dY * dY))); dX = (dX / length); dY = (dY / length); var C:Number = (length - m_length); C = b2Math.b2Clamp(C, -(b2Settings.b2_maxLinearCorrection), b2Settings.b2_maxLinearCorrection); var impulse:Number = (-(m_mass) * C); m_u.Set(dX, dY); var PX:Number = (impulse * m_u.x); var PY:Number = (impulse * m_u.y); b1.m_sweep.c.x = (b1.m_sweep.c.x - (b1.m_invMass * PX)); b1.m_sweep.c.y = (b1.m_sweep.c.y - (b1.m_invMass * PY)); b1.m_sweep.a = (b1.m_sweep.a - (b1.m_invI * ((r1X * PY) - (r1Y * PX)))); b2.m_sweep.c.x = (b2.m_sweep.c.x + (b2.m_invMass * PX)); b2.m_sweep.c.y = (b2.m_sweep.c.y + (b2.m_invMass * PY)); b2.m_sweep.a = (b2.m_sweep.a + (b2.m_invI * ((r2X * PY) - (r2Y * PX)))); b1.SynchronizeTransform(); b2.SynchronizeTransform(); return ((b2Math.b2Abs(C) < b2Settings.b2_linearSlop)); } override public function SolveVelocityConstraints(step:b2TimeStep):void{ var tMat:b2Mat22; var b1:b2Body = m_body1; var b2:b2Body = m_body2; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var v1X:Number = (b1.m_linearVelocity.x + (-(b1.m_angularVelocity) * r1Y)); var v1Y:Number = (b1.m_linearVelocity.y + (b1.m_angularVelocity * r1X)); var v2X:Number = (b2.m_linearVelocity.x + (-(b2.m_angularVelocity) * r2Y)); var v2Y:Number = (b2.m_linearVelocity.y + (b2.m_angularVelocity * r2X)); var Cdot:Number = ((m_u.x * (v2X - v1X)) + (m_u.y * (v2Y - v1Y))); var impulse:Number = (-(m_mass) * ((Cdot + m_bias) + (m_gamma * m_impulse))); m_impulse = (m_impulse + impulse); var PX:Number = (impulse * m_u.x); var PY:Number = (impulse * m_u.y); b1.m_linearVelocity.x = (b1.m_linearVelocity.x - (b1.m_invMass * PX)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y - (b1.m_invMass * PY)); b1.m_angularVelocity = (b1.m_angularVelocity - (b1.m_invI * ((r1X * PY) - (r1Y * PX)))); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (b2.m_invMass * PX)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (b2.m_invMass * PY)); b2.m_angularVelocity = (b2.m_angularVelocity + (b2.m_invI * ((r2X * PY) - (r2Y * PX)))); } } }//package Box2D.Dynamics.Joints
Section 49
//b2DistanceJointDef (Box2D.Dynamics.Joints.b2DistanceJointDef) package Box2D.Dynamics.Joints { import Box2D.Dynamics.*; import Box2D.Common.Math.*; public class b2DistanceJointDef extends b2JointDef { public var localAnchor1:b2Vec2; public var length:Number; public var dampingRatio:Number; public var localAnchor2:b2Vec2; public var frequencyHz:Number; public function b2DistanceJointDef(){ localAnchor1 = new b2Vec2(); localAnchor2 = new b2Vec2(); super(); type = b2Joint.e_distanceJoint; length = 1; frequencyHz = 0; dampingRatio = 0; } public function Initialize(b1:b2Body, b2:b2Body, anchor1:b2Vec2, anchor2:b2Vec2):void{ body1 = b1; body2 = b2; localAnchor1.SetV(body1.GetLocalPoint(anchor1)); localAnchor2.SetV(body2.GetLocalPoint(anchor2)); var dX:Number = (anchor2.x - anchor1.x); var dY:Number = (anchor2.y - anchor1.y); length = Math.sqrt(((dX * dX) + (dY * dY))); frequencyHz = 0; dampingRatio = 0; } } }//package Box2D.Dynamics.Joints
Section 50
//b2GearJoint (Box2D.Dynamics.Joints.b2GearJoint) package Box2D.Dynamics.Joints { import Box2D.Dynamics.*; import Box2D.Common.Math.*; import Box2D.Common.*; public class b2GearJoint extends b2Joint { public var m_ground2:b2Body; public var m_groundAnchor1:b2Vec2; public var m_groundAnchor2:b2Vec2; public var m_localAnchor1:b2Vec2; public var m_localAnchor2:b2Vec2; public var m_ratio:Number; public var m_revolute2:b2RevoluteJoint; public var m_force:Number; public var m_mass:Number; public var m_prismatic2:b2PrismaticJoint; public var m_ground1:b2Body; public var m_revolute1:b2RevoluteJoint; public var m_prismatic1:b2PrismaticJoint; public var m_constant:Number; public var m_J:b2Jacobian; public function b2GearJoint(def:b2GearJointDef){ var coordinate1:Number; var coordinate2:Number; m_groundAnchor1 = new b2Vec2(); m_groundAnchor2 = new b2Vec2(); m_localAnchor1 = new b2Vec2(); m_localAnchor2 = new b2Vec2(); m_J = new b2Jacobian(); super(def); var type1:int = def.joint1.m_type; var type2:int = def.joint2.m_type; m_revolute1 = null; m_prismatic1 = null; m_revolute2 = null; m_prismatic2 = null; m_ground1 = def.joint1.m_body1; m_body1 = def.joint1.m_body2; if (type1 == b2Joint.e_revoluteJoint){ m_revolute1 = (def.joint1 as b2RevoluteJoint); m_groundAnchor1.SetV(m_revolute1.m_localAnchor1); m_localAnchor1.SetV(m_revolute1.m_localAnchor2); coordinate1 = m_revolute1.GetJointAngle(); } else { m_prismatic1 = (def.joint1 as b2PrismaticJoint); m_groundAnchor1.SetV(m_prismatic1.m_localAnchor1); m_localAnchor1.SetV(m_prismatic1.m_localAnchor2); coordinate1 = m_prismatic1.GetJointTranslation(); }; m_ground2 = def.joint2.m_body1; m_body2 = def.joint2.m_body2; if (type2 == b2Joint.e_revoluteJoint){ m_revolute2 = (def.joint2 as b2RevoluteJoint); m_groundAnchor2.SetV(m_revolute2.m_localAnchor1); m_localAnchor2.SetV(m_revolute2.m_localAnchor2); coordinate2 = m_revolute2.GetJointAngle(); } else { m_prismatic2 = (def.joint2 as b2PrismaticJoint); m_groundAnchor2.SetV(m_prismatic2.m_localAnchor1); m_localAnchor2.SetV(m_prismatic2.m_localAnchor2); coordinate2 = m_prismatic2.GetJointTranslation(); }; m_ratio = def.ratio; m_constant = (coordinate1 + (m_ratio * coordinate2)); m_force = 0; } override public function GetAnchor1():b2Vec2{ return (m_body1.GetWorldPoint(m_localAnchor1)); } override public function GetAnchor2():b2Vec2{ return (m_body2.GetWorldPoint(m_localAnchor2)); } override public function InitVelocityConstraints(step:b2TimeStep):void{ var ugX:Number; var ugY:Number; var rX:Number; var rY:Number; var tMat:b2Mat22; var tVec:b2Vec2; var crug:Number; var tX:Number; var P:Number; var g1:b2Body = m_ground1; var g2:b2Body = m_ground2; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var K:Number = 0; m_J.SetZero(); if (m_revolute1){ m_J.angular1 = -1; K = (K + b1.m_invI); } else { tMat = g1.m_xf.R; tVec = m_prismatic1.m_localXAxis1; ugX = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); ugY = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); tMat = b1.m_xf.R; rX = (m_localAnchor1.x - b1.m_sweep.localCenter.x); rY = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * rX) + (tMat.col2.x * rY)); rY = ((tMat.col1.y * rX) + (tMat.col2.y * rY)); rX = tX; crug = ((rX * ugY) - (rY * ugX)); m_J.linear1.Set(-(ugX), -(ugY)); m_J.angular1 = -(crug); K = (K + (b1.m_invMass + ((b1.m_invI * crug) * crug))); }; if (m_revolute2){ m_J.angular2 = -(m_ratio); K = (K + ((m_ratio * m_ratio) * b2.m_invI)); } else { tMat = g2.m_xf.R; tVec = m_prismatic2.m_localXAxis1; ugX = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); ugY = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); tMat = b2.m_xf.R; rX = (m_localAnchor2.x - b2.m_sweep.localCenter.x); rY = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * rX) + (tMat.col2.x * rY)); rY = ((tMat.col1.y * rX) + (tMat.col2.y * rY)); rX = tX; crug = ((rX * ugY) - (rY * ugX)); m_J.linear2.Set((-(m_ratio) * ugX), (-(m_ratio) * ugY)); m_J.angular2 = (-(m_ratio) * crug); K = (K + ((m_ratio * m_ratio) * (b2.m_invMass + ((b2.m_invI * crug) * crug)))); }; m_mass = (1 / K); if (step.warmStarting){ P = (step.dt * m_force); b1.m_linearVelocity.x = (b1.m_linearVelocity.x + ((b1.m_invMass * P) * m_J.linear1.x)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y + ((b1.m_invMass * P) * m_J.linear1.y)); b1.m_angularVelocity = (b1.m_angularVelocity + ((b1.m_invI * P) * m_J.angular1)); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + ((b2.m_invMass * P) * m_J.linear2.x)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + ((b2.m_invMass * P) * m_J.linear2.y)); b2.m_angularVelocity = (b2.m_angularVelocity + ((b2.m_invI * P) * m_J.angular2)); } else { m_force = 0; }; } override public function GetReactionTorque():Number{ var tMat:b2Mat22 = m_body2.m_xf.R; var rX:Number = (m_localAnchor1.x - m_body2.m_sweep.localCenter.x); var rY:Number = (m_localAnchor1.y - m_body2.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * rX) + (tMat.col2.x * rY)); rY = ((tMat.col1.y * rX) + (tMat.col2.y * rY)); rX = tX; tX = ((m_force * m_J.angular2) - ((rX * (m_force * m_J.linear2.y)) - (rY * (m_force * m_J.linear2.x)))); return (tX); } override public function GetReactionForce():b2Vec2{ var F:b2Vec2 = new b2Vec2((m_force * m_J.linear2.x), (m_force * m_J.linear2.y)); return (F); } override public function SolvePositionConstraints():Boolean{ var coordinate1:Number; var coordinate2:Number; var linearError:Number = 0; var b1:b2Body = m_body1; var b2:b2Body = m_body2; if (m_revolute1){ coordinate1 = m_revolute1.GetJointAngle(); } else { coordinate1 = m_prismatic1.GetJointTranslation(); }; if (m_revolute2){ coordinate2 = m_revolute2.GetJointAngle(); } else { coordinate2 = m_prismatic2.GetJointTranslation(); }; var C:Number = (m_constant - (coordinate1 + (m_ratio * coordinate2))); var impulse:Number = (-(m_mass) * C); b1.m_sweep.c.x = (b1.m_sweep.c.x + ((b1.m_invMass * impulse) * m_J.linear1.x)); b1.m_sweep.c.y = (b1.m_sweep.c.y + ((b1.m_invMass * impulse) * m_J.linear1.y)); b1.m_sweep.a = (b1.m_sweep.a + ((b1.m_invI * impulse) * m_J.angular1)); b2.m_sweep.c.x = (b2.m_sweep.c.x + ((b2.m_invMass * impulse) * m_J.linear2.x)); b2.m_sweep.c.y = (b2.m_sweep.c.y + ((b2.m_invMass * impulse) * m_J.linear2.y)); b2.m_sweep.a = (b2.m_sweep.a + ((b2.m_invI * impulse) * m_J.angular2)); b1.SynchronizeTransform(); b2.SynchronizeTransform(); return ((linearError < b2Settings.b2_linearSlop)); } public function GetRatio():Number{ return (m_ratio); } override public function SolveVelocityConstraints(step:b2TimeStep):void{ var b1:b2Body = m_body1; var b2:b2Body = m_body2; var Cdot:Number = m_J.Compute(b1.m_linearVelocity, b1.m_angularVelocity, b2.m_linearVelocity, b2.m_angularVelocity); var force:Number = ((-(step.inv_dt) * m_mass) * Cdot); m_force = (m_force + force); var P:Number = (step.dt * force); b1.m_linearVelocity.x = (b1.m_linearVelocity.x + ((b1.m_invMass * P) * m_J.linear1.x)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y + ((b1.m_invMass * P) * m_J.linear1.y)); b1.m_angularVelocity = (b1.m_angularVelocity + ((b1.m_invI * P) * m_J.angular1)); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + ((b2.m_invMass * P) * m_J.linear2.x)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + ((b2.m_invMass * P) * m_J.linear2.y)); b2.m_angularVelocity = (b2.m_angularVelocity + ((b2.m_invI * P) * m_J.angular2)); } } }//package Box2D.Dynamics.Joints
Section 51
//b2GearJointDef (Box2D.Dynamics.Joints.b2GearJointDef) package Box2D.Dynamics.Joints { public class b2GearJointDef extends b2JointDef { public var joint1:b2Joint; public var joint2:b2Joint; public var ratio:Number; public function b2GearJointDef(){ super(); type = b2Joint.e_gearJoint; joint1 = null; joint2 = null; ratio = 1; } } }//package Box2D.Dynamics.Joints
Section 52
//b2Jacobian (Box2D.Dynamics.Joints.b2Jacobian) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; public class b2Jacobian { public var linear1:b2Vec2; public var linear2:b2Vec2; public var angular1:Number; public var angular2:Number; public function b2Jacobian(){ linear1 = new b2Vec2(); linear2 = new b2Vec2(); super(); } public function Set(x1:b2Vec2, a1:Number, x2:b2Vec2, a2:Number):void{ linear1.SetV(x1); angular1 = a1; linear2.SetV(x2); angular2 = a2; } public function SetZero():void{ linear1.SetZero(); angular1 = 0; linear2.SetZero(); angular2 = 0; } public function Compute(x1:b2Vec2, a1:Number, x2:b2Vec2, a2:Number):Number{ return ((((((linear1.x * x1.x) + (linear1.y * x1.y)) + (angular1 * a1)) + ((linear2.x * x2.x) + (linear2.y * x2.y))) + (angular2 * a2))); } } }//package Box2D.Dynamics.Joints
Section 53
//b2Joint (Box2D.Dynamics.Joints.b2Joint) package Box2D.Dynamics.Joints { import Box2D.Dynamics.*; import Box2D.Common.Math.*; public class b2Joint { public var m_islandFlag:Boolean; public var m_body1:b2Body; public var m_prev:b2Joint; public var m_next:b2Joint; public var m_type:int; public var m_collideConnected:Boolean; public var m_node1:b2JointEdge; public var m_node2:b2JointEdge; public var m_inv_dt:Number; public var m_userData; public var m_body2:b2Body; public static const e_unknownJoint:int = 0; public static const e_inactiveLimit:int = 0; public static const e_atUpperLimit:int = 2; public static const e_atLowerLimit:int = 1; public static const e_gearJoint:int = 6; public static const e_revoluteJoint:int = 1; public static const e_equalLimits:int = 3; public static const e_distanceJoint:int = 3; public static const e_pulleyJoint:int = 4; public static const e_prismaticJoint:int = 2; public static const e_mouseJoint:int = 5; public function b2Joint(def:b2JointDef){ m_node1 = new b2JointEdge(); m_node2 = new b2JointEdge(); super(); m_type = def.type; m_prev = null; m_next = null; m_body1 = def.body1; m_body2 = def.body2; m_collideConnected = def.collideConnected; m_islandFlag = false; m_userData = def.userData; } public function GetBody2():b2Body{ return (m_body2); } public function GetAnchor1():b2Vec2{ return (null); } public function GetAnchor2():b2Vec2{ return (null); } public function GetNext():b2Joint{ return (m_next); } public function GetType():int{ return (m_type); } public function InitVelocityConstraints(step:b2TimeStep):void{ } public function GetReactionTorque():Number{ return (0); } public function GetUserData(){ return (m_userData); } public function GetReactionForce():b2Vec2{ return (null); } public function SolvePositionConstraints():Boolean{ return (false); } public function SetUserData(data):void{ m_userData = data; } public function GetBody1():b2Body{ return (m_body1); } public function SolveVelocityConstraints(step:b2TimeStep):void{ } public function InitPositionConstraints():void{ } public static function Destroy(joint:b2Joint, allocator):void{ } public static function Create(def:b2JointDef, allocator):b2Joint{ var joint:b2Joint; switch (def.type){ case e_distanceJoint: joint = new b2DistanceJoint((def as b2DistanceJointDef)); break; case e_mouseJoint: joint = new b2MouseJoint((def as b2MouseJointDef)); break; case e_prismaticJoint: joint = new b2PrismaticJoint((def as b2PrismaticJointDef)); break; case e_revoluteJoint: joint = new b2RevoluteJoint((def as b2RevoluteJointDef)); break; case e_pulleyJoint: joint = new b2PulleyJoint((def as b2PulleyJointDef)); break; case e_gearJoint: joint = new b2GearJoint((def as b2GearJointDef)); break; default: break; }; return (joint); } } }//package Box2D.Dynamics.Joints
Section 54
//b2JointDef (Box2D.Dynamics.Joints.b2JointDef) package Box2D.Dynamics.Joints { import Box2D.Dynamics.*; public class b2JointDef { public var body2:b2Body; public var type:int; public var userData; public var collideConnected:Boolean; public var body1:b2Body; public function b2JointDef(){ super(); type = b2Joint.e_unknownJoint; userData = null; body1 = null; body2 = null; collideConnected = false; } } }//package Box2D.Dynamics.Joints
Section 55
//b2JointEdge (Box2D.Dynamics.Joints.b2JointEdge) package Box2D.Dynamics.Joints { import Box2D.Dynamics.*; public class b2JointEdge { public var other:b2Body; public var next:b2JointEdge; public var prev:b2JointEdge; public var joint:b2Joint; public function b2JointEdge(){ super(); } } }//package Box2D.Dynamics.Joints
Section 56
//b2MouseJoint (Box2D.Dynamics.Joints.b2MouseJoint) package Box2D.Dynamics.Joints { import Box2D.Dynamics.*; import Box2D.Common.Math.*; import Box2D.Common.*; public class b2MouseJoint extends b2Joint { private var K1:b2Mat22; private var K:b2Mat22; public var m_beta:Number; public var m_mass:b2Mat22; private var K2:b2Mat22; public var m_target:b2Vec2; public var m_gamma:Number; public var m_impulse:b2Vec2; public var m_C:b2Vec2; public var m_localAnchor:b2Vec2; public var m_maxForce:Number; public function b2MouseJoint(def:b2MouseJointDef){ var tY:Number; K = new b2Mat22(); K1 = new b2Mat22(); K2 = new b2Mat22(); m_localAnchor = new b2Vec2(); m_target = new b2Vec2(); m_impulse = new b2Vec2(); m_mass = new b2Mat22(); m_C = new b2Vec2(); super(def); m_target.SetV(def.target); var tX:Number = (m_target.x - m_body2.m_xf.position.x); tY = (m_target.y - m_body2.m_xf.position.y); var tMat:b2Mat22 = m_body2.m_xf.R; m_localAnchor.x = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); m_localAnchor.y = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); m_maxForce = def.maxForce; m_impulse.SetZero(); var mass:Number = m_body2.m_mass; var omega:Number = ((2 * b2Settings.b2_pi) * def.frequencyHz); var d:Number = (((2 * mass) * def.dampingRatio) * omega); var k:Number = ((def.timeStep * mass) * (omega * omega)); m_gamma = (1 / (d + k)); m_beta = (k / (d + k)); } public function SetTarget(target:b2Vec2):void{ if (m_body2.IsSleeping()){ m_body2.WakeUp(); }; m_target = target; } override public function GetAnchor2():b2Vec2{ return (m_body2.GetWorldPoint(m_localAnchor)); } override public function InitVelocityConstraints(step:b2TimeStep):void{ var b:b2Body; var tMat:b2Mat22; var rX:Number; var rY:Number; var invMass:Number; var invI:Number; b = m_body2; tMat = b.m_xf.R; rX = (m_localAnchor.x - b.m_sweep.localCenter.x); rY = (m_localAnchor.y - b.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * rX) + (tMat.col2.x * rY)); rY = ((tMat.col1.y * rX) + (tMat.col2.y * rY)); rX = tX; invMass = b.m_invMass; invI = b.m_invI; K1.col1.x = invMass; K1.col2.x = 0; K1.col1.y = 0; K1.col2.y = invMass; K2.col1.x = ((invI * rY) * rY); K2.col2.x = ((-(invI) * rX) * rY); K2.col1.y = ((-(invI) * rX) * rY); K2.col2.y = ((invI * rX) * rX); K.SetM(K1); K.AddM(K2); K.col1.x = (K.col1.x + m_gamma); K.col2.y = (K.col2.y + m_gamma); K.Invert(m_mass); m_C.x = ((b.m_sweep.c.x + rX) - m_target.x); m_C.y = ((b.m_sweep.c.y + rY) - m_target.y); b.m_angularVelocity = (b.m_angularVelocity * 0.98); var PX:Number = (step.dt * m_impulse.x); var PY:Number = (step.dt * m_impulse.y); b.m_linearVelocity.x = (b.m_linearVelocity.x + (invMass * PX)); b.m_linearVelocity.y = (b.m_linearVelocity.y + (invMass * PY)); b.m_angularVelocity = (b.m_angularVelocity + (invI * ((rX * PY) - (rY * PX)))); } override public function GetAnchor1():b2Vec2{ return (m_target); } override public function GetReactionTorque():Number{ return (0); } override public function GetReactionForce():b2Vec2{ return (m_impulse); } override public function SolvePositionConstraints():Boolean{ return (true); } override public function SolveVelocityConstraints(step:b2TimeStep):void{ var tMat:b2Mat22; var tX:Number; var tY:Number; var b:b2Body = m_body2; tMat = b.m_xf.R; var rX:Number = (m_localAnchor.x - b.m_sweep.localCenter.x); var rY:Number = (m_localAnchor.y - b.m_sweep.localCenter.y); tX = ((tMat.col1.x * rX) + (tMat.col2.x * rY)); rY = ((tMat.col1.y * rX) + (tMat.col2.y * rY)); rX = tX; var CdotX:Number = (b.m_linearVelocity.x + (-(b.m_angularVelocity) * rY)); var CdotY:Number = (b.m_linearVelocity.y + (b.m_angularVelocity * rX)); tMat = m_mass; tX = ((CdotX + ((m_beta * step.inv_dt) * m_C.x)) + ((m_gamma * step.dt) * m_impulse.x)); tY = ((CdotY + ((m_beta * step.inv_dt) * m_C.y)) + ((m_gamma * step.dt) * m_impulse.y)); var forceX:Number = (-(step.inv_dt) * ((tMat.col1.x * tX) + (tMat.col2.x * tY))); var forceY:Number = (-(step.inv_dt) * ((tMat.col1.y * tX) + (tMat.col2.y * tY))); var oldForceX:Number = m_impulse.x; var oldForceY:Number = m_impulse.y; m_impulse.x = (m_impulse.x + forceX); m_impulse.y = (m_impulse.y + forceY); var forceMagnitude:Number = m_impulse.Length(); if (forceMagnitude > m_maxForce){ m_impulse.Multiply((m_maxForce / forceMagnitude)); }; forceX = (m_impulse.x - oldForceX); forceY = (m_impulse.y - oldForceY); var PX:Number = (step.dt * forceX); var PY:Number = (step.dt * forceY); b.m_linearVelocity.x = (b.m_linearVelocity.x + (b.m_invMass * PX)); b.m_linearVelocity.y = (b.m_linearVelocity.y + (b.m_invMass * PY)); b.m_angularVelocity = (b.m_angularVelocity + (b.m_invI * ((rX * PY) - (rY * PX)))); } } }//package Box2D.Dynamics.Joints
Section 57
//b2MouseJointDef (Box2D.Dynamics.Joints.b2MouseJointDef) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; public class b2MouseJointDef extends b2JointDef { public var timeStep:Number; public var target:b2Vec2; public var maxForce:Number; public var dampingRatio:Number; public var frequencyHz:Number; public function b2MouseJointDef(){ target = new b2Vec2(); super(); type = b2Joint.e_mouseJoint; maxForce = 0; frequencyHz = 5; dampingRatio = 0.7; timeStep = (1 / 60); } } }//package Box2D.Dynamics.Joints
Section 58
//b2PrismaticJoint (Box2D.Dynamics.Joints.b2PrismaticJoint) package Box2D.Dynamics.Joints { import Box2D.Dynamics.*; import Box2D.Common.Math.*; import Box2D.Common.*; public class b2PrismaticJoint extends b2Joint { public var m_limitForce:Number; public var m_lowerTranslation:Number; public var m_localXAxis1:b2Vec2; public var m_refAngle:Number; public var m_torque:Number; public var m_motorForce:Number; public var m_enableLimit:Boolean; public var m_angularMass:Number; public var m_maxMotorForce:Number; public var m_localYAxis1:b2Vec2; public var m_force:Number; public var m_motorMass:Number; public var m_upperTranslation:Number; public var m_localAnchor1:b2Vec2; public var m_localAnchor2:b2Vec2; public var m_limitState:int; public var m_linearMass:Number; public var m_motorJacobian:b2Jacobian; public var m_limitPositionImpulse:Number; public var m_motorSpeed:Number; public var m_enableMotor:Boolean; public var m_linearJacobian:b2Jacobian; public function b2PrismaticJoint(def:b2PrismaticJointDef){ var tMat:b2Mat22; var tX:Number; var tY:Number; m_localAnchor1 = new b2Vec2(); m_localAnchor2 = new b2Vec2(); m_localXAxis1 = new b2Vec2(); m_localYAxis1 = new b2Vec2(); m_linearJacobian = new b2Jacobian(); m_motorJacobian = new b2Jacobian(); super(def); m_localAnchor1.SetV(def.localAnchor1); m_localAnchor2.SetV(def.localAnchor2); m_localXAxis1.SetV(def.localAxis1); m_localYAxis1.x = -(m_localXAxis1.y); m_localYAxis1.y = m_localXAxis1.x; m_refAngle = def.referenceAngle; m_linearJacobian.SetZero(); m_linearMass = 0; m_force = 0; m_angularMass = 0; m_torque = 0; m_motorJacobian.SetZero(); m_motorMass = 0; m_motorForce = 0; m_limitForce = 0; m_limitPositionImpulse = 0; m_lowerTranslation = def.lowerTranslation; m_upperTranslation = def.upperTranslation; m_maxMotorForce = def.maxMotorForce; m_motorSpeed = def.motorSpeed; m_enableLimit = def.enableLimit; m_enableMotor = def.enableMotor; } override public function SolveVelocityConstraints(step:b2TimeStep):void{ var oldLimitForce:Number; var motorCdot:Number; var motorForce:Number; var oldMotorForce:Number; var limitCdot:Number; var limitForce:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var invMass1:Number = b1.m_invMass; var invMass2:Number = b2.m_invMass; var invI1:Number = b1.m_invI; var invI2:Number = b2.m_invI; var linearCdot:Number = m_linearJacobian.Compute(b1.m_linearVelocity, b1.m_angularVelocity, b2.m_linearVelocity, b2.m_angularVelocity); var force:Number = ((-(step.inv_dt) * m_linearMass) * linearCdot); m_force = (m_force + force); var P:Number = (step.dt * force); b1.m_linearVelocity.x = (b1.m_linearVelocity.x + ((invMass1 * P) * m_linearJacobian.linear1.x)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y + ((invMass1 * P) * m_linearJacobian.linear1.y)); b1.m_angularVelocity = (b1.m_angularVelocity + ((invI1 * P) * m_linearJacobian.angular1)); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + ((invMass2 * P) * m_linearJacobian.linear2.x)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + ((invMass2 * P) * m_linearJacobian.linear2.y)); b2.m_angularVelocity = (b2.m_angularVelocity + ((invI2 * P) * m_linearJacobian.angular2)); var angularCdot:Number = (b2.m_angularVelocity - b1.m_angularVelocity); var torque:Number = ((-(step.inv_dt) * m_angularMass) * angularCdot); m_torque = (m_torque + torque); var L:Number = (step.dt * torque); b1.m_angularVelocity = (b1.m_angularVelocity - (invI1 * L)); b2.m_angularVelocity = (b2.m_angularVelocity + (invI2 * L)); if (((m_enableMotor) && (!((m_limitState == e_equalLimits))))){ motorCdot = (m_motorJacobian.Compute(b1.m_linearVelocity, b1.m_angularVelocity, b2.m_linearVelocity, b2.m_angularVelocity) - m_motorSpeed); motorForce = ((-(step.inv_dt) * m_motorMass) * motorCdot); oldMotorForce = m_motorForce; m_motorForce = b2Math.b2Clamp((m_motorForce + motorForce), -(m_maxMotorForce), m_maxMotorForce); motorForce = (m_motorForce - oldMotorForce); P = (step.dt * motorForce); b1.m_linearVelocity.x = (b1.m_linearVelocity.x + ((invMass1 * P) * m_motorJacobian.linear1.x)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y + ((invMass1 * P) * m_motorJacobian.linear1.y)); b1.m_angularVelocity = (b1.m_angularVelocity + ((invI1 * P) * m_motorJacobian.angular1)); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + ((invMass2 * P) * m_motorJacobian.linear2.x)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + ((invMass2 * P) * m_motorJacobian.linear2.y)); b2.m_angularVelocity = (b2.m_angularVelocity + ((invI2 * P) * m_motorJacobian.angular2)); }; if (((m_enableLimit) && (!((m_limitState == e_inactiveLimit))))){ limitCdot = m_motorJacobian.Compute(b1.m_linearVelocity, b1.m_angularVelocity, b2.m_linearVelocity, b2.m_angularVelocity); limitForce = ((-(step.inv_dt) * m_motorMass) * limitCdot); if (m_limitState == e_equalLimits){ m_limitForce = (m_limitForce + limitForce); } else { if (m_limitState == e_atLowerLimit){ oldLimitForce = m_limitForce; m_limitForce = b2Math.b2Max((m_limitForce + limitForce), 0); limitForce = (m_limitForce - oldLimitForce); } else { if (m_limitState == e_atUpperLimit){ oldLimitForce = m_limitForce; m_limitForce = b2Math.b2Min((m_limitForce + limitForce), 0); limitForce = (m_limitForce - oldLimitForce); }; }; }; P = (step.dt * limitForce); b1.m_linearVelocity.x = (b1.m_linearVelocity.x + ((invMass1 * P) * m_motorJacobian.linear1.x)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y + ((invMass1 * P) * m_motorJacobian.linear1.y)); b1.m_angularVelocity = (b1.m_angularVelocity + ((invI1 * P) * m_motorJacobian.angular1)); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + ((invMass2 * P) * m_motorJacobian.linear2.x)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + ((invMass2 * P) * m_motorJacobian.linear2.y)); b2.m_angularVelocity = (b2.m_angularVelocity + ((invI2 * P) * m_motorJacobian.angular2)); }; } override public function GetAnchor1():b2Vec2{ return (m_body1.GetWorldPoint(m_localAnchor1)); } override public function GetAnchor2():b2Vec2{ return (m_body2.GetWorldPoint(m_localAnchor2)); } public function GetUpperLimit():Number{ return (m_upperTranslation); } public function GetLowerLimit():Number{ return (m_lowerTranslation); } public function EnableMotor(flag:Boolean):void{ m_enableMotor = flag; } public function GetJointTranslation():Number{ var tMat:b2Mat22; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var p1:b2Vec2 = b1.GetWorldPoint(m_localAnchor1); var p2:b2Vec2 = b2.GetWorldPoint(m_localAnchor2); var dX:Number = (p2.x - p1.x); var dY:Number = (p2.y - p1.y); var axis:b2Vec2 = b1.GetWorldVector(m_localXAxis1); var translation:Number = ((axis.x * dX) + (axis.y * dY)); return (translation); } public function GetMotorSpeed():Number{ return (m_motorSpeed); } override public function GetReactionForce():b2Vec2{ var tMat:b2Mat22 = m_body1.m_xf.R; var ax1X:Number = (m_limitForce * ((tMat.col1.x * m_localXAxis1.x) + (tMat.col2.x * m_localXAxis1.y))); var ax1Y:Number = (m_limitForce * ((tMat.col1.y * m_localXAxis1.x) + (tMat.col2.y * m_localXAxis1.y))); var ay1X:Number = (m_force * ((tMat.col1.x * m_localYAxis1.x) + (tMat.col2.x * m_localYAxis1.y))); var ay1Y:Number = (m_force * ((tMat.col1.y * m_localYAxis1.x) + (tMat.col2.y * m_localYAxis1.y))); return (new b2Vec2(((m_limitForce * ax1X) + (m_force * ay1X)), ((m_limitForce * ax1Y) + (m_force * ay1Y)))); } override public function SolvePositionConstraints():Boolean{ var limitC:Number; var oldLimitImpulse:Number; var tMat:b2Mat22; var tX:Number; var ax1X:Number; var ax1Y:Number; var translation:Number; var limitImpulse:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var invMass1:Number = b1.m_invMass; var invMass2:Number = b2.m_invMass; var invI1:Number = b1.m_invI; var invI2:Number = b2.m_invI; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var p1X:Number = (b1.m_sweep.c.x + r1X); var p1Y:Number = (b1.m_sweep.c.y + r1Y); var p2X:Number = (b2.m_sweep.c.x + r2X); var p2Y:Number = (b2.m_sweep.c.y + r2Y); var dX:Number = (p2X - p1X); var dY:Number = (p2Y - p1Y); tMat = b1.m_xf.R; var ay1X:Number = ((tMat.col1.x * m_localYAxis1.x) + (tMat.col2.x * m_localYAxis1.y)); var ay1Y:Number = ((tMat.col1.y * m_localYAxis1.x) + (tMat.col2.y * m_localYAxis1.y)); var linearC:Number = ((ay1X * dX) + (ay1Y * dY)); linearC = b2Math.b2Clamp(linearC, -(b2Settings.b2_maxLinearCorrection), b2Settings.b2_maxLinearCorrection); var linearImpulse:Number = (-(m_linearMass) * linearC); b1.m_sweep.c.x = (b1.m_sweep.c.x + ((invMass1 * linearImpulse) * m_linearJacobian.linear1.x)); b1.m_sweep.c.y = (b1.m_sweep.c.y + ((invMass1 * linearImpulse) * m_linearJacobian.linear1.y)); b1.m_sweep.a = (b1.m_sweep.a + ((invI1 * linearImpulse) * m_linearJacobian.angular1)); b2.m_sweep.c.x = (b2.m_sweep.c.x + ((invMass2 * linearImpulse) * m_linearJacobian.linear2.x)); b2.m_sweep.c.y = (b2.m_sweep.c.y + ((invMass2 * linearImpulse) * m_linearJacobian.linear2.y)); b2.m_sweep.a = (b2.m_sweep.a + ((invI2 * linearImpulse) * m_linearJacobian.angular2)); var positionError:Number = b2Math.b2Abs(linearC); var angularC:Number = ((b2.m_sweep.a - b1.m_sweep.a) - m_refAngle); angularC = b2Math.b2Clamp(angularC, -(b2Settings.b2_maxAngularCorrection), b2Settings.b2_maxAngularCorrection); var angularImpulse:Number = (-(m_angularMass) * angularC); b1.m_sweep.a = (b1.m_sweep.a - (b1.m_invI * angularImpulse)); b2.m_sweep.a = (b2.m_sweep.a + (b2.m_invI * angularImpulse)); b1.SynchronizeTransform(); b2.SynchronizeTransform(); var angularError:Number = b2Math.b2Abs(angularC); if (((m_enableLimit) && (!((m_limitState == e_inactiveLimit))))){ tMat = b1.m_xf.R; r1X = (m_localAnchor1.x - b1.m_sweep.localCenter.x); r1Y = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; r2X = (m_localAnchor2.x - b2.m_sweep.localCenter.x); r2Y = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; p1X = (b1.m_sweep.c.x + r1X); p1Y = (b1.m_sweep.c.y + r1Y); p2X = (b2.m_sweep.c.x + r2X); p2Y = (b2.m_sweep.c.y + r2Y); dX = (p2X - p1X); dY = (p2Y - p1Y); tMat = b1.m_xf.R; ax1X = ((tMat.col1.x * m_localXAxis1.x) + (tMat.col2.x * m_localXAxis1.y)); ax1Y = ((tMat.col1.y * m_localXAxis1.x) + (tMat.col2.y * m_localXAxis1.y)); translation = ((ax1X * dX) + (ax1Y * dY)); limitImpulse = 0; if (m_limitState == e_equalLimits){ limitC = b2Math.b2Clamp(translation, -(b2Settings.b2_maxLinearCorrection), b2Settings.b2_maxLinearCorrection); limitImpulse = (-(m_motorMass) * limitC); positionError = b2Math.b2Max(positionError, b2Math.b2Abs(angularC)); } else { if (m_limitState == e_atLowerLimit){ limitC = (translation - m_lowerTranslation); positionError = b2Math.b2Max(positionError, -(limitC)); limitC = b2Math.b2Clamp((limitC + b2Settings.b2_linearSlop), -(b2Settings.b2_maxLinearCorrection), 0); limitImpulse = (-(m_motorMass) * limitC); oldLimitImpulse = m_limitPositionImpulse; m_limitPositionImpulse = b2Math.b2Max((m_limitPositionImpulse + limitImpulse), 0); limitImpulse = (m_limitPositionImpulse - oldLimitImpulse); } else { if (m_limitState == e_atUpperLimit){ limitC = (translation - m_upperTranslation); positionError = b2Math.b2Max(positionError, limitC); limitC = b2Math.b2Clamp((limitC - b2Settings.b2_linearSlop), 0, b2Settings.b2_maxLinearCorrection); limitImpulse = (-(m_motorMass) * limitC); oldLimitImpulse = m_limitPositionImpulse; m_limitPositionImpulse = b2Math.b2Min((m_limitPositionImpulse + limitImpulse), 0); limitImpulse = (m_limitPositionImpulse - oldLimitImpulse); }; }; }; b1.m_sweep.c.x = (b1.m_sweep.c.x + ((invMass1 * limitImpulse) * m_motorJacobian.linear1.x)); b1.m_sweep.c.y = (b1.m_sweep.c.y + ((invMass1 * limitImpulse) * m_motorJacobian.linear1.y)); b1.m_sweep.a = (b1.m_sweep.a + ((invI1 * limitImpulse) * m_motorJacobian.angular1)); b2.m_sweep.c.x = (b2.m_sweep.c.x + ((invMass2 * limitImpulse) * m_motorJacobian.linear2.x)); b2.m_sweep.c.y = (b2.m_sweep.c.y + ((invMass2 * limitImpulse) * m_motorJacobian.linear2.y)); b2.m_sweep.a = (b2.m_sweep.a + ((invI2 * limitImpulse) * m_motorJacobian.angular2)); b1.SynchronizeTransform(); b2.SynchronizeTransform(); }; return ((((positionError <= b2Settings.b2_linearSlop)) && ((angularError <= b2Settings.b2_angularSlop)))); } public function SetMotorSpeed(speed:Number):void{ m_motorSpeed = speed; } public function GetJointSpeed():Number{ var tMat:b2Mat22; var b1:b2Body = m_body1; var b2:b2Body = m_body2; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var p1X:Number = (b1.m_sweep.c.x + r1X); var p1Y:Number = (b1.m_sweep.c.y + r1Y); var p2X:Number = (b2.m_sweep.c.x + r2X); var p2Y:Number = (b2.m_sweep.c.y + r2Y); var dX:Number = (p2X - p1X); var dY:Number = (p2Y - p1Y); var axis:b2Vec2 = b1.GetWorldVector(m_localXAxis1); var v1:b2Vec2 = b1.m_linearVelocity; var v2:b2Vec2 = b2.m_linearVelocity; var w1:Number = b1.m_angularVelocity; var w2:Number = b2.m_angularVelocity; var speed:Number = (((dX * (-(w1) * axis.y)) + (dY * (w1 * axis.x))) + ((axis.x * (((v2.x + (-(w2) * r2Y)) - v1.x) - (-(w1) * r1Y))) + (axis.y * (((v2.y + (w2 * r2X)) - v1.y) - (w1 * r1X))))); return (speed); } override public function InitVelocityConstraints(step:b2TimeStep):void{ var tMat:b2Mat22; var tX:Number; var ax1X:Number; var ax1Y:Number; var dX:Number; var dY:Number; var jointTranslation:Number; var P1X:Number; var P1Y:Number; var P2X:Number; var P2Y:Number; var L1:Number; var L2:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var invMass1:Number = b1.m_invMass; var invMass2:Number = b2.m_invMass; var invI1:Number = b1.m_invI; var invI2:Number = b2.m_invI; tMat = b1.m_xf.R; var ay1X:Number = ((tMat.col1.x * m_localYAxis1.x) + (tMat.col2.x * m_localYAxis1.y)); var ay1Y:Number = ((tMat.col1.y * m_localYAxis1.x) + (tMat.col2.y * m_localYAxis1.y)); var eX:Number = ((b2.m_sweep.c.x + r2X) - b1.m_sweep.c.x); var eY:Number = ((b2.m_sweep.c.y + r2Y) - b1.m_sweep.c.y); m_linearJacobian.linear1.x = -(ay1X); m_linearJacobian.linear1.y = -(ay1Y); m_linearJacobian.linear2.x = ay1X; m_linearJacobian.linear2.y = ay1Y; m_linearJacobian.angular1 = -(((eX * ay1Y) - (eY * ay1X))); m_linearJacobian.angular2 = ((r2X * ay1Y) - (r2Y * ay1X)); m_linearMass = (((invMass1 + ((invI1 * m_linearJacobian.angular1) * m_linearJacobian.angular1)) + invMass2) + ((invI2 * m_linearJacobian.angular2) * m_linearJacobian.angular2)); m_linearMass = (1 / m_linearMass); m_angularMass = (invI1 + invI2); if (m_angularMass > Number.MIN_VALUE){ m_angularMass = (1 / m_angularMass); }; if (((m_enableLimit) || (m_enableMotor))){ tMat = b1.m_xf.R; ax1X = ((tMat.col1.x * m_localXAxis1.x) + (tMat.col2.x * m_localXAxis1.y)); ax1Y = ((tMat.col1.y * m_localXAxis1.x) + (tMat.col2.y * m_localXAxis1.y)); m_motorJacobian.linear1.x = -(ax1X); m_motorJacobian.linear1.y = -(ax1Y); m_motorJacobian.linear2.x = ax1X; m_motorJacobian.linear2.y = ax1Y; m_motorJacobian.angular1 = -(((eX * ax1Y) - (eY * ax1X))); m_motorJacobian.angular2 = ((r2X * ax1Y) - (r2Y * ax1X)); m_motorMass = (((invMass1 + ((invI1 * m_motorJacobian.angular1) * m_motorJacobian.angular1)) + invMass2) + ((invI2 * m_motorJacobian.angular2) * m_motorJacobian.angular2)); m_motorMass = (1 / m_motorMass); if (m_enableLimit){ dX = (eX - r1X); dY = (eY - r1Y); jointTranslation = ((ax1X * dX) + (ax1Y * dY)); if (b2Math.b2Abs((m_upperTranslation - m_lowerTranslation)) < (2 * b2Settings.b2_linearSlop)){ m_limitState = e_equalLimits; } else { if (jointTranslation <= m_lowerTranslation){ if (m_limitState != e_atLowerLimit){ m_limitForce = 0; }; m_limitState = e_atLowerLimit; } else { if (jointTranslation >= m_upperTranslation){ if (m_limitState != e_atUpperLimit){ m_limitForce = 0; }; m_limitState = e_atUpperLimit; } else { m_limitState = e_inactiveLimit; m_limitForce = 0; }; }; }; }; }; if (m_enableMotor == false){ m_motorForce = 0; }; if (m_enableLimit == false){ m_limitForce = 0; }; if (step.warmStarting){ P1X = (step.dt * ((m_force * m_linearJacobian.linear1.x) + ((m_motorForce + m_limitForce) * m_motorJacobian.linear1.x))); P1Y = (step.dt * ((m_force * m_linearJacobian.linear1.y) + ((m_motorForce + m_limitForce) * m_motorJacobian.linear1.y))); P2X = (step.dt * ((m_force * m_linearJacobian.linear2.x) + ((m_motorForce + m_limitForce) * m_motorJacobian.linear2.x))); P2Y = (step.dt * ((m_force * m_linearJacobian.linear2.y) + ((m_motorForce + m_limitForce) * m_motorJacobian.linear2.y))); L1 = (step.dt * (((m_force * m_linearJacobian.angular1) - m_torque) + ((m_motorForce + m_limitForce) * m_motorJacobian.angular1))); L2 = (step.dt * (((m_force * m_linearJacobian.angular2) + m_torque) + ((m_motorForce + m_limitForce) * m_motorJacobian.angular2))); b1.m_linearVelocity.x = (b1.m_linearVelocity.x + (invMass1 * P1X)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y + (invMass1 * P1Y)); b1.m_angularVelocity = (b1.m_angularVelocity + (invI1 * L1)); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (invMass2 * P2X)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (invMass2 * P2Y)); b2.m_angularVelocity = (b2.m_angularVelocity + (invI2 * L2)); } else { m_force = 0; m_torque = 0; m_limitForce = 0; m_motorForce = 0; }; m_limitPositionImpulse = 0; } public function GetMotorForce():Number{ return (m_motorForce); } public function EnableLimit(flag:Boolean):void{ m_enableLimit = flag; } public function SetMaxMotorForce(force:Number):void{ m_maxMotorForce = force; } override public function GetReactionTorque():Number{ return (m_torque); } public function IsLimitEnabled():Boolean{ return (m_enableLimit); } public function IsMotorEnabled():Boolean{ return (m_enableMotor); } public function SetLimits(lower:Number, upper:Number):void{ m_lowerTranslation = lower; m_upperTranslation = upper; } } }//package Box2D.Dynamics.Joints
Section 59
//b2PrismaticJointDef (Box2D.Dynamics.Joints.b2PrismaticJointDef) package Box2D.Dynamics.Joints { import Box2D.Dynamics.*; import Box2D.Common.Math.*; public class b2PrismaticJointDef extends b2JointDef { public var motorSpeed:Number; public var localAxis1:b2Vec2; public var referenceAngle:Number; public var upperTranslation:Number; public var localAnchor1:b2Vec2; public var localAnchor2:b2Vec2; public var enableLimit:Boolean; public var enableMotor:Boolean; public var maxMotorForce:Number; public var lowerTranslation:Number; public function b2PrismaticJointDef(){ localAnchor1 = new b2Vec2(); localAnchor2 = new b2Vec2(); localAxis1 = new b2Vec2(); super(); type = b2Joint.e_prismaticJoint; localAxis1.Set(1, 0); referenceAngle = 0; enableLimit = false; lowerTranslation = 0; upperTranslation = 0; enableMotor = false; maxMotorForce = 0; motorSpeed = 0; } public function Initialize(b1:b2Body, b2:b2Body, anchor:b2Vec2, axis:b2Vec2):void{ body1 = b1; body2 = b2; localAnchor1 = body1.GetLocalPoint(anchor); localAnchor2 = body2.GetLocalPoint(anchor); localAxis1 = body1.GetLocalVector(axis); referenceAngle = (body2.GetAngle() - body1.GetAngle()); } } }//package Box2D.Dynamics.Joints
Section 60
//b2PulleyJoint (Box2D.Dynamics.Joints.b2PulleyJoint) package Box2D.Dynamics.Joints { import Box2D.Dynamics.*; import Box2D.Common.Math.*; import Box2D.Common.*; public class b2PulleyJoint extends b2Joint { public var m_limitState1:int; public var m_limitState2:int; public var m_ground:b2Body; public var m_maxLength2:Number; public var m_maxLength1:Number; public var m_limitPositionImpulse1:Number; public var m_limitPositionImpulse2:Number; public var m_force:Number; public var m_constant:Number; public var m_positionImpulse:Number; public var m_state:int; public var m_ratio:Number; public var m_groundAnchor1:b2Vec2; public var m_groundAnchor2:b2Vec2; public var m_localAnchor1:b2Vec2; public var m_localAnchor2:b2Vec2; public var m_limitMass1:Number; public var m_limitMass2:Number; public var m_pulleyMass:Number; public var m_u1:b2Vec2; public var m_limitForce1:Number; public var m_limitForce2:Number; public var m_u2:b2Vec2; public static const b2_minPulleyLength:Number = 2; public function b2PulleyJoint(def:b2PulleyJointDef){ var tMat:b2Mat22; var tX:Number; var tY:Number; m_groundAnchor1 = new b2Vec2(); m_groundAnchor2 = new b2Vec2(); m_localAnchor1 = new b2Vec2(); m_localAnchor2 = new b2Vec2(); m_u1 = new b2Vec2(); m_u2 = new b2Vec2(); super(def); m_ground = m_body1.m_world.m_groundBody; m_groundAnchor1.x = (def.groundAnchor1.x - m_ground.m_xf.position.x); m_groundAnchor1.y = (def.groundAnchor1.y - m_ground.m_xf.position.y); m_groundAnchor2.x = (def.groundAnchor2.x - m_ground.m_xf.position.x); m_groundAnchor2.y = (def.groundAnchor2.y - m_ground.m_xf.position.y); m_localAnchor1.SetV(def.localAnchor1); m_localAnchor2.SetV(def.localAnchor2); m_ratio = def.ratio; m_constant = (def.length1 + (m_ratio * def.length2)); m_maxLength1 = b2Math.b2Min(def.maxLength1, (m_constant - (m_ratio * b2_minPulleyLength))); m_maxLength2 = b2Math.b2Min(def.maxLength2, ((m_constant - b2_minPulleyLength) / m_ratio)); m_force = 0; m_limitForce1 = 0; m_limitForce2 = 0; } public function GetGroundAnchor2():b2Vec2{ var a:b2Vec2 = m_ground.m_xf.position.Copy(); a.Add(m_groundAnchor2); return (a); } override public function GetAnchor1():b2Vec2{ return (m_body1.GetWorldPoint(m_localAnchor1)); } override public function GetAnchor2():b2Vec2{ return (m_body2.GetWorldPoint(m_localAnchor2)); } override public function GetReactionForce():b2Vec2{ var F:b2Vec2 = m_u2.Copy(); F.Multiply(m_force); return (F); } override public function SolvePositionConstraints():Boolean{ var tMat:b2Mat22; var r1X:Number; var r1Y:Number; var r2X:Number; var r2Y:Number; var p1X:Number; var p1Y:Number; var p2X:Number; var p2Y:Number; var length1:Number; var length2:Number; var C:Number; var impulse:Number; var oldImpulse:Number; var oldLimitPositionImpulse:Number; var tX:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var s1X:Number = (m_ground.m_xf.position.x + m_groundAnchor1.x); var s1Y:Number = (m_ground.m_xf.position.y + m_groundAnchor1.y); var s2X:Number = (m_ground.m_xf.position.x + m_groundAnchor2.x); var s2Y:Number = (m_ground.m_xf.position.y + m_groundAnchor2.y); var linearError:Number = 0; if (m_state == e_atUpperLimit){ tMat = b1.m_xf.R; r1X = (m_localAnchor1.x - b1.m_sweep.localCenter.x); r1Y = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; r2X = (m_localAnchor2.x - b2.m_sweep.localCenter.x); r2Y = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; p1X = (b1.m_sweep.c.x + r1X); p1Y = (b1.m_sweep.c.y + r1Y); p2X = (b2.m_sweep.c.x + r2X); p2Y = (b2.m_sweep.c.y + r2Y); m_u1.Set((p1X - s1X), (p1Y - s1Y)); m_u2.Set((p2X - s2X), (p2Y - s2Y)); length1 = m_u1.Length(); length2 = m_u2.Length(); if (length1 > b2Settings.b2_linearSlop){ m_u1.Multiply((1 / length1)); } else { m_u1.SetZero(); }; if (length2 > b2Settings.b2_linearSlop){ m_u2.Multiply((1 / length2)); } else { m_u2.SetZero(); }; C = ((m_constant - length1) - (m_ratio * length2)); linearError = b2Math.b2Max(linearError, -(C)); C = b2Math.b2Clamp((C + b2Settings.b2_linearSlop), -(b2Settings.b2_maxLinearCorrection), 0); impulse = (-(m_pulleyMass) * C); oldImpulse = m_positionImpulse; m_positionImpulse = b2Math.b2Max(0, (m_positionImpulse + impulse)); impulse = (m_positionImpulse - oldImpulse); p1X = (-(impulse) * m_u1.x); p1Y = (-(impulse) * m_u1.y); p2X = ((-(m_ratio) * impulse) * m_u2.x); p2Y = ((-(m_ratio) * impulse) * m_u2.y); b1.m_sweep.c.x = (b1.m_sweep.c.x + (b1.m_invMass * p1X)); b1.m_sweep.c.y = (b1.m_sweep.c.y + (b1.m_invMass * p1Y)); b1.m_sweep.a = (b1.m_sweep.a + (b1.m_invI * ((r1X * p1Y) - (r1Y * p1X)))); b2.m_sweep.c.x = (b2.m_sweep.c.x + (b2.m_invMass * p2X)); b2.m_sweep.c.y = (b2.m_sweep.c.y + (b2.m_invMass * p2Y)); b2.m_sweep.a = (b2.m_sweep.a + (b2.m_invI * ((r2X * p2Y) - (r2Y * p2X)))); b1.SynchronizeTransform(); b2.SynchronizeTransform(); }; if (m_limitState1 == e_atUpperLimit){ tMat = b1.m_xf.R; r1X = (m_localAnchor1.x - b1.m_sweep.localCenter.x); r1Y = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; p1X = (b1.m_sweep.c.x + r1X); p1Y = (b1.m_sweep.c.y + r1Y); m_u1.Set((p1X - s1X), (p1Y - s1Y)); length1 = m_u1.Length(); if (length1 > b2Settings.b2_linearSlop){ m_u1.x = (m_u1.x * (1 / length1)); m_u1.y = (m_u1.y * (1 / length1)); } else { m_u1.SetZero(); }; C = (m_maxLength1 - length1); linearError = b2Math.b2Max(linearError, -(C)); C = b2Math.b2Clamp((C + b2Settings.b2_linearSlop), -(b2Settings.b2_maxLinearCorrection), 0); impulse = (-(m_limitMass1) * C); oldLimitPositionImpulse = m_limitPositionImpulse1; m_limitPositionImpulse1 = b2Math.b2Max(0, (m_limitPositionImpulse1 + impulse)); impulse = (m_limitPositionImpulse1 - oldLimitPositionImpulse); p1X = (-(impulse) * m_u1.x); p1Y = (-(impulse) * m_u1.y); b1.m_sweep.c.x = (b1.m_sweep.c.x + (b1.m_invMass * p1X)); b1.m_sweep.c.y = (b1.m_sweep.c.y + (b1.m_invMass * p1Y)); b1.m_sweep.a = (b1.m_sweep.a + (b1.m_invI * ((r1X * p1Y) - (r1Y * p1X)))); b1.SynchronizeTransform(); }; if (m_limitState2 == e_atUpperLimit){ tMat = b2.m_xf.R; r2X = (m_localAnchor2.x - b2.m_sweep.localCenter.x); r2Y = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; p2X = (b2.m_sweep.c.x + r2X); p2Y = (b2.m_sweep.c.y + r2Y); m_u2.Set((p2X - s2X), (p2Y - s2Y)); length2 = m_u2.Length(); if (length2 > b2Settings.b2_linearSlop){ m_u2.x = (m_u2.x * (1 / length2)); m_u2.y = (m_u2.y * (1 / length2)); } else { m_u2.SetZero(); }; C = (m_maxLength2 - length2); linearError = b2Math.b2Max(linearError, -(C)); C = b2Math.b2Clamp((C + b2Settings.b2_linearSlop), -(b2Settings.b2_maxLinearCorrection), 0); impulse = (-(m_limitMass2) * C); oldLimitPositionImpulse = m_limitPositionImpulse2; m_limitPositionImpulse2 = b2Math.b2Max(0, (m_limitPositionImpulse2 + impulse)); impulse = (m_limitPositionImpulse2 - oldLimitPositionImpulse); p2X = (-(impulse) * m_u2.x); p2Y = (-(impulse) * m_u2.y); b2.m_sweep.c.x = (b2.m_sweep.c.x + (b2.m_invMass * p2X)); b2.m_sweep.c.y = (b2.m_sweep.c.y + (b2.m_invMass * p2Y)); b2.m_sweep.a = (b2.m_sweep.a + (b2.m_invI * ((r2X * p2Y) - (r2Y * p2X)))); b2.SynchronizeTransform(); }; return ((linearError < b2Settings.b2_linearSlop)); } override public function InitVelocityConstraints(step:b2TimeStep):void{ var tMat:b2Mat22; var P1X:Number; var P1Y:Number; var P2X:Number; var P2Y:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var p1X:Number = (b1.m_sweep.c.x + r1X); var p1Y:Number = (b1.m_sweep.c.y + r1Y); var p2X:Number = (b2.m_sweep.c.x + r2X); var p2Y:Number = (b2.m_sweep.c.y + r2Y); var s1X:Number = (m_ground.m_xf.position.x + m_groundAnchor1.x); var s1Y:Number = (m_ground.m_xf.position.y + m_groundAnchor1.y); var s2X:Number = (m_ground.m_xf.position.x + m_groundAnchor2.x); var s2Y:Number = (m_ground.m_xf.position.y + m_groundAnchor2.y); m_u1.Set((p1X - s1X), (p1Y - s1Y)); m_u2.Set((p2X - s2X), (p2Y - s2Y)); var length1:Number = m_u1.Length(); var length2:Number = m_u2.Length(); if (length1 > b2Settings.b2_linearSlop){ m_u1.Multiply((1 / length1)); } else { m_u1.SetZero(); }; if (length2 > b2Settings.b2_linearSlop){ m_u2.Multiply((1 / length2)); } else { m_u2.SetZero(); }; var C:Number = ((m_constant - length1) - (m_ratio * length2)); if (C > 0){ m_state = e_inactiveLimit; m_force = 0; } else { m_state = e_atUpperLimit; m_positionImpulse = 0; }; if (length1 < m_maxLength1){ m_limitState1 = e_inactiveLimit; m_limitForce1 = 0; } else { m_limitState1 = e_atUpperLimit; m_limitPositionImpulse1 = 0; }; if (length2 < m_maxLength2){ m_limitState2 = e_inactiveLimit; m_limitForce2 = 0; } else { m_limitState2 = e_atUpperLimit; m_limitPositionImpulse2 = 0; }; var cr1u1:Number = ((r1X * m_u1.y) - (r1Y * m_u1.x)); var cr2u2:Number = ((r2X * m_u2.y) - (r2Y * m_u2.x)); m_limitMass1 = (b1.m_invMass + ((b1.m_invI * cr1u1) * cr1u1)); m_limitMass2 = (b2.m_invMass + ((b2.m_invI * cr2u2) * cr2u2)); m_pulleyMass = (m_limitMass1 + ((m_ratio * m_ratio) * m_limitMass2)); m_limitMass1 = (1 / m_limitMass1); m_limitMass2 = (1 / m_limitMass2); m_pulleyMass = (1 / m_pulleyMass); if (step.warmStarting){ P1X = ((step.dt * (-(m_force) - m_limitForce1)) * m_u1.x); P1Y = ((step.dt * (-(m_force) - m_limitForce1)) * m_u1.y); P2X = ((step.dt * ((-(m_ratio) * m_force) - m_limitForce2)) * m_u2.x); P2Y = ((step.dt * ((-(m_ratio) * m_force) - m_limitForce2)) * m_u2.y); b1.m_linearVelocity.x = (b1.m_linearVelocity.x + (b1.m_invMass * P1X)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y + (b1.m_invMass * P1Y)); b1.m_angularVelocity = (b1.m_angularVelocity + (b1.m_invI * ((r1X * P1Y) - (r1Y * P1X)))); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (b2.m_invMass * P2X)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (b2.m_invMass * P2Y)); b2.m_angularVelocity = (b2.m_angularVelocity + (b2.m_invI * ((r2X * P2Y) - (r2Y * P2X)))); } else { m_force = 0; m_limitForce1 = 0; m_limitForce2 = 0; }; } override public function GetReactionTorque():Number{ return (0); } public function GetRatio():Number{ return (m_ratio); } override public function SolveVelocityConstraints(step:b2TimeStep):void{ var tMat:b2Mat22; var v1X:Number; var v1Y:Number; var v2X:Number; var v2Y:Number; var P1X:Number; var P1Y:Number; var P2X:Number; var P2Y:Number; var Cdot:Number; var force:Number; var oldForce:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; if (m_state == e_atUpperLimit){ v1X = (b1.m_linearVelocity.x + (-(b1.m_angularVelocity) * r1Y)); v1Y = (b1.m_linearVelocity.y + (b1.m_angularVelocity * r1X)); v2X = (b2.m_linearVelocity.x + (-(b2.m_angularVelocity) * r2Y)); v2Y = (b2.m_linearVelocity.y + (b2.m_angularVelocity * r2X)); Cdot = (-(((m_u1.x * v1X) + (m_u1.y * v1Y))) - (m_ratio * ((m_u2.x * v2X) + (m_u2.y * v2Y)))); force = ((-(step.inv_dt) * m_pulleyMass) * Cdot); oldForce = m_force; m_force = b2Math.b2Max(0, (m_force + force)); force = (m_force - oldForce); P1X = ((-(step.dt) * force) * m_u1.x); P1Y = ((-(step.dt) * force) * m_u1.y); P2X = (((-(step.dt) * m_ratio) * force) * m_u2.x); P2Y = (((-(step.dt) * m_ratio) * force) * m_u2.y); b1.m_linearVelocity.x = (b1.m_linearVelocity.x + (b1.m_invMass * P1X)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y + (b1.m_invMass * P1Y)); b1.m_angularVelocity = (b1.m_angularVelocity + (b1.m_invI * ((r1X * P1Y) - (r1Y * P1X)))); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (b2.m_invMass * P2X)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (b2.m_invMass * P2Y)); b2.m_angularVelocity = (b2.m_angularVelocity + (b2.m_invI * ((r2X * P2Y) - (r2Y * P2X)))); }; if (m_limitState1 == e_atUpperLimit){ v1X = (b1.m_linearVelocity.x + (-(b1.m_angularVelocity) * r1Y)); v1Y = (b1.m_linearVelocity.y + (b1.m_angularVelocity * r1X)); Cdot = -(((m_u1.x * v1X) + (m_u1.y * v1Y))); force = ((-(step.inv_dt) * m_limitMass1) * Cdot); oldForce = m_limitForce1; m_limitForce1 = b2Math.b2Max(0, (m_limitForce1 + force)); force = (m_limitForce1 - oldForce); P1X = ((-(step.dt) * force) * m_u1.x); P1Y = ((-(step.dt) * force) * m_u1.y); b1.m_linearVelocity.x = (b1.m_linearVelocity.x + (b1.m_invMass * P1X)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y + (b1.m_invMass * P1Y)); b1.m_angularVelocity = (b1.m_angularVelocity + (b1.m_invI * ((r1X * P1Y) - (r1Y * P1X)))); }; if (m_limitState2 == e_atUpperLimit){ v2X = (b2.m_linearVelocity.x + (-(b2.m_angularVelocity) * r2Y)); v2Y = (b2.m_linearVelocity.y + (b2.m_angularVelocity * r2X)); Cdot = -(((m_u2.x * v2X) + (m_u2.y * v2Y))); force = ((-(step.inv_dt) * m_limitMass2) * Cdot); oldForce = m_limitForce2; m_limitForce2 = b2Math.b2Max(0, (m_limitForce2 + force)); force = (m_limitForce2 - oldForce); P2X = ((-(step.dt) * force) * m_u2.x); P2Y = ((-(step.dt) * force) * m_u2.y); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (b2.m_invMass * P2X)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (b2.m_invMass * P2Y)); b2.m_angularVelocity = (b2.m_angularVelocity + (b2.m_invI * ((r2X * P2Y) - (r2Y * P2X)))); }; } public function GetLength1():Number{ var p:b2Vec2 = m_body1.GetWorldPoint(m_localAnchor1); var sX:Number = (m_ground.m_xf.position.x + m_groundAnchor1.x); var sY:Number = (m_ground.m_xf.position.y + m_groundAnchor1.y); var dX:Number = (p.x - sX); var dY:Number = (p.y - sY); return (Math.sqrt(((dX * dX) + (dY * dY)))); } public function GetLength2():Number{ var p:b2Vec2 = m_body2.GetWorldPoint(m_localAnchor2); var sX:Number = (m_ground.m_xf.position.x + m_groundAnchor2.x); var sY:Number = (m_ground.m_xf.position.y + m_groundAnchor2.y); var dX:Number = (p.x - sX); var dY:Number = (p.y - sY); return (Math.sqrt(((dX * dX) + (dY * dY)))); } public function GetGroundAnchor1():b2Vec2{ var a:b2Vec2 = m_ground.m_xf.position.Copy(); a.Add(m_groundAnchor1); return (a); } } }//package Box2D.Dynamics.Joints
Section 61
//b2PulleyJointDef (Box2D.Dynamics.Joints.b2PulleyJointDef) package Box2D.Dynamics.Joints { import Box2D.Dynamics.*; import Box2D.Common.Math.*; public class b2PulleyJointDef extends b2JointDef { public var maxLength1:Number; public var maxLength2:Number; public var length1:Number; public var localAnchor1:b2Vec2; public var localAnchor2:b2Vec2; public var groundAnchor1:b2Vec2; public var groundAnchor2:b2Vec2; public var ratio:Number; public var length2:Number; public function b2PulleyJointDef(){ groundAnchor1 = new b2Vec2(); groundAnchor2 = new b2Vec2(); localAnchor1 = new b2Vec2(); localAnchor2 = new b2Vec2(); super(); type = b2Joint.e_pulleyJoint; groundAnchor1.Set(-1, 1); groundAnchor2.Set(1, 1); localAnchor1.Set(-1, 0); localAnchor2.Set(1, 0); length1 = 0; maxLength1 = 0; length2 = 0; maxLength2 = 0; ratio = 1; collideConnected = true; } public function Initialize(b1:b2Body, b2:b2Body, ga1:b2Vec2, ga2:b2Vec2, anchor1:b2Vec2, anchor2:b2Vec2, r:Number):void{ body1 = b1; body2 = b2; groundAnchor1.SetV(ga1); groundAnchor2.SetV(ga2); localAnchor1 = body1.GetLocalPoint(anchor1); localAnchor2 = body2.GetLocalPoint(anchor2); var d1X:Number = (anchor1.x - ga1.x); var d1Y:Number = (anchor1.y - ga1.y); length1 = Math.sqrt(((d1X * d1X) + (d1Y * d1Y))); var d2X:Number = (anchor2.x - ga2.x); var d2Y:Number = (anchor2.y - ga2.y); length2 = Math.sqrt(((d2X * d2X) + (d2Y * d2Y))); ratio = r; var C:Number = (length1 + (ratio * length2)); maxLength1 = (C - (ratio * b2PulleyJoint.b2_minPulleyLength)); maxLength2 = ((C - b2PulleyJoint.b2_minPulleyLength) / ratio); } } }//package Box2D.Dynamics.Joints
Section 62
//b2RevoluteJoint (Box2D.Dynamics.Joints.b2RevoluteJoint) package Box2D.Dynamics.Joints { import Box2D.Dynamics.*; import Box2D.Common.Math.*; import Box2D.Common.*; public class b2RevoluteJoint extends b2Joint { public var m_limitForce:Number; public var m_pivotMass:b2Mat22; public var m_motorForce:Number; public var m_enableLimit:Boolean; public var m_limitState:int; public var m_motorMass:Number; public var m_localAnchor1:b2Vec2; public var m_localAnchor2:b2Vec2; private var K1:b2Mat22; private var K2:b2Mat22; private var K3:b2Mat22; private var K:b2Mat22; public var m_pivotForce:b2Vec2; public var m_enableMotor:Boolean; public var m_referenceAngle:Number; public var m_limitPositionImpulse:Number; public var m_motorSpeed:Number; public var m_upperAngle:Number; public var m_lowerAngle:Number; public var m_maxMotorTorque:Number; public static var tImpulse:b2Vec2 = new b2Vec2(); public function b2RevoluteJoint(def:b2RevoluteJointDef){ K = new b2Mat22(); K1 = new b2Mat22(); K2 = new b2Mat22(); K3 = new b2Mat22(); m_localAnchor1 = new b2Vec2(); m_localAnchor2 = new b2Vec2(); m_pivotForce = new b2Vec2(); m_pivotMass = new b2Mat22(); super(def); m_localAnchor1.SetV(def.localAnchor1); m_localAnchor2.SetV(def.localAnchor2); m_referenceAngle = def.referenceAngle; m_pivotForce.Set(0, 0); m_motorForce = 0; m_limitForce = 0; m_limitPositionImpulse = 0; m_lowerAngle = def.lowerAngle; m_upperAngle = def.upperAngle; m_maxMotorTorque = def.maxMotorTorque; m_motorSpeed = def.motorSpeed; m_enableLimit = def.enableLimit; m_enableMotor = def.enableMotor; } override public function SolveVelocityConstraints(step:b2TimeStep):void{ var tMat:b2Mat22; var tX:Number; var oldLimitForce:Number; var PY:Number; var motorCdot:Number; var motorForce:Number; var oldMotorForce:Number; var limitCdot:Number; var limitForce:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var pivotCdotX:Number = (((b2.m_linearVelocity.x + (-(b2.m_angularVelocity) * r2Y)) - b1.m_linearVelocity.x) - (-(b1.m_angularVelocity) * r1Y)); var pivotCdotY:Number = (((b2.m_linearVelocity.y + (b2.m_angularVelocity * r2X)) - b1.m_linearVelocity.y) - (b1.m_angularVelocity * r1X)); var pivotForceX:Number = (-(step.inv_dt) * ((m_pivotMass.col1.x * pivotCdotX) + (m_pivotMass.col2.x * pivotCdotY))); var pivotForceY:Number = (-(step.inv_dt) * ((m_pivotMass.col1.y * pivotCdotX) + (m_pivotMass.col2.y * pivotCdotY))); m_pivotForce.x = (m_pivotForce.x + pivotForceX); m_pivotForce.y = (m_pivotForce.y + pivotForceY); var PX:Number = (step.dt * pivotForceX); PY = (step.dt * pivotForceY); b1.m_linearVelocity.x = (b1.m_linearVelocity.x - (b1.m_invMass * PX)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y - (b1.m_invMass * PY)); b1.m_angularVelocity = (b1.m_angularVelocity - (b1.m_invI * ((r1X * PY) - (r1Y * PX)))); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (b2.m_invMass * PX)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (b2.m_invMass * PY)); b2.m_angularVelocity = (b2.m_angularVelocity + (b2.m_invI * ((r2X * PY) - (r2Y * PX)))); if (((m_enableMotor) && (!((m_limitState == e_equalLimits))))){ motorCdot = ((b2.m_angularVelocity - b1.m_angularVelocity) - m_motorSpeed); motorForce = ((-(step.inv_dt) * m_motorMass) * motorCdot); oldMotorForce = m_motorForce; m_motorForce = b2Math.b2Clamp((m_motorForce + motorForce), -(m_maxMotorTorque), m_maxMotorTorque); motorForce = (m_motorForce - oldMotorForce); b1.m_angularVelocity = (b1.m_angularVelocity - ((b1.m_invI * step.dt) * motorForce)); b2.m_angularVelocity = (b2.m_angularVelocity + ((b2.m_invI * step.dt) * motorForce)); }; if (((m_enableLimit) && (!((m_limitState == e_inactiveLimit))))){ limitCdot = (b2.m_angularVelocity - b1.m_angularVelocity); limitForce = ((-(step.inv_dt) * m_motorMass) * limitCdot); if (m_limitState == e_equalLimits){ m_limitForce = (m_limitForce + limitForce); } else { if (m_limitState == e_atLowerLimit){ oldLimitForce = m_limitForce; m_limitForce = b2Math.b2Max((m_limitForce + limitForce), 0); limitForce = (m_limitForce - oldLimitForce); } else { if (m_limitState == e_atUpperLimit){ oldLimitForce = m_limitForce; m_limitForce = b2Math.b2Min((m_limitForce + limitForce), 0); limitForce = (m_limitForce - oldLimitForce); }; }; }; b1.m_angularVelocity = (b1.m_angularVelocity - ((b1.m_invI * step.dt) * limitForce)); b2.m_angularVelocity = (b2.m_angularVelocity + ((b2.m_invI * step.dt) * limitForce)); }; } override public function GetAnchor1():b2Vec2{ return (m_body1.GetWorldPoint(m_localAnchor1)); } override public function GetAnchor2():b2Vec2{ return (m_body2.GetWorldPoint(m_localAnchor2)); } public function GetUpperLimit():Number{ return (m_upperAngle); } public function GetLowerLimit():Number{ return (m_lowerAngle); } public function EnableMotor(flag:Boolean):void{ m_enableMotor = flag; } public function GetMotorSpeed():Number{ return (m_motorSpeed); } override public function GetReactionForce():b2Vec2{ return (m_pivotForce); } override public function SolvePositionConstraints():Boolean{ var oldLimitImpulse:Number; var limitC:Number; var tMat:b2Mat22; var angle:Number; var limitImpulse:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var positionError:Number = 0; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var p1X:Number = (b1.m_sweep.c.x + r1X); var p1Y:Number = (b1.m_sweep.c.y + r1Y); var p2X:Number = (b2.m_sweep.c.x + r2X); var p2Y:Number = (b2.m_sweep.c.y + r2Y); var ptpCX:Number = (p2X - p1X); var ptpCY:Number = (p2Y - p1Y); positionError = Math.sqrt(((ptpCX * ptpCX) + (ptpCY * ptpCY))); var invMass1:Number = b1.m_invMass; var invMass2:Number = b2.m_invMass; var invI1:Number = b1.m_invI; var invI2:Number = b2.m_invI; K1.col1.x = (invMass1 + invMass2); K1.col2.x = 0; K1.col1.y = 0; K1.col2.y = (invMass1 + invMass2); K2.col1.x = ((invI1 * r1Y) * r1Y); K2.col2.x = ((-(invI1) * r1X) * r1Y); K2.col1.y = ((-(invI1) * r1X) * r1Y); K2.col2.y = ((invI1 * r1X) * r1X); K3.col1.x = ((invI2 * r2Y) * r2Y); K3.col2.x = ((-(invI2) * r2X) * r2Y); K3.col1.y = ((-(invI2) * r2X) * r2Y); K3.col2.y = ((invI2 * r2X) * r2X); K.SetM(K1); K.AddM(K2); K.AddM(K3); K.Solve(tImpulse, -(ptpCX), -(ptpCY)); var impulseX:Number = tImpulse.x; var impulseY:Number = tImpulse.y; b1.m_sweep.c.x = (b1.m_sweep.c.x - (b1.m_invMass * impulseX)); b1.m_sweep.c.y = (b1.m_sweep.c.y - (b1.m_invMass * impulseY)); b1.m_sweep.a = (b1.m_sweep.a - (b1.m_invI * ((r1X * impulseY) - (r1Y * impulseX)))); b2.m_sweep.c.x = (b2.m_sweep.c.x + (b2.m_invMass * impulseX)); b2.m_sweep.c.y = (b2.m_sweep.c.y + (b2.m_invMass * impulseY)); b2.m_sweep.a = (b2.m_sweep.a + (b2.m_invI * ((r2X * impulseY) - (r2Y * impulseX)))); b1.SynchronizeTransform(); b2.SynchronizeTransform(); var angularError:Number = 0; if (((m_enableLimit) && (!((m_limitState == e_inactiveLimit))))){ angle = ((b2.m_sweep.a - b1.m_sweep.a) - m_referenceAngle); limitImpulse = 0; if (m_limitState == e_equalLimits){ limitC = b2Math.b2Clamp(angle, -(b2Settings.b2_maxAngularCorrection), b2Settings.b2_maxAngularCorrection); limitImpulse = (-(m_motorMass) * limitC); angularError = b2Math.b2Abs(limitC); } else { if (m_limitState == e_atLowerLimit){ limitC = (angle - m_lowerAngle); angularError = b2Math.b2Max(0, -(limitC)); limitC = b2Math.b2Clamp((limitC + b2Settings.b2_angularSlop), -(b2Settings.b2_maxAngularCorrection), 0); limitImpulse = (-(m_motorMass) * limitC); oldLimitImpulse = m_limitPositionImpulse; m_limitPositionImpulse = b2Math.b2Max((m_limitPositionImpulse + limitImpulse), 0); limitImpulse = (m_limitPositionImpulse - oldLimitImpulse); } else { if (m_limitState == e_atUpperLimit){ limitC = (angle - m_upperAngle); angularError = b2Math.b2Max(0, limitC); limitC = b2Math.b2Clamp((limitC - b2Settings.b2_angularSlop), 0, b2Settings.b2_maxAngularCorrection); limitImpulse = (-(m_motorMass) * limitC); oldLimitImpulse = m_limitPositionImpulse; m_limitPositionImpulse = b2Math.b2Min((m_limitPositionImpulse + limitImpulse), 0); limitImpulse = (m_limitPositionImpulse - oldLimitImpulse); }; }; }; b1.m_sweep.a = (b1.m_sweep.a - (b1.m_invI * limitImpulse)); b2.m_sweep.a = (b2.m_sweep.a + (b2.m_invI * limitImpulse)); b1.SynchronizeTransform(); b2.SynchronizeTransform(); }; return ((((positionError <= b2Settings.b2_linearSlop)) && ((angularError <= b2Settings.b2_angularSlop)))); } public function SetMotorSpeed(speed:Number):void{ m_motorSpeed = speed; } public function GetJointSpeed():Number{ return ((m_body2.m_angularVelocity - m_body1.m_angularVelocity)); } public function SetMaxMotorTorque(torque:Number):void{ m_maxMotorTorque = torque; } public function GetJointAngle():Number{ return (((m_body2.m_sweep.a - m_body1.m_sweep.a) - m_referenceAngle)); } public function GetMotorTorque():Number{ return (m_motorForce); } override public function InitVelocityConstraints(step:b2TimeStep):void{ var b1:b2Body; var b2:b2Body; var tMat:b2Mat22; var tX:Number; var r1Y:Number; var jointAngle:Number; b1 = m_body1; b2 = m_body2; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); r1Y = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var invMass1:Number = b1.m_invMass; var invMass2:Number = b2.m_invMass; var invI1:Number = b1.m_invI; var invI2:Number = b2.m_invI; K1.col1.x = (invMass1 + invMass2); K1.col2.x = 0; K1.col1.y = 0; K1.col2.y = (invMass1 + invMass2); K2.col1.x = ((invI1 * r1Y) * r1Y); K2.col2.x = ((-(invI1) * r1X) * r1Y); K2.col1.y = ((-(invI1) * r1X) * r1Y); K2.col2.y = ((invI1 * r1X) * r1X); K3.col1.x = ((invI2 * r2Y) * r2Y); K3.col2.x = ((-(invI2) * r2X) * r2Y); K3.col1.y = ((-(invI2) * r2X) * r2Y); K3.col2.y = ((invI2 * r2X) * r2X); K.SetM(K1); K.AddM(K2); K.AddM(K3); K.Invert(m_pivotMass); m_motorMass = (1 / (invI1 + invI2)); if (m_enableMotor == false){ m_motorForce = 0; }; if (m_enableLimit){ jointAngle = ((b2.m_sweep.a - b1.m_sweep.a) - m_referenceAngle); if (b2Math.b2Abs((m_upperAngle - m_lowerAngle)) < (2 * b2Settings.b2_angularSlop)){ m_limitState = e_equalLimits; } else { if (jointAngle <= m_lowerAngle){ if (m_limitState != e_atLowerLimit){ m_limitForce = 0; }; m_limitState = e_atLowerLimit; } else { if (jointAngle >= m_upperAngle){ if (m_limitState != e_atUpperLimit){ m_limitForce = 0; }; m_limitState = e_atUpperLimit; } else { m_limitState = e_inactiveLimit; m_limitForce = 0; }; }; }; } else { m_limitForce = 0; }; if (step.warmStarting){ b1.m_linearVelocity.x = (b1.m_linearVelocity.x - ((step.dt * invMass1) * m_pivotForce.x)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y - ((step.dt * invMass1) * m_pivotForce.y)); b1.m_angularVelocity = (b1.m_angularVelocity - ((step.dt * invI1) * ((((r1X * m_pivotForce.y) - (r1Y * m_pivotForce.x)) + m_motorForce) + m_limitForce))); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + ((step.dt * invMass2) * m_pivotForce.x)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + ((step.dt * invMass2) * m_pivotForce.y)); b2.m_angularVelocity = (b2.m_angularVelocity + ((step.dt * invI2) * ((((r2X * m_pivotForce.y) - (r2Y * m_pivotForce.x)) + m_motorForce) + m_limitForce))); } else { m_pivotForce.SetZero(); m_motorForce = 0; m_limitForce = 0; }; m_limitPositionImpulse = 0; } public function EnableLimit(flag:Boolean):void{ m_enableLimit = flag; } override public function GetReactionTorque():Number{ return (m_limitForce); } public function IsLimitEnabled():Boolean{ return (m_enableLimit); } public function IsMotorEnabled():Boolean{ return (m_enableMotor); } public function SetLimits(lower:Number, upper:Number):void{ m_lowerAngle = lower; m_upperAngle = upper; } } }//package Box2D.Dynamics.Joints
Section 63
//b2RevoluteJointDef (Box2D.Dynamics.Joints.b2RevoluteJointDef) package Box2D.Dynamics.Joints { import Box2D.Dynamics.*; import Box2D.Common.Math.*; public class b2RevoluteJointDef extends b2JointDef { public var upperAngle:Number; public var enableMotor:Boolean; public var referenceAngle:Number; public var motorSpeed:Number; public var localAnchor1:b2Vec2; public var localAnchor2:b2Vec2; public var enableLimit:Boolean; public var lowerAngle:Number; public var maxMotorTorque:Number; public function b2RevoluteJointDef(){ localAnchor1 = new b2Vec2(); localAnchor2 = new b2Vec2(); super(); type = b2Joint.e_revoluteJoint; localAnchor1.Set(0, 0); localAnchor2.Set(0, 0); referenceAngle = 0; lowerAngle = 0; upperAngle = 0; maxMotorTorque = 0; motorSpeed = 0; enableLimit = false; enableMotor = false; } public function Initialize(b1:b2Body, b2:b2Body, anchor:b2Vec2):void{ body1 = b1; body2 = b2; localAnchor1 = body1.GetLocalPoint(anchor); localAnchor2 = body2.GetLocalPoint(anchor); referenceAngle = (body2.GetAngle() - body1.GetAngle()); } } }//package Box2D.Dynamics.Joints
Section 64
//b2Body (Box2D.Dynamics.b2Body) package Box2D.Dynamics { import Box2D.Common.Math.*; import Box2D.Dynamics.Joints.*; import Box2D.Collision.Shapes.*; import Box2D.Dynamics.Contacts.*; public class b2Body { public var m_next:b2Body; public var m_xf:b2XForm; public var m_contactList:b2ContactEdge; public var m_angularVelocity:Number; public var m_shapeList:b2Shape; public var m_force:b2Vec2; public var m_mass:Number; public var m_sweep:b2Sweep; public var m_torque:Number; public var m_userData; public var m_flags:uint; public var m_world:b2World; public var m_prev:b2Body; public var m_invMass:Number; public var m_type:int; public var m_linearDamping:Number; public var m_shapeCount:int; public var m_angularDamping:Number; public var m_invI:Number; public var m_linearVelocity:b2Vec2; public var m_sleepTime:Number; public var m_jointList:b2JointEdge; public var m_I:Number; public static var e_fixedRotationFlag:uint = 64; public static var e_frozenFlag:uint = 2; public static var e_maxTypes:uint = 3; public static var e_sleepFlag:uint = 8; private static var s_massData:b2MassData = new b2MassData(); public static var e_bulletFlag:uint = 32; public static var e_staticType:uint = 1; public static var e_islandFlag:uint = 4; public static var e_allowSleepFlag:uint = 16; private static var s_xf1:b2XForm = new b2XForm(); public static var e_dynamicType:uint = 2; public function b2Body(bd:b2BodyDef, world:b2World){ m_xf = new b2XForm(); m_sweep = new b2Sweep(); m_linearVelocity = new b2Vec2(); m_force = new b2Vec2(); super(); m_flags = 0; if (bd.isBullet){ m_flags = (m_flags | e_bulletFlag); }; if (bd.fixedRotation){ m_flags = (m_flags | e_fixedRotationFlag); }; if (bd.allowSleep){ m_flags = (m_flags | e_allowSleepFlag); }; if (bd.isSleeping){ m_flags = (m_flags | e_sleepFlag); }; m_world = world; m_xf.position.SetV(bd.position); m_xf.R.Set(bd.angle); m_sweep.localCenter.SetV(bd.massData.center); m_sweep.t0 = 1; m_sweep.a0 = (m_sweep.a = bd.angle); var tMat:b2Mat22 = m_xf.R; var tVec:b2Vec2 = m_sweep.localCenter; m_sweep.c.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); m_sweep.c.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); m_sweep.c.x = (m_sweep.c.x + m_xf.position.x); m_sweep.c.y = (m_sweep.c.y + m_xf.position.y); m_sweep.c0.SetV(m_sweep.c); m_jointList = null; m_contactList = null; m_prev = null; m_next = null; m_linearDamping = bd.linearDamping; m_angularDamping = bd.angularDamping; m_force.Set(0, 0); m_torque = 0; m_linearVelocity.SetZero(); m_angularVelocity = 0; m_sleepTime = 0; m_invMass = 0; m_I = 0; m_invI = 0; m_mass = bd.massData.mass; if (m_mass > 0){ m_invMass = (1 / m_mass); }; if ((m_flags & b2Body.e_fixedRotationFlag) == 0){ m_I = bd.massData.I; }; if (m_I > 0){ m_invI = (1 / m_I); }; if ((((m_invMass == 0)) && ((m_invI == 0)))){ m_type = e_staticType; } else { m_type = e_dynamicType; }; m_userData = bd.userData; m_shapeList = null; m_shapeCount = 0; } public function GetLinearVelocityFromWorldPoint(worldPoint:b2Vec2):b2Vec2{ return (new b2Vec2((m_linearVelocity.x - (m_angularVelocity * (worldPoint.y - m_sweep.c.y))), (m_linearVelocity.y + (m_angularVelocity * (worldPoint.x - m_sweep.c.x))))); } public function SetLinearVelocity(v:b2Vec2):void{ m_linearVelocity.SetV(v); } public function WakeUp():void{ m_flags = (m_flags & ~(e_sleepFlag)); m_sleepTime = 0; } public function GetLocalCenter():b2Vec2{ return (m_sweep.localCenter); } public function ApplyTorque(torque:Number):void{ if (IsSleeping()){ WakeUp(); }; m_torque = (m_torque + torque); } public function IsFrozen():Boolean{ return (((m_flags & e_frozenFlag) == e_frozenFlag)); } public function IsDynamic():Boolean{ return ((m_type == e_dynamicType)); } public function GetLinearVelocity():b2Vec2{ return (m_linearVelocity); } public function SynchronizeTransform():void{ m_xf.R.Set(m_sweep.a); var tMat:b2Mat22 = m_xf.R; var tVec:b2Vec2 = m_sweep.localCenter; m_xf.position.x = (m_sweep.c.x - ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); m_xf.position.y = (m_sweep.c.y - ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); } public function GetInertia():Number{ return (m_I); } public function IsSleeping():Boolean{ return (((m_flags & e_sleepFlag) == e_sleepFlag)); } public function SetMassFromShapes():void{ var s:b2Shape; if (m_world.m_lock == true){ return; }; m_mass = 0; m_invMass = 0; m_I = 0; m_invI = 0; var centerX:Number = 0; var centerY:Number = 0; var massData:b2MassData = s_massData; s = m_shapeList; while (s) { s.ComputeMass(massData); m_mass = (m_mass + massData.mass); centerX = (centerX + (massData.mass * massData.center.x)); centerY = (centerY + (massData.mass * massData.center.y)); m_I = (m_I + massData.I); s = s.m_next; }; if (m_mass > 0){ m_invMass = (1 / m_mass); centerX = (centerX * m_invMass); centerY = (centerY * m_invMass); }; if ((((m_I > 0)) && (((m_flags & e_fixedRotationFlag) == 0)))){ m_I = (m_I - (m_mass * ((centerX * centerX) + (centerY * centerY)))); m_invI = (1 / m_I); } else { m_I = 0; m_invI = 0; }; m_sweep.localCenter.Set(centerX, centerY); var tMat:b2Mat22 = m_xf.R; var tVec:b2Vec2 = m_sweep.localCenter; m_sweep.c.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); m_sweep.c.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); m_sweep.c.x = (m_sweep.c.x + m_xf.position.x); m_sweep.c.y = (m_sweep.c.y + m_xf.position.y); m_sweep.c0.SetV(m_sweep.c); s = m_shapeList; while (s) { s.UpdateSweepRadius(m_sweep.localCenter); s = s.m_next; }; var oldType:int = m_type; if ((((m_invMass == 0)) && ((m_invI == 0)))){ m_type = e_staticType; } else { m_type = e_dynamicType; }; if (oldType != m_type){ s = m_shapeList; while (s) { s.RefilterProxy(m_world.m_broadPhase, m_xf); s = s.m_next; }; }; } public function PutToSleep():void{ m_flags = (m_flags | e_sleepFlag); m_sleepTime = 0; m_linearVelocity.SetZero(); m_angularVelocity = 0; m_force.SetZero(); m_torque = 0; } public function GetJointList():b2JointEdge{ return (m_jointList); } public function SetXForm(position:b2Vec2, angle:Number):Boolean{ var s:b2Shape; var inRange:Boolean; if (m_world.m_lock == true){ return (true); }; if (IsFrozen()){ return (false); }; m_xf.R.Set(angle); m_xf.position.SetV(position); var tMat:b2Mat22 = m_xf.R; var tVec:b2Vec2 = m_sweep.localCenter; m_sweep.c.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); m_sweep.c.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); m_sweep.c.x = (m_sweep.c.x + m_xf.position.x); m_sweep.c.y = (m_sweep.c.y + m_xf.position.y); m_sweep.c0.SetV(m_sweep.c); m_sweep.a0 = (m_sweep.a = angle); var freeze:Boolean; s = m_shapeList; while (s) { inRange = s.Synchronize(m_world.m_broadPhase, m_xf, m_xf); if (inRange == false){ freeze = true; break; }; s = s.m_next; }; if (freeze == true){ m_flags = (m_flags | e_frozenFlag); m_linearVelocity.SetZero(); m_angularVelocity = 0; s = m_shapeList; while (s) { s.DestroyProxy(m_world.m_broadPhase); s = s.m_next; }; return (false); }; m_world.m_broadPhase.Commit(); return (true); } public function GetLocalPoint(worldPoint:b2Vec2):b2Vec2{ return (b2Math.b2MulXT(m_xf, worldPoint)); } public function ApplyForce(force:b2Vec2, point:b2Vec2):void{ if (IsSleeping()){ WakeUp(); }; m_force.x = (m_force.x + force.x); m_force.y = (m_force.y + force.y); m_torque = (m_torque + (((point.x - m_sweep.c.x) * force.y) - ((point.y - m_sweep.c.y) * force.x))); } public function SynchronizeShapes():Boolean{ var s:b2Shape; var xf1:b2XForm = s_xf1; xf1.R.Set(m_sweep.a0); var tMat:b2Mat22 = xf1.R; var tVec:b2Vec2 = m_sweep.localCenter; xf1.position.x = (m_sweep.c0.x - ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); xf1.position.y = (m_sweep.c0.y - ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); var inRange:Boolean; s = m_shapeList; while (s) { inRange = s.Synchronize(m_world.m_broadPhase, xf1, m_xf); if (inRange == false){ break; }; s = s.m_next; }; if (inRange == false){ m_flags = (m_flags | e_frozenFlag); m_linearVelocity.SetZero(); m_angularVelocity = 0; s = m_shapeList; while (s) { s.DestroyProxy(m_world.m_broadPhase); s = s.m_next; }; return (false); }; return (true); } public function GetAngle():Number{ return (m_sweep.a); } public function GetXForm():b2XForm{ return (m_xf); } public function GetLinearVelocityFromLocalPoint(localPoint:b2Vec2):b2Vec2{ var A:b2Mat22 = m_xf.R; var worldPoint:b2Vec2 = new b2Vec2(((A.col1.x * localPoint.x) + (A.col2.x * localPoint.y)), ((A.col1.y * localPoint.x) + (A.col2.y * localPoint.y))); worldPoint.x = (worldPoint.x + m_xf.position.x); worldPoint.y = (worldPoint.y + m_xf.position.y); return (new b2Vec2((m_linearVelocity.x + (m_angularVelocity * (worldPoint.y - m_sweep.c.y))), (m_linearVelocity.x - (m_angularVelocity * (worldPoint.x - m_sweep.c.x))))); } public function GetNext():b2Body{ return (m_next); } public function GetMass():Number{ return (m_mass); } public function ApplyImpulse(impulse:b2Vec2, point:b2Vec2):void{ if (IsSleeping()){ WakeUp(); }; m_linearVelocity.x = (m_linearVelocity.x + (m_invMass * impulse.x)); m_linearVelocity.y = (m_linearVelocity.y + (m_invMass * impulse.y)); m_angularVelocity = (m_angularVelocity + (m_invI * (((point.x - m_sweep.c.x) * impulse.y) - ((point.y - m_sweep.c.y) * impulse.x)))); } public function GetAngularVelocity():Number{ return (m_angularVelocity); } public function SetAngularVelocity(omega:Number):void{ m_angularVelocity = omega; } public function SetMass(massData:b2MassData):void{ var s:b2Shape; if (m_world.m_lock == true){ return; }; m_invMass = 0; m_I = 0; m_invI = 0; m_mass = massData.mass; if (m_mass > 0){ m_invMass = (1 / m_mass); }; if ((m_flags & b2Body.e_fixedRotationFlag) == 0){ m_I = massData.I; }; if (m_I > 0){ m_invI = (1 / m_I); }; m_sweep.localCenter.SetV(massData.center); var tMat:b2Mat22 = m_xf.R; var tVec:b2Vec2 = m_sweep.localCenter; m_sweep.c.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); m_sweep.c.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); m_sweep.c.x = (m_sweep.c.x + m_xf.position.x); m_sweep.c.y = (m_sweep.c.y + m_xf.position.y); m_sweep.c0.SetV(m_sweep.c); s = m_shapeList; while (s) { s.UpdateSweepRadius(m_sweep.localCenter); s = s.m_next; }; var oldType:int = m_type; if ((((m_invMass == 0)) && ((m_invI == 0)))){ m_type = e_staticType; } else { m_type = e_dynamicType; }; if (oldType != m_type){ s = m_shapeList; while (s) { s.RefilterProxy(m_world.m_broadPhase, m_xf); s = s.m_next; }; }; } public function IsStatic():Boolean{ return ((m_type == e_staticType)); } public function GetWorldVector(localVector:b2Vec2):b2Vec2{ return (b2Math.b2MulMV(m_xf.R, localVector)); } public function GetShapeList():b2Shape{ return (m_shapeList); } public function Advance(t:Number):void{ m_sweep.Advance(t); m_sweep.c.SetV(m_sweep.c0); m_sweep.a = m_sweep.a0; SynchronizeTransform(); } public function SetBullet(flag:Boolean):void{ if (flag){ m_flags = (m_flags | e_bulletFlag); } else { m_flags = (m_flags & ~(e_bulletFlag)); }; } public function CreateShape(def:b2ShapeDef):b2Shape{ if (m_world.m_lock == true){ return (null); }; var s:b2Shape = b2Shape.Create(def, m_world.m_blockAllocator); s.m_next = m_shapeList; m_shapeList = s; m_shapeCount++; s.m_body = this; s.CreateProxy(m_world.m_broadPhase, m_xf); s.UpdateSweepRadius(m_sweep.localCenter); return (s); } public function IsConnected(other:b2Body):Boolean{ var jn:b2JointEdge = m_jointList; while (jn) { if (jn.other == other){ return ((jn.joint.m_collideConnected == false)); }; jn = jn.next; }; return (false); } public function DestroyShape(s:b2Shape):void{ if (m_world.m_lock == true){ return; }; s.DestroyProxy(m_world.m_broadPhase); var node:b2Shape = m_shapeList; var ppS:b2Shape; var found:Boolean; while (node != null) { if (node == s){ if (ppS){ ppS.m_next = s.m_next; } else { m_shapeList = s.m_next; }; found = true; break; }; ppS = node; node = node.m_next; }; s.m_body = null; s.m_next = null; m_shapeCount--; b2Shape.Destroy(s, m_world.m_blockAllocator); } public function GetUserData(){ return (m_userData); } public function IsBullet():Boolean{ return (((m_flags & e_bulletFlag) == e_bulletFlag)); } public function GetWorldCenter():b2Vec2{ return (m_sweep.c); } public function AllowSleeping(flag:Boolean):void{ if (flag){ m_flags = (m_flags | e_allowSleepFlag); } else { m_flags = (m_flags & ~(e_allowSleepFlag)); WakeUp(); }; } public function SetUserData(data):void{ m_userData = data; } public function GetLocalVector(worldVector:b2Vec2):b2Vec2{ return (b2Math.b2MulTMV(m_xf.R, worldVector)); } public function GetWorldPoint(localPoint:b2Vec2):b2Vec2{ var A:b2Mat22 = m_xf.R; var u:b2Vec2 = new b2Vec2(((A.col1.x * localPoint.x) + (A.col2.x * localPoint.y)), ((A.col1.y * localPoint.x) + (A.col2.y * localPoint.y))); u.x = (u.x + m_xf.position.x); u.y = (u.y + m_xf.position.y); return (u); } public function GetWorld():b2World{ return (m_world); } public function GetPosition():b2Vec2{ return (m_xf.position); } } }//package Box2D.Dynamics
Section 65
//b2BodyDef (Box2D.Dynamics.b2BodyDef) package Box2D.Dynamics { import Box2D.Common.Math.*; import Box2D.Collision.Shapes.*; public class b2BodyDef { public var angularDamping:Number; public var angle:Number; public var isSleeping:Boolean; public var position:b2Vec2; public var isBullet:Boolean; public var allowSleep:Boolean; public var userData; public var fixedRotation:Boolean; public var linearDamping:Number; public var massData:b2MassData; public function b2BodyDef(){ massData = new b2MassData(); position = new b2Vec2(); super(); massData.center.SetZero(); massData.mass = 0; massData.I = 0; userData = null; position.Set(0, 0); angle = 0; linearDamping = 0; angularDamping = 0; allowSleep = true; isSleeping = false; fixedRotation = false; isBullet = false; } } }//package Box2D.Dynamics
Section 66
//b2BoundaryListener (Box2D.Dynamics.b2BoundaryListener) package Box2D.Dynamics { public class b2BoundaryListener { public function b2BoundaryListener(){ super(); } public function Violation(body:b2Body):void{ } } }//package Box2D.Dynamics
Section 67
//b2ContactFilter (Box2D.Dynamics.b2ContactFilter) package Box2D.Dynamics { import Box2D.Collision.Shapes.*; public class b2ContactFilter { public static var b2_defaultFilter:b2ContactFilter = new (b2ContactFilter); ; public function b2ContactFilter(){ super(); } public function ShouldCollide(shape1:b2Shape, shape2:b2Shape):Boolean{ var filter1:b2FilterData = shape1.GetFilterData(); var filter2:b2FilterData = shape2.GetFilterData(); if ((((filter1.groupIndex == filter2.groupIndex)) && (!((filter1.groupIndex == 0))))){ return ((filter1.groupIndex > 0)); }; var collide:Boolean = ((!(((filter1.maskBits & filter2.categoryBits) == 0))) && (!(((filter1.categoryBits & filter2.maskBits) == 0)))); return (collide); } public function RayCollide(userData, shape:b2Shape):Boolean{ if (!userData){ return (true); }; return (ShouldCollide((userData as b2Shape), shape)); } } }//package Box2D.Dynamics
Section 68
//b2ContactListener (Box2D.Dynamics.b2ContactListener) package Box2D.Dynamics { import Box2D.Collision.*; import Box2D.Dynamics.Contacts.*; public class b2ContactListener { public function b2ContactListener(){ super(); } public function Add(point:b2ContactPoint):void{ } public function Remove(point:b2ContactPoint):void{ } public function Persist(point:b2ContactPoint):void{ } public function Result(point:b2ContactResult):void{ } } }//package Box2D.Dynamics
Section 69
//b2ContactManager (Box2D.Dynamics.b2ContactManager) package Box2D.Dynamics { import Box2D.Collision.*; import Box2D.Common.Math.*; import Box2D.Collision.Shapes.*; import Box2D.Dynamics.Contacts.*; public class b2ContactManager extends b2PairCallback { public var m_world:b2World; public var m_destroyImmediate:Boolean; public var m_nullContact:b2NullContact; private static const s_evalCP:b2ContactPoint = new b2ContactPoint(); public function b2ContactManager(){ m_nullContact = new b2NullContact(); super(); m_world = null; m_destroyImmediate = false; } override public function PairRemoved(proxyUserData1, proxyUserData2, pairUserData):void{ if (pairUserData == null){ return; }; var c:b2Contact = (pairUserData as b2Contact); if (c == m_nullContact){ return; }; Destroy(c); } public function Destroy(c:b2Contact):void{ var b1:b2Body; var b2:b2Body; var manifolds:Array; var cp:b2ContactPoint; var i:int; var manifold:b2Manifold; var j:int; var mp:b2ManifoldPoint; var v1:b2Vec2; var v2:b2Vec2; var shape1:b2Shape = c.m_shape1; var shape2:b2Shape = c.m_shape2; var manifoldCount:int = c.m_manifoldCount; if ((((manifoldCount > 0)) && (m_world.m_contactListener))){ b1 = shape1.m_body; b2 = shape2.m_body; manifolds = c.GetManifolds(); cp = s_evalCP; cp.shape1 = c.m_shape1; cp.shape2 = c.m_shape1; cp.friction = c.m_friction; cp.restitution = c.m_restitution; i = 0; while (i < manifoldCount) { manifold = manifolds[i]; cp.normal.SetV(manifold.normal); j = 0; while (j < manifold.pointCount) { mp = manifold.points[j]; cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.separation = mp.separation; cp.id.key = mp.id._key; m_world.m_contactListener.Remove(cp); j++; }; i++; }; }; 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 == m_world.m_contactList){ m_world.m_contactList = c.m_next; }; var body1:b2Body = shape1.m_body; var body2:b2Body = shape2.m_body; if (c.m_node1.prev){ c.m_node1.prev.next = c.m_node1.next; }; if (c.m_node1.next){ c.m_node1.next.prev = c.m_node1.prev; }; if (c.m_node1 == body1.m_contactList){ body1.m_contactList = c.m_node1.next; }; if (c.m_node2.prev){ c.m_node2.prev.next = c.m_node2.next; }; if (c.m_node2.next){ c.m_node2.next.prev = c.m_node2.prev; }; if (c.m_node2 == body2.m_contactList){ body2.m_contactList = c.m_node2.next; }; b2Contact.Destroy(c, m_world.m_blockAllocator); m_world.m_contactCount--; } override public function PairAdded(proxyUserData1, proxyUserData2){ var body1:b2Body; var shape1:b2Shape = (proxyUserData1 as b2Shape); var shape2:b2Shape = (proxyUserData2 as b2Shape); body1 = shape1.m_body; var body2:b2Body = shape2.m_body; if (((body1.IsStatic()) && (body2.IsStatic()))){ return (m_nullContact); }; if (shape1.m_body == shape2.m_body){ return (m_nullContact); }; if (body2.IsConnected(body1)){ return (m_nullContact); }; if (((!((m_world.m_contactFilter == null))) && ((m_world.m_contactFilter.ShouldCollide(shape1, shape2) == false)))){ return (m_nullContact); }; var c:b2Contact = b2Contact.Create(shape1, shape2, m_world.m_blockAllocator); if (c == null){ return (m_nullContact); }; shape1 = c.m_shape1; shape2 = c.m_shape2; body1 = shape1.m_body; body2 = shape2.m_body; c.m_prev = null; c.m_next = m_world.m_contactList; if (m_world.m_contactList != null){ m_world.m_contactList.m_prev = c; }; m_world.m_contactList = c; c.m_node1.contact = c; c.m_node1.other = body2; c.m_node1.prev = null; c.m_node1.next = body1.m_contactList; if (body1.m_contactList != null){ body1.m_contactList.prev = c.m_node1; }; body1.m_contactList = c.m_node1; c.m_node2.contact = c; c.m_node2.other = body1; c.m_node2.prev = null; c.m_node2.next = body2.m_contactList; if (body2.m_contactList != null){ body2.m_contactList.prev = c.m_node2; }; body2.m_contactList = c.m_node2; m_world.m_contactCount++; return (c); } public function Collide():void{ var body1:b2Body; var body2:b2Body; var c:b2Contact = m_world.m_contactList; while (c) { body1 = c.m_shape1.m_body; body2 = c.m_shape2.m_body; if (((body1.IsSleeping()) && (body2.IsSleeping()))){ } else { c.Update(m_world.m_contactListener); }; c = c.m_next; }; } } }//package Box2D.Dynamics
Section 70
//b2DebugDraw (Box2D.Dynamics.b2DebugDraw) package Box2D.Dynamics { import flash.display.*; import Box2D.Collision.*; import Box2D.Common.Math.*; import Box2D.Collision.Shapes.*; import Box2D.Common.*; import Box2D.Dynamics.Contacts.*; public class b2DebugDraw { public var m_xformScale:Number;// = 1 public var m_fillAlpha:Number;// = 1 public var m_alpha:Number;// = 1 public var m_drawFlags:uint; public var m_lineThickness:Number;// = 1 public var m_drawScale:Number;// = 1 public var m_sprite:Sprite; public static var e_coreShapeBit:uint = 4; public static var e_shapeBit:uint = 1; public static var e_centerOfMassBit:uint = 64; public static var e_aabbBit:uint = 8; public static var e_obbBit:uint = 16; public static var e_pairBit:uint = 32; public static var e_jointBit:uint = 2; public function b2DebugDraw(){ super(); m_drawFlags = 0; } public function ClearFlags(flags:uint):void{ m_drawFlags = (m_drawFlags & ~(flags)); } public function SetFlags(flags:uint):void{ m_drawFlags = flags; } public function AppendFlags(flags:uint):void{ m_drawFlags = (m_drawFlags | flags); } public function DrawSegment(p1:b2Vec2, p2:b2Vec2, color:b2Color):void{ m_sprite.graphics.lineStyle(m_lineThickness, color.color, m_alpha); m_sprite.graphics.moveTo((p1.x * m_drawScale), (p1.y * m_drawScale)); m_sprite.graphics.lineTo((p2.x * m_drawScale), (p2.y * m_drawScale)); } public function DrawSolidPolygon(vertices:Array, vertexCount:int, color:b2Color):void{ m_sprite.graphics.lineStyle(m_lineThickness, color.color, m_alpha); m_sprite.graphics.moveTo((vertices[0].x * m_drawScale), (vertices[0].y * m_drawScale)); m_sprite.graphics.beginFill(color.color, m_fillAlpha); var i = 1; while (i < vertexCount) { m_sprite.graphics.lineTo((vertices[i].x * m_drawScale), (vertices[i].y * m_drawScale)); i++; }; m_sprite.graphics.lineTo((vertices[0].x * m_drawScale), (vertices[0].y * m_drawScale)); m_sprite.graphics.endFill(); } public function DrawCircle(center:b2Vec2, radius:Number, color:b2Color):void{ m_sprite.graphics.lineStyle(m_lineThickness, color.color, m_alpha); m_sprite.graphics.drawCircle((center.x * m_drawScale), (center.y * m_drawScale), (radius * m_drawScale)); } public function DrawPolygon(vertices:Array, vertexCount:int, color:b2Color):void{ m_sprite.graphics.lineStyle(m_lineThickness, color.color, m_alpha); m_sprite.graphics.moveTo((vertices[0].x * m_drawScale), (vertices[0].y * m_drawScale)); var i = 1; while (i < vertexCount) { m_sprite.graphics.lineTo((vertices[i].x * m_drawScale), (vertices[i].y * m_drawScale)); i++; }; m_sprite.graphics.lineTo((vertices[0].x * m_drawScale), (vertices[0].y * m_drawScale)); } public function DrawSolidCircle(center:b2Vec2, radius:Number, axis:b2Vec2, color:b2Color):void{ m_sprite.graphics.lineStyle(m_lineThickness, color.color, m_alpha); m_sprite.graphics.moveTo(0, 0); m_sprite.graphics.beginFill(color.color, m_fillAlpha); m_sprite.graphics.drawCircle((center.x * m_drawScale), (center.y * m_drawScale), (radius * m_drawScale)); m_sprite.graphics.endFill(); m_sprite.graphics.moveTo((center.x * m_drawScale), (center.y * m_drawScale)); m_sprite.graphics.lineTo(((center.x + (axis.x * radius)) * m_drawScale), ((center.y + (axis.y * radius)) * m_drawScale)); } public function GetFlags():uint{ return (m_drawFlags); } public function DrawXForm(xf:b2XForm):void{ m_sprite.graphics.lineStyle(m_lineThickness, 0xFF0000, m_alpha); m_sprite.graphics.moveTo((xf.position.x * m_drawScale), (xf.position.y * m_drawScale)); m_sprite.graphics.lineTo(((xf.position.x + (m_xformScale * xf.R.col1.x)) * m_drawScale), ((xf.position.y + (m_xformScale * xf.R.col1.y)) * m_drawScale)); m_sprite.graphics.lineStyle(m_lineThickness, 0xFF00, m_alpha); m_sprite.graphics.moveTo((xf.position.x * m_drawScale), (xf.position.y * m_drawScale)); m_sprite.graphics.lineTo(((xf.position.x + (m_xformScale * xf.R.col2.x)) * m_drawScale), ((xf.position.y + (m_xformScale * xf.R.col2.y)) * m_drawScale)); } } }//package Box2D.Dynamics
Section 71
//b2DestructionListener (Box2D.Dynamics.b2DestructionListener) package Box2D.Dynamics { import Box2D.Dynamics.Joints.*; import Box2D.Collision.Shapes.*; public class b2DestructionListener { public function b2DestructionListener(){ super(); } public function SayGoodbyeShape(shape:b2Shape):void{ } public function SayGoodbyeJoint(joint:b2Joint):void{ } } }//package Box2D.Dynamics
Section 72
//b2Island (Box2D.Dynamics.b2Island) package Box2D.Dynamics { import Box2D.Collision.*; import Box2D.Common.Math.*; import Box2D.Dynamics.Joints.*; import Box2D.Common.*; import Box2D.Dynamics.Contacts.*; public class b2Island { public var m_listener:b2ContactListener; public var m_positionIterationCount:int; public var m_bodyCapacity:int; public var m_bodies:Array; public var m_joints:Array; public var m_jointCapacity:int; public var m_contactCount:int; public var m_contacts:Array; public var m_contactCapacity:int; public var m_jointCount:int; public var m_allocator; public var m_bodyCount:int; private static var s_reportCR:b2ContactResult = new b2ContactResult(); public function b2Island(bodyCapacity:int, contactCapacity:int, jointCapacity:int, allocator, listener:b2ContactListener){ var i:int; super(); m_bodyCapacity = bodyCapacity; m_contactCapacity = contactCapacity; m_jointCapacity = jointCapacity; m_bodyCount = 0; m_contactCount = 0; m_jointCount = 0; m_allocator = allocator; m_listener = listener; m_bodies = new Array(bodyCapacity); i = 0; while (i < bodyCapacity) { m_bodies[i] = null; i++; }; m_contacts = new Array(contactCapacity); i = 0; while (i < contactCapacity) { m_contacts[i] = null; i++; }; m_joints = new Array(jointCapacity); i = 0; while (i < jointCapacity) { m_joints[i] = null; i++; }; m_positionIterationCount = 0; } public function AddBody(body:b2Body):void{ var _local2 = m_bodyCount++; m_bodies[_local2] = body; } public function AddJoint(joint:b2Joint):void{ var _local2 = m_jointCount++; m_joints[_local2] = joint; } public function Report(constraints:Array):void{ var tMat:b2Mat22; var tVec:b2Vec2; var c:b2Contact; var cc:b2ContactConstraint; var cr:b2ContactResult; var b1:b2Body; var manifoldCount:int; var manifolds:Array; var j:int; var manifold:b2Manifold; var k:int; var point:b2ManifoldPoint; var ccp:b2ContactConstraintPoint; if (m_listener == null){ return; }; var i:int; while (i < m_contactCount) { c = m_contacts[i]; cc = constraints[i]; cr = s_reportCR; cr.shape1 = c.m_shape1; cr.shape2 = c.m_shape2; b1 = cr.shape1.m_body; manifoldCount = c.m_manifoldCount; manifolds = c.GetManifolds(); j = 0; while (j < manifoldCount) { manifold = manifolds[j]; cr.normal.SetV(manifold.normal); k = 0; while (k < manifold.pointCount) { point = manifold.points[k]; ccp = cc.points[k]; cr.position = b1.GetWorldPoint(point.localPoint1); cr.normalImpulse = ccp.normalImpulse; cr.tangentImpulse = ccp.tangentImpulse; cr.id.key = point.id.key; m_listener.Result(cr); k++; }; j++; }; i++; }; } public function AddContact(contact:b2Contact):void{ var _local2 = m_contactCount++; m_contacts[_local2] = contact; } public function Solve(step:b2TimeStep, gravity:b2Vec2, correctPositions:Boolean, allowSleep:Boolean):void{ var i:int; var b:b2Body; var joint:b2Joint; var j:int; var contactsOkay:Boolean; var jointsOkay:Boolean; var jointOkay:Boolean; var minSleepTime:Number; var linTolSqr:Number; var angTolSqr:Number; i = 0; while (i < m_bodyCount) { b = m_bodies[i]; if (b.IsStatic()){ } else { b.m_linearVelocity.x = (b.m_linearVelocity.x + (step.dt * (gravity.x + (b.m_invMass * b.m_force.x)))); b.m_linearVelocity.y = (b.m_linearVelocity.y + (step.dt * (gravity.y + (b.m_invMass * b.m_force.y)))); b.m_angularVelocity = (b.m_angularVelocity + ((step.dt * b.m_invI) * b.m_torque)); b.m_force.SetZero(); b.m_torque = 0; b.m_linearVelocity.Multiply(b2Math.b2Clamp((1 - (step.dt * b.m_linearDamping)), 0, 1)); b.m_angularVelocity = (b.m_angularVelocity * b2Math.b2Clamp((1 - (step.dt * b.m_angularDamping)), 0, 1)); if (b.m_linearVelocity.LengthSquared() > b2Settings.b2_maxLinearVelocitySquared){ b.m_linearVelocity.Normalize(); b.m_linearVelocity.x = (b.m_linearVelocity.x * b2Settings.b2_maxLinearVelocity); b.m_linearVelocity.y = (b.m_linearVelocity.y * b2Settings.b2_maxLinearVelocity); }; if ((b.m_angularVelocity * b.m_angularVelocity) > b2Settings.b2_maxAngularVelocitySquared){ if (b.m_angularVelocity < 0){ b.m_angularVelocity = -(b2Settings.b2_maxAngularVelocity); } else { b.m_angularVelocity = b2Settings.b2_maxAngularVelocity; }; }; }; i++; }; var contactSolver:b2ContactSolver = new b2ContactSolver(step, m_contacts, m_contactCount, m_allocator); contactSolver.InitVelocityConstraints(step); i = 0; while (i < m_jointCount) { joint = m_joints[i]; joint.InitVelocityConstraints(step); i++; }; i = 0; while (i < step.maxIterations) { contactSolver.SolveVelocityConstraints(); j = 0; while (j < m_jointCount) { joint = m_joints[j]; joint.SolveVelocityConstraints(step); j++; }; i++; }; contactSolver.FinalizeVelocityConstraints(); i = 0; while (i < m_bodyCount) { b = m_bodies[i]; if (b.IsStatic()){ } else { b.m_sweep.c0.SetV(b.m_sweep.c); b.m_sweep.a0 = b.m_sweep.a; b.m_sweep.c.x = (b.m_sweep.c.x + (step.dt * b.m_linearVelocity.x)); b.m_sweep.c.y = (b.m_sweep.c.y + (step.dt * b.m_linearVelocity.y)); b.m_sweep.a = (b.m_sweep.a + (step.dt * b.m_angularVelocity)); b.SynchronizeTransform(); }; i++; }; if (correctPositions){ i = 0; while (i < m_jointCount) { joint = m_joints[i]; joint.InitPositionConstraints(); i++; }; m_positionIterationCount = 0; while (m_positionIterationCount < step.maxIterations) { contactsOkay = contactSolver.SolvePositionConstraints(b2Settings.b2_contactBaumgarte); jointsOkay = true; i = 0; while (i < m_jointCount) { joint = m_joints[i]; jointOkay = joint.SolvePositionConstraints(); jointsOkay = ((jointsOkay) && (jointOkay)); i++; }; if (((contactsOkay) && (jointsOkay))){ break; }; m_positionIterationCount++; }; }; Report(contactSolver.m_constraints); if (allowSleep){ minSleepTime = Number.MAX_VALUE; linTolSqr = (b2Settings.b2_linearSleepTolerance * b2Settings.b2_linearSleepTolerance); angTolSqr = (b2Settings.b2_angularSleepTolerance * b2Settings.b2_angularSleepTolerance); i = 0; while (i < m_bodyCount) { b = m_bodies[i]; if (b.m_invMass == 0){ } else { if ((b.m_flags & b2Body.e_allowSleepFlag) == 0){ b.m_sleepTime = 0; minSleepTime = 0; }; if (((((((b.m_flags & b2Body.e_allowSleepFlag) == 0)) || (((b.m_angularVelocity * b.m_angularVelocity) > angTolSqr)))) || ((b2Math.b2Dot(b.m_linearVelocity, b.m_linearVelocity) > linTolSqr)))){ b.m_sleepTime = 0; minSleepTime = 0; } else { b.m_sleepTime = (b.m_sleepTime + step.dt); minSleepTime = b2Math.b2Min(minSleepTime, b.m_sleepTime); }; }; i++; }; if (minSleepTime >= b2Settings.b2_timeToSleep){ i = 0; while (i < m_bodyCount) { b = m_bodies[i]; b.m_flags = (b.m_flags | b2Body.e_sleepFlag); b.m_linearVelocity.SetZero(); b.m_angularVelocity = 0; i++; }; }; }; } public function Clear():void{ m_bodyCount = 0; m_contactCount = 0; m_jointCount = 0; } public function SolveTOI(subStep:b2TimeStep):void{ var i:int; var b:b2Body; var contactsOkay:Boolean; var contactSolver:b2ContactSolver = new b2ContactSolver(subStep, m_contacts, m_contactCount, m_allocator); i = 0; while (i < subStep.maxIterations) { contactSolver.SolveVelocityConstraints(); i++; }; i = 0; while (i < m_bodyCount) { b = m_bodies[i]; if (b.IsStatic()){ } else { b.m_sweep.c0.SetV(b.m_sweep.c); b.m_sweep.a0 = b.m_sweep.a; b.m_sweep.c.x = (b.m_sweep.c.x + (subStep.dt * b.m_linearVelocity.x)); b.m_sweep.c.y = (b.m_sweep.c.y + (subStep.dt * b.m_linearVelocity.y)); b.m_sweep.a = (b.m_sweep.a + (subStep.dt * b.m_angularVelocity)); b.SynchronizeTransform(); }; i++; }; var k_toiBaumgarte:Number = 0.75; i = 0; while (i < subStep.maxIterations) { contactsOkay = contactSolver.SolvePositionConstraints(k_toiBaumgarte); if (contactsOkay){ break; }; i++; }; Report(contactSolver.m_constraints); } } }//package Box2D.Dynamics
Section 73
//b2TimeStep (Box2D.Dynamics.b2TimeStep) package Box2D.Dynamics { public class b2TimeStep { public var warmStarting:Boolean; public var positionCorrection:Boolean; public var dt:Number; public var maxIterations:int; public var dtRatio:Number; public var inv_dt:Number; public function b2TimeStep(){ super(); } } }//package Box2D.Dynamics
Section 74
//b2World (Box2D.Dynamics.b2World) package Box2D.Dynamics { import Box2D.Collision.*; import Box2D.Common.Math.*; import Box2D.Dynamics.Joints.*; import Box2D.Collision.Shapes.*; import Box2D.Common.*; import Box2D.Dynamics.Contacts.*; public class b2World { public var m_inv_dt0:Number; public var m_boundaryListener:b2BoundaryListener; public var m_contactList:b2Contact; public var m_blockAllocator; public var m_contactListener:b2ContactListener; public var m_raycastSegment:b2Segment; public var m_broadPhase:b2BroadPhase; public var m_destructionListener:b2DestructionListener; public var m_jointCount:int; public var m_lock:Boolean; public var m_bodyCount:int; public var m_raycastUserData; public var m_allowSleep:Boolean; public var m_positionIterationCount:int; public var m_groundBody:b2Body; public var m_contactCount:int; public var m_raycastNormal:b2Vec2; public var m_contactFilter:b2ContactFilter; public var m_bodyList:b2Body; public var m_debugDraw:b2DebugDraw; public var m_stackAllocator; public var m_jointList:b2Joint; public var m_gravity:b2Vec2; public var m_contactManager:b2ContactManager; private static var s_jointColor:b2Color = new b2Color(0.5, 0.8, 0.8); public static var m_continuousPhysics:Boolean; public static var m_warmStarting:Boolean; private static var s_coreColor:b2Color = new b2Color(0.9, 0.6, 0.6); public static var m_positionCorrection:Boolean; private static var s_xf:b2XForm = new b2XForm(); public function b2World(worldAABB:b2AABB, gravity:b2Vec2, doSleep:Boolean){ m_raycastNormal = new b2Vec2(); m_contactManager = new b2ContactManager(); super(); m_destructionListener = null; m_boundaryListener = null; m_contactFilter = b2ContactFilter.b2_defaultFilter; m_contactListener = null; m_debugDraw = null; m_bodyList = null; m_contactList = null; m_jointList = null; m_bodyCount = 0; m_contactCount = 0; m_jointCount = 0; m_positionCorrection = true; m_warmStarting = true; m_continuousPhysics = true; m_allowSleep = doSleep; m_gravity = gravity; m_lock = false; m_inv_dt0 = 0; m_contactManager.m_world = this; m_broadPhase = new b2BroadPhase(worldAABB, m_contactManager); var bd:b2BodyDef = new b2BodyDef(); m_groundBody = CreateBody(bd); } public function DrawJoint(joint:b2Joint):void{ var pulley:b2PulleyJoint; var s1:b2Vec2; var s2:b2Vec2; var b1:b2Body = joint.m_body1; var b2:b2Body = joint.m_body2; var xf1:b2XForm = b1.m_xf; var xf2:b2XForm = b2.m_xf; var x1:b2Vec2 = xf1.position; var x2:b2Vec2 = xf2.position; var p1:b2Vec2 = joint.GetAnchor1(); var p2:b2Vec2 = joint.GetAnchor2(); var color:b2Color = s_jointColor; switch (joint.m_type){ case b2Joint.e_distanceJoint: m_debugDraw.DrawSegment(p1, p2, color); break; case b2Joint.e_pulleyJoint: pulley = (joint as b2PulleyJoint); s1 = pulley.GetGroundAnchor1(); s2 = pulley.GetGroundAnchor2(); m_debugDraw.DrawSegment(s1, p1, color); m_debugDraw.DrawSegment(s2, p2, color); m_debugDraw.DrawSegment(s1, s2, color); break; case b2Joint.e_mouseJoint: m_debugDraw.DrawSegment(p1, p2, color); break; default: if (b1 != m_groundBody){ m_debugDraw.DrawSegment(x1, p1, color); }; m_debugDraw.DrawSegment(p1, p2, color); if (b2 != m_groundBody){ m_debugDraw.DrawSegment(x2, p2, color); }; }; } public function Refilter(shape:b2Shape):void{ shape.RefilterProxy(m_broadPhase, shape.m_body.m_xf); } public function SetDebugDraw(debugDraw:b2DebugDraw):void{ m_debugDraw = debugDraw; } public function SetContinuousPhysics(flag:Boolean):void{ m_continuousPhysics = flag; } public function GetProxyCount():int{ return (m_broadPhase.m_proxyCount); } public function DrawDebugData():void{ var i:int; var b:b2Body; var s:b2Shape; var j:b2Joint; var bp:b2BroadPhase; var xf:b2XForm; var core:Boolean; var index:uint; var pair:b2Pair; var p1:b2Proxy; var p2:b2Proxy; var worldLower:b2Vec2; var worldUpper:b2Vec2; var p:b2Proxy; var poly:b2PolygonShape; var obb:b2OBB; var h:b2Vec2; var tMat:b2Mat22; var tVec:b2Vec2; var tX:Number; if (m_debugDraw == null){ return; }; m_debugDraw.m_sprite.graphics.clear(); var flags:uint = m_debugDraw.GetFlags(); var invQ:b2Vec2 = new b2Vec2(); var x1:b2Vec2 = new b2Vec2(); var x2:b2Vec2 = new b2Vec2(); var color:b2Color = new b2Color(0, 0, 0); var b1:b2AABB = new b2AABB(); var b2:b2AABB = new b2AABB(); var vs:Array = [new b2Vec2(), new b2Vec2(), new b2Vec2(), new b2Vec2()]; if ((flags & b2DebugDraw.e_shapeBit)){ core = ((flags & b2DebugDraw.e_coreShapeBit) == b2DebugDraw.e_coreShapeBit); b = m_bodyList; while (b) { xf = b.m_xf; s = b.GetShapeList(); while (s) { if (b.IsStatic()){ DrawShape(s, xf, new b2Color(0.5, 0.9, 0.5), core); } else { if (b.IsSleeping()){ DrawShape(s, xf, new b2Color(0.5, 0.5, 0.9), core); } else { DrawShape(s, xf, new b2Color(0.9, 0.9, 0.9), core); }; }; s = s.m_next; }; b = b.m_next; }; }; if ((flags & b2DebugDraw.e_jointBit)){ j = m_jointList; while (j) { DrawJoint(j); j = j.m_next; }; }; if ((flags & b2DebugDraw.e_pairBit)){ bp = m_broadPhase; invQ.Set((1 / bp.m_quantizationFactor.x), (1 / bp.m_quantizationFactor.y)); color.Set(0.9, 0.9, 0.3); i = 0; while (i < b2Pair.b2_tableCapacity) { index = bp.m_pairManager.m_hashTable[i]; while (index != b2Pair.b2_nullPair) { pair = bp.m_pairManager.m_pairs[index]; p1 = bp.m_proxyPool[pair.proxyId1]; p2 = bp.m_proxyPool[pair.proxyId2]; b1.lowerBound.x = (bp.m_worldAABB.lowerBound.x + (invQ.x * bp.m_bounds[0][p1.lowerBounds[0]].value)); b1.lowerBound.y = (bp.m_worldAABB.lowerBound.y + (invQ.y * bp.m_bounds[1][p1.lowerBounds[1]].value)); b1.upperBound.x = (bp.m_worldAABB.lowerBound.x + (invQ.x * bp.m_bounds[0][p1.upperBounds[0]].value)); b1.upperBound.y = (bp.m_worldAABB.lowerBound.y + (invQ.y * bp.m_bounds[1][p1.upperBounds[1]].value)); b2.lowerBound.x = (bp.m_worldAABB.lowerBound.x + (invQ.x * bp.m_bounds[0][p2.lowerBounds[0]].value)); b2.lowerBound.y = (bp.m_worldAABB.lowerBound.y + (invQ.y * bp.m_bounds[1][p2.lowerBounds[1]].value)); b2.upperBound.x = (bp.m_worldAABB.lowerBound.x + (invQ.x * bp.m_bounds[0][p2.upperBounds[0]].value)); b2.upperBound.y = (bp.m_worldAABB.lowerBound.y + (invQ.y * bp.m_bounds[1][p2.upperBounds[1]].value)); x1.x = (0.5 * (b1.lowerBound.x + b1.upperBound.x)); x1.y = (0.5 * (b1.lowerBound.y + b1.upperBound.y)); x2.x = (0.5 * (b2.lowerBound.x + b2.upperBound.x)); x2.y = (0.5 * (b2.lowerBound.y + b2.upperBound.y)); m_debugDraw.DrawSegment(x1, x2, color); index = pair.next; }; i++; }; }; if ((flags & b2DebugDraw.e_aabbBit)){ bp = m_broadPhase; worldLower = bp.m_worldAABB.lowerBound; worldUpper = bp.m_worldAABB.upperBound; invQ.Set((1 / bp.m_quantizationFactor.x), (1 / bp.m_quantizationFactor.y)); color.Set(0.9, 0.3, 0.9); i = 0; while (i < b2Settings.b2_maxProxies) { p = bp.m_proxyPool[i]; if (p.IsValid() == false){ } else { b1.lowerBound.x = (worldLower.x + (invQ.x * bp.m_bounds[0][p.lowerBounds[0]].value)); b1.lowerBound.y = (worldLower.y + (invQ.y * bp.m_bounds[1][p.lowerBounds[1]].value)); b1.upperBound.x = (worldLower.x + (invQ.x * bp.m_bounds[0][p.upperBounds[0]].value)); b1.upperBound.y = (worldLower.y + (invQ.y * bp.m_bounds[1][p.upperBounds[1]].value)); vs[0].Set(b1.lowerBound.x, b1.lowerBound.y); vs[1].Set(b1.upperBound.x, b1.lowerBound.y); vs[2].Set(b1.upperBound.x, b1.upperBound.y); vs[3].Set(b1.lowerBound.x, b1.upperBound.y); m_debugDraw.DrawPolygon(vs, 4, color); }; i++; }; vs[0].Set(worldLower.x, worldLower.y); vs[1].Set(worldUpper.x, worldLower.y); vs[2].Set(worldUpper.x, worldUpper.y); vs[3].Set(worldLower.x, worldUpper.y); m_debugDraw.DrawPolygon(vs, 4, new b2Color(0.3, 0.9, 0.9)); }; if ((flags & b2DebugDraw.e_obbBit)){ color.Set(0.5, 0.3, 0.5); b = m_bodyList; while (b) { xf = b.m_xf; s = b.GetShapeList(); while (s) { if (s.m_type != b2Shape.e_polygonShape){ } else { poly = (s as b2PolygonShape); obb = poly.GetOBB(); h = obb.extents; vs[0].Set(-(h.x), -(h.y)); vs[1].Set(h.x, -(h.y)); vs[2].Set(h.x, h.y); vs[3].Set(-(h.x), h.y); i = 0; while (i < 4) { tMat = obb.R; tVec = vs[i]; tX = (obb.center.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); vs[i].y = (obb.center.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); vs[i].x = tX; tMat = xf.R; tX = (xf.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); vs[i].y = (xf.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); vs[i].x = tX; i++; }; m_debugDraw.DrawPolygon(vs, 4, color); }; s = s.m_next; }; b = b.m_next; }; }; if ((flags & b2DebugDraw.e_centerOfMassBit)){ b = m_bodyList; while (b) { xf = s_xf; xf.R = b.m_xf.R; xf.position = b.GetWorldCenter(); m_debugDraw.DrawXForm(xf); b = b.m_next; }; }; } public function DestroyBody(b:b2Body):void{ var jn0:b2JointEdge; var s0:b2Shape; if (m_lock == true){ return; }; var jn:b2JointEdge = b.m_jointList; while (jn) { jn0 = jn; jn = jn.next; if (m_destructionListener){ m_destructionListener.SayGoodbyeJoint(jn0.joint); }; DestroyJoint(jn0.joint); }; var s:b2Shape = b.m_shapeList; while (s) { s0 = s; s = s.m_next; if (m_destructionListener){ m_destructionListener.SayGoodbyeShape(s0); }; s0.DestroyProxy(m_broadPhase); b2Shape.Destroy(s0, m_blockAllocator); }; if (b.m_prev){ b.m_prev.m_next = b.m_next; }; if (b.m_next){ b.m_next.m_prev = b.m_prev; }; if (b == m_bodyList){ m_bodyList = b.m_next; }; m_bodyCount--; } public function DrawShape(shape:b2Shape, xf:b2XForm, color:b2Color, core:Boolean):void{ var circle:b2CircleShape; var center:b2Vec2; var radius:Number; var axis:b2Vec2; var i:int; var poly:b2PolygonShape; var vertexCount:int; var localVertices:Array; var vertices:Array; var localCoreVertices:Array; var coreColor:b2Color = s_coreColor; switch (shape.m_type){ case b2Shape.e_circleShape: circle = (shape as b2CircleShape); center = b2Math.b2MulX(xf, circle.m_localPosition); radius = circle.m_radius; axis = xf.R.col1; m_debugDraw.DrawSolidCircle(center, radius, axis, color); if (core){ m_debugDraw.DrawCircle(center, (radius - b2Settings.b2_toiSlop), coreColor); }; break; case b2Shape.e_polygonShape: poly = (shape as b2PolygonShape); vertexCount = poly.GetVertexCount(); localVertices = poly.GetVertices(); vertices = new Array(b2Settings.b2_maxPolygonVertices); i = 0; while (i < vertexCount) { vertices[i] = b2Math.b2MulX(xf, localVertices[i]); i++; }; m_debugDraw.DrawSolidPolygon(vertices, vertexCount, color); if (core){ localCoreVertices = poly.GetCoreVertices(); i = 0; while (i < vertexCount) { vertices[i] = b2Math.b2MulX(xf, localCoreVertices[i]); i++; }; m_debugDraw.DrawPolygon(vertices, vertexCount, coreColor); }; break; }; } public function GetGroundBody():b2Body{ return (m_groundBody); } public function SetContactFilter(filter:b2ContactFilter):void{ m_contactFilter = filter; } public function Solve(step:b2TimeStep):void{ var b:b2Body; var stackCount:int; var i:int; var other:b2Body; var cn:b2ContactEdge; var jn:b2JointEdge; var inRange:Boolean; m_positionIterationCount = 0; var island:b2Island = new b2Island(m_bodyCount, m_contactCount, m_jointCount, m_stackAllocator, m_contactListener); b = m_bodyList; while (b) { b.m_flags = (b.m_flags & ~(b2Body.e_islandFlag)); b = b.m_next; }; var c:b2Contact = m_contactList; while (c) { c.m_flags = (c.m_flags & ~(b2Contact.e_islandFlag)); c = c.m_next; }; var j:b2Joint = m_jointList; while (j) { j.m_islandFlag = false; j = j.m_next; }; var stackSize:int = m_bodyCount; var stack:Array = new Array(stackSize); var seed:b2Body = m_bodyList; while (seed) { if ((seed.m_flags & ((b2Body.e_islandFlag | b2Body.e_sleepFlag) | b2Body.e_frozenFlag))){ } else { if (seed.IsStatic()){ } else { island.Clear(); stackCount = 0; var _temp1 = stackCount; stackCount = (stackCount + 1); var _local15 = _temp1; stack[_local15] = seed; seed.m_flags = (seed.m_flags | b2Body.e_islandFlag); while (stackCount > 0) { --stackCount; b = stack[stackCount]; island.AddBody(b); b.m_flags = (b.m_flags & ~(b2Body.e_sleepFlag)); if (b.IsStatic()){ } else { cn = b.m_contactList; while (cn) { if ((cn.contact.m_flags & (b2Contact.e_islandFlag | b2Contact.e_nonSolidFlag))){ } else { if (cn.contact.m_manifoldCount == 0){ } else { island.AddContact(cn.contact); cn.contact.m_flags = (cn.contact.m_flags | b2Contact.e_islandFlag); other = cn.other; if ((other.m_flags & b2Body.e_islandFlag)){ } else { var _temp2 = stackCount; stackCount = (stackCount + 1); var _local16 = _temp2; stack[_local16] = other; other.m_flags = (other.m_flags | b2Body.e_islandFlag); }; }; }; cn = cn.next; }; jn = b.m_jointList; while (jn) { if (jn.joint.m_islandFlag == true){ } else { island.AddJoint(jn.joint); jn.joint.m_islandFlag = true; other = jn.other; if ((other.m_flags & b2Body.e_islandFlag)){ } else { var _temp3 = stackCount; stackCount = (stackCount + 1); _local16 = _temp3; stack[_local16] = other; other.m_flags = (other.m_flags | b2Body.e_islandFlag); }; }; jn = jn.next; }; }; }; island.Solve(step, m_gravity, m_positionCorrection, m_allowSleep); if (island.m_positionIterationCount > m_positionIterationCount){ m_positionIterationCount = island.m_positionIterationCount; }; i = 0; while (i < island.m_bodyCount) { b = island.m_bodies[i]; if (b.IsStatic()){ b.m_flags = (b.m_flags & ~(b2Body.e_islandFlag)); }; i++; }; }; }; seed = seed.m_next; }; b = m_bodyList; while (b) { if ((b.m_flags & (b2Body.e_sleepFlag | b2Body.e_frozenFlag))){ } else { if (b.IsStatic()){ } else { inRange = b.SynchronizeShapes(); if ((((inRange == false)) && (!((m_boundaryListener == null))))){ m_boundaryListener.Violation(b); }; }; }; b = b.m_next; }; m_broadPhase.Commit(); } public function Query(aabb:b2AABB, shapes:Array, maxCount:int):int{ var results:Array = new Array(maxCount); var count:int = m_broadPhase.QueryAABB(aabb, results, maxCount); var i:int; while (i < count) { shapes[i] = results[i]; i++; }; return (count); } public function GetContactCount():int{ return (m_contactCount); } public function SolveTOI(step:b2TimeStep):void{ var b:b2Body; var s1:b2Shape; var s2:b2Shape; var b1:b2Body; var b2:b2Body; var cn:b2ContactEdge; var c:b2Contact; var minContact:b2Contact; var minTOI:Number; var seed:b2Body; var stackCount:int; var subStep:b2TimeStep; var i:int; var toi:Number; var t0:Number; var other:b2Body; var inRange:Boolean; var island:b2Island = new b2Island(m_bodyCount, b2Settings.b2_maxTOIContactsPerIsland, 0, m_stackAllocator, m_contactListener); var stackSize:int = m_bodyCount; var stack:Array = new Array(stackSize); b = m_bodyList; while (b) { b.m_flags = (b.m_flags & ~(b2Body.e_islandFlag)); b.m_sweep.t0 = 0; b = b.m_next; }; c = m_contactList; while (c) { c.m_flags = (c.m_flags & ~((b2Contact.e_toiFlag | b2Contact.e_islandFlag))); c = c.m_next; }; while (true) { minContact = null; minTOI = 1; c = m_contactList; for (;c;(c = c.m_next)) { if ((c.m_flags & (b2Contact.e_slowFlag | b2Contact.e_nonSolidFlag))){ } else { toi = 1; if ((c.m_flags & b2Contact.e_toiFlag)){ toi = c.m_toi; } else { s1 = c.m_shape1; s2 = c.m_shape2; b1 = s1.m_body; b2 = s2.m_body; if (((((b1.IsStatic()) || (b1.IsSleeping()))) && (((b2.IsStatic()) || (b2.IsSleeping()))))){ continue; }; t0 = b1.m_sweep.t0; if (b1.m_sweep.t0 < b2.m_sweep.t0){ t0 = b2.m_sweep.t0; b1.m_sweep.Advance(t0); } else { if (b2.m_sweep.t0 < b1.m_sweep.t0){ t0 = b1.m_sweep.t0; b2.m_sweep.Advance(t0); }; }; toi = b2TimeOfImpact.TimeOfImpact(c.m_shape1, b1.m_sweep, c.m_shape2, b2.m_sweep); if ((((toi > 0)) && ((toi < 1)))){ toi = (((1 - toi) * t0) + toi); if (toi > 1){ toi = 1; }; }; c.m_toi = toi; c.m_flags = (c.m_flags | b2Contact.e_toiFlag); }; if ((((Number.MIN_VALUE < toi)) && ((toi < minTOI)))){ minContact = c; minTOI = toi; }; }; }; if ((((minContact == null)) || (((1 - (100 * Number.MIN_VALUE)) < minTOI)))){ break; }; s1 = minContact.m_shape1; s2 = minContact.m_shape2; b1 = s1.m_body; b2 = s2.m_body; b1.Advance(minTOI); b2.Advance(minTOI); minContact.Update(m_contactListener); minContact.m_flags = (minContact.m_flags & ~(b2Contact.e_toiFlag)); if (minContact.m_manifoldCount == 0){ } else { seed = b1; if (seed.IsStatic()){ seed = b2; }; island.Clear(); stackCount = 0; var _temp1 = stackCount; stackCount = (stackCount + 1); var _local22 = _temp1; stack[_local22] = seed; seed.m_flags = (seed.m_flags | b2Body.e_islandFlag); while (stackCount > 0) { --stackCount; b = stack[stackCount]; island.AddBody(b); b.m_flags = (b.m_flags & ~(b2Body.e_sleepFlag)); if (b.IsStatic()){ } else { cn = b.m_contactList; while (cn) { if (island.m_contactCount == island.m_contactCapacity){ } else { if ((cn.contact.m_flags & ((b2Contact.e_islandFlag | b2Contact.e_slowFlag) | b2Contact.e_nonSolidFlag))){ } else { if (cn.contact.m_manifoldCount == 0){ } else { island.AddContact(cn.contact); cn.contact.m_flags = (cn.contact.m_flags | b2Contact.e_islandFlag); other = cn.other; if ((other.m_flags & b2Body.e_islandFlag)){ } else { if (other.IsStatic() == false){ other.Advance(minTOI); other.WakeUp(); }; var _temp2 = stackCount; stackCount = (stackCount + 1); var _local23 = _temp2; stack[_local23] = other; other.m_flags = (other.m_flags | b2Body.e_islandFlag); }; }; }; }; cn = cn.next; }; }; }; subStep = new b2TimeStep(); subStep.dt = ((1 - minTOI) * step.dt); subStep.inv_dt = (1 / subStep.dt); subStep.maxIterations = step.maxIterations; island.SolveTOI(subStep); i = 0; while (i < island.m_bodyCount) { b = island.m_bodies[i]; b.m_flags = (b.m_flags & ~(b2Body.e_islandFlag)); if ((b.m_flags & (b2Body.e_sleepFlag | b2Body.e_frozenFlag))){ } else { if (b.IsStatic()){ } else { inRange = b.SynchronizeShapes(); if ((((inRange == false)) && (!((m_boundaryListener == null))))){ m_boundaryListener.Violation(b); }; cn = b.m_contactList; while (cn) { cn.contact.m_flags = (cn.contact.m_flags & ~(b2Contact.e_toiFlag)); cn = cn.next; }; }; }; i++; }; i = 0; while (i < island.m_contactCount) { c = island.m_contacts[i]; c.m_flags = (c.m_flags & ~((b2Contact.e_toiFlag | b2Contact.e_islandFlag))); i++; }; m_broadPhase.Commit(); }; }; } public function GetJointList():b2Joint{ return (m_jointList); } public function Validate():void{ m_broadPhase.Validate(); } public function SetGravity(gravity:b2Vec2):void{ m_gravity = gravity; } public function GetGravity():b2Vec2{ return (m_gravity); } public function GetBodyList():b2Body{ return (m_bodyList); } public function GetPairCount():int{ return (m_broadPhase.m_pairManager.m_pairCount); } public function SetWarmStarting(flag:Boolean):void{ m_warmStarting = flag; } public function SetPositionCorrection(flag:Boolean):void{ m_positionCorrection = flag; } public function CreateJoint(def:b2JointDef):b2Joint{ var b:b2Body; var s:b2Shape; var j:b2Joint = b2Joint.Create(def, m_blockAllocator); j.m_prev = null; j.m_next = m_jointList; if (m_jointList){ m_jointList.m_prev = j; }; m_jointList = j; m_jointCount++; j.m_node1.joint = j; j.m_node1.other = j.m_body2; j.m_node1.prev = null; j.m_node1.next = j.m_body1.m_jointList; if (j.m_body1.m_jointList){ j.m_body1.m_jointList.prev = j.m_node1; }; j.m_body1.m_jointList = j.m_node1; j.m_node2.joint = j; j.m_node2.other = j.m_body1; j.m_node2.prev = null; j.m_node2.next = j.m_body2.m_jointList; if (j.m_body2.m_jointList){ j.m_body2.m_jointList.prev = j.m_node2; }; j.m_body2.m_jointList = j.m_node2; if (def.collideConnected == false){ b = ((def.body1.m_shapeCount < def.body2.m_shapeCount)) ? def.body1 : def.body2; s = b.m_shapeList; while (s) { s.RefilterProxy(m_broadPhase, b.m_xf); s = s.m_next; }; }; return (j); } public function DestroyJoint(j:b2Joint):void{ var b:b2Body; var s:b2Shape; var collideConnected:Boolean = j.m_collideConnected; if (j.m_prev){ j.m_prev.m_next = j.m_next; }; if (j.m_next){ j.m_next.m_prev = j.m_prev; }; if (j == m_jointList){ m_jointList = j.m_next; }; var body1:b2Body = j.m_body1; var body2:b2Body = j.m_body2; body1.WakeUp(); body2.WakeUp(); if (j.m_node1.prev){ j.m_node1.prev.next = j.m_node1.next; }; if (j.m_node1.next){ j.m_node1.next.prev = j.m_node1.prev; }; if (j.m_node1 == body1.m_jointList){ body1.m_jointList = j.m_node1.next; }; j.m_node1.prev = null; j.m_node1.next = null; if (j.m_node2.prev){ j.m_node2.prev.next = j.m_node2.next; }; if (j.m_node2.next){ j.m_node2.next.prev = j.m_node2.prev; }; if (j.m_node2 == body2.m_jointList){ body2.m_jointList = j.m_node2.next; }; j.m_node2.prev = null; j.m_node2.next = null; b2Joint.Destroy(j, m_blockAllocator); m_jointCount--; if (collideConnected == false){ b = ((body1.m_shapeCount < body2.m_shapeCount)) ? body1 : body2; s = b.m_shapeList; while (s) { s.RefilterProxy(m_broadPhase, b.m_xf); s = s.m_next; }; }; } public function SetContactListener(listener:b2ContactListener):void{ m_contactListener = listener; } public function Raycast(segment:b2Segment, shapes:Array, maxCount:int, solidShapes:Boolean, userData):int{ var count:int; var results:Array = new Array(maxCount); m_raycastSegment = segment; m_raycastUserData = userData; if (solidShapes){ count = m_broadPhase.QuerySegment(segment, results, maxCount, RaycastSortKey); } else { count = m_broadPhase.QuerySegment(segment, results, maxCount, RaycastSortKey2); }; var i:int; while (i < count) { shapes[i] = results[i]; i++; }; return (count); } public function RaycastSortKey2(shape:b2Shape){ if (((m_contactFilter) && (!(m_contactFilter.RayCollide(m_raycastUserData, shape))))){ return (-1); }; var body:b2Body = shape.GetBody(); var xf:b2XForm = body.GetXForm(); var lambda:Array = [0]; if (shape.TestSegment(xf, lambda, m_raycastNormal, m_raycastSegment, 1) != b2Shape.e_hitCollide){ return (-1); }; return (lambda[0]); } public function RaycastOne(segment:b2Segment, lambda:Array, normal:b2Vec2, solidShapes:Boolean, userData):b2Shape{ var shapes:Array = new Array(1); var count:Number = Raycast(segment, shapes, 1, solidShapes, userData); if (count == 0){ return (null); }; if (count > 1){ trace(count); }; var shape:b2Shape = shapes[0]; var xf:b2XForm = shape.GetBody().GetXForm(); shape.TestSegment(xf, lambda, normal, segment, 1); return (shape); } public function CreateBody(def:b2BodyDef):b2Body{ if (m_lock == true){ return (null); }; var b:b2Body = new b2Body(def, this); b.m_prev = null; b.m_next = m_bodyList; if (m_bodyList){ m_bodyList.m_prev = b; }; m_bodyList = b; m_bodyCount++; return (b); } public function RaycastSortKey(shape:b2Shape){ if (((m_contactFilter) && (!(m_contactFilter.RayCollide(m_raycastUserData, shape))))){ return (-1); }; var body:b2Body = shape.GetBody(); var xf:b2XForm = body.GetXForm(); var lambda:Array = [0]; if (shape.TestSegment(xf, lambda, m_raycastNormal, m_raycastSegment, 1) == b2Shape.e_missCollide){ return (-1); }; return (lambda[0]); } public function SetBoundaryListener(listener:b2BoundaryListener):void{ m_boundaryListener = listener; } public function SetDestructionListener(listener:b2DestructionListener):void{ m_destructionListener = listener; } public function Step(dt:Number, iterations:int):void{ m_lock = true; var step:b2TimeStep = new b2TimeStep(); step.dt = dt; step.maxIterations = iterations; if (dt > 0){ step.inv_dt = (1 / dt); } else { step.inv_dt = 0; }; step.dtRatio = (m_inv_dt0 * dt); step.positionCorrection = m_positionCorrection; step.warmStarting = m_warmStarting; m_contactManager.Collide(); if (step.dt > 0){ Solve(step); }; if (((m_continuousPhysics) && ((step.dt > 0)))){ SolveTOI(step); }; DrawDebugData(); m_inv_dt0 = step.inv_dt; m_lock = false; } public function GetBodyCount():int{ return (m_bodyCount); } public function GetJointCount():int{ return (m_jointCount); } } }//package Box2D.Dynamics
Section 75
//SoundShortcuts (caurina.transitions.properties.SoundShortcuts) package caurina.transitions.properties { import flash.media.*; import caurina.transitions.*; public class SoundShortcuts { public function SoundShortcuts(){ super(); trace("This is an static class and should not be instantiated."); } public static function init():void{ Tweener.registerSpecialProperty("_sound_volume", _sound_volume_get, _sound_volume_set); Tweener.registerSpecialProperty("_sound_pan", _sound_pan_get, _sound_pan_set); } public static function _sound_pan_set(p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object=null):void{ var sndTransform:SoundTransform = p_obj.soundTransform; sndTransform.pan = p_value; p_obj.soundTransform = sndTransform; } public static function _sound_volume_set(p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object=null):void{ var sndTransform:SoundTransform = p_obj.soundTransform; sndTransform.volume = p_value; p_obj.soundTransform = sndTransform; } public static function _sound_pan_get(p_obj:Object, p_parameters:Array, p_extra:Object=null):Number{ return (p_obj.soundTransform.pan); } public static function _sound_volume_get(p_obj:Object, p_parameters:Array, p_extra:Object=null):Number{ return (p_obj.soundTransform.volume); } } }//package caurina.transitions.properties
Section 76
//AuxFunctions (caurina.transitions.AuxFunctions) package caurina.transitions { public class AuxFunctions { public function AuxFunctions(){ super(); } public static function concatObjects(... _args):Object{ var currentObject:Object; var prop:String; var finalObject:Object = {}; var i:int; while (i < _args.length) { currentObject = _args[i]; for (prop in currentObject) { if (currentObject[prop] == null){ delete finalObject[prop]; } else { finalObject[prop] = currentObject[prop]; }; }; i++; }; return (finalObject); } public static function numberToG(p_num:Number):Number{ return (((p_num & 0xFF00) >> 8)); } public static function numberToR(p_num:Number):Number{ return (((p_num & 0xFF0000) >> 16)); } public static function isInArray(p_string:String, p_array:Array):Boolean{ var l:uint = p_array.length; var i:uint; while (i < l) { if (p_array[i] == p_string){ return (true); }; i++; }; return (false); } public static function getObjectLength(p_object:Object):uint{ var pName:String; var totalProperties:uint; for (pName in p_object) { totalProperties++; }; return (totalProperties); } public static function numberToB(p_num:Number):Number{ return ((p_num & 0xFF)); } } }//package caurina.transitions
Section 77
//Equations (caurina.transitions.Equations) package caurina.transitions { public class Equations { public function Equations(){ super(); trace("Equations is a static class and should not be instantiated."); } public static function easeOutBounce(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / d); if (t < (1 / 2.75)){ return (((c * ((7.5625 * t) * t)) + b)); }; if (t < (2 / 2.75)){ t = (t - (1.5 / 2.75)); return (((c * (((7.5625 * t) * t) + 0.75)) + b)); }; if (t < (2.5 / 2.75)){ t = (t - (2.25 / 2.75)); return (((c * (((7.5625 * t) * t) + 0.9375)) + b)); }; t = (t - (2.625 / 2.75)); return (((c * (((7.5625 * t) * t) + 0.984375)) + b)); } public static function easeInOutElastic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ var s:Number; if (t == 0){ return (b); }; t = (t / (d / 2)); if (t == 2){ return ((b + c)); }; var p:Number = (((!(Boolean(p_params))) || (isNaN(p_params.period)))) ? (d * (0.3 * 1.5)) : p_params.period; var a:Number = (((!(Boolean(p_params))) || (isNaN(p_params.amplitude)))) ? 0 : p_params.amplitude; if (((!(Boolean(a))) || ((a < Math.abs(c))))){ a = c; s = (p / 4); } else { s = ((p / (2 * Math.PI)) * Math.asin((c / a))); }; if (t < 1){ --t; return (((-0.5 * ((a * Math.pow(2, (10 * t))) * Math.sin(((((t * d) - s) * (2 * Math.PI)) / p)))) + b)); }; --t; return ((((((a * Math.pow(2, (-10 * t))) * Math.sin(((((t * d) - s) * (2 * Math.PI)) / p))) * 0.5) + c) + b)); } public static function easeInOutQuad(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / (d / 2)); if (t < 1){ return (((((c / 2) * t) * t) + b)); }; --t; return ((((-(c) / 2) * ((t * (t - 2)) - 1)) + b)); } public static function easeInOutBounce(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (((easeInBounce((t * 2), 0, c, d) * 0.5) + b)); }; return ((((easeOutBounce(((t * 2) - d), 0, c, d) * 0.5) + (c * 0.5)) + b)); } public static function easeInOutBack(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ var s:Number = (((!(Boolean(p_params))) || (isNaN(p_params.overshoot)))) ? 1.70158 : p_params.overshoot; t = (t / (d / 2)); if (t < 1){ s = (s * 1.525); return ((((c / 2) * ((t * t) * (((s + 1) * t) - s))) + b)); }; t = (t - 2); s = (s * 1.525); return ((((c / 2) * (((t * t) * (((s + 1) * t) + s)) + 2)) + b)); } public static function easeOutInCubic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutCubic((t * 2), b, (c / 2), d, p_params)); }; return (easeInCubic(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeNone(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ return ((((c * t) / d) + b)); } public static function easeOutBack(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ var s:Number = (((!(Boolean(p_params))) || (isNaN(p_params.overshoot)))) ? 1.70158 : p_params.overshoot; t = ((t / d) - 1); return (((c * (((t * t) * (((s + 1) * t) + s)) + 1)) + b)); } public static function easeInOutSine(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ return ((((-(c) / 2) * (Math.cos(((Math.PI * t) / d)) - 1)) + b)); } public static function easeInBack(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ var s:Number = (((!(Boolean(p_params))) || (isNaN(p_params.overshoot)))) ? 1.70158 : p_params.overshoot; t = (t / d); return (((((c * t) * t) * (((s + 1) * t) - s)) + b)); } public static function easeInQuart(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / d); return ((((((c * t) * t) * t) * t) + b)); } public static function easeOutInQuint(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutQuint((t * 2), b, (c / 2), d, p_params)); }; return (easeInQuint(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeOutInBounce(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutBounce((t * 2), b, (c / 2), d, p_params)); }; return (easeInBounce(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function init():void{ Tweener.registerTransition("easenone", easeNone); Tweener.registerTransition("linear", easeNone); Tweener.registerTransition("easeinquad", easeInQuad); Tweener.registerTransition("easeoutquad", easeOutQuad); Tweener.registerTransition("easeinoutquad", easeInOutQuad); Tweener.registerTransition("easeoutinquad", easeOutInQuad); Tweener.registerTransition("easeincubic", easeInCubic); Tweener.registerTransition("easeoutcubic", easeOutCubic); Tweener.registerTransition("easeinoutcubic", easeInOutCubic); Tweener.registerTransition("easeoutincubic", easeOutInCubic); Tweener.registerTransition("easeinquart", easeInQuart); Tweener.registerTransition("easeoutquart", easeOutQuart); Tweener.registerTransition("easeinoutquart", easeInOutQuart); Tweener.registerTransition("easeoutinquart", easeOutInQuart); Tweener.registerTransition("easeinquint", easeInQuint); Tweener.registerTransition("easeoutquint", easeOutQuint); Tweener.registerTransition("easeinoutquint", easeInOutQuint); Tweener.registerTransition("easeoutinquint", easeOutInQuint); Tweener.registerTransition("easeinsine", easeInSine); Tweener.registerTransition("easeoutsine", easeOutSine); Tweener.registerTransition("easeinoutsine", easeInOutSine); Tweener.registerTransition("easeoutinsine", easeOutInSine); Tweener.registerTransition("easeincirc", easeInCirc); Tweener.registerTransition("easeoutcirc", easeOutCirc); Tweener.registerTransition("easeinoutcirc", easeInOutCirc); Tweener.registerTransition("easeoutincirc", easeOutInCirc); Tweener.registerTransition("easeinexpo", easeInExpo); Tweener.registerTransition("easeoutexpo", easeOutExpo); Tweener.registerTransition("easeinoutexpo", easeInOutExpo); Tweener.registerTransition("easeoutinexpo", easeOutInExpo); Tweener.registerTransition("easeinelastic", easeInElastic); Tweener.registerTransition("easeoutelastic", easeOutElastic); Tweener.registerTransition("easeinoutelastic", easeInOutElastic); Tweener.registerTransition("easeoutinelastic", easeOutInElastic); Tweener.registerTransition("easeinback", easeInBack); Tweener.registerTransition("easeoutback", easeOutBack); Tweener.registerTransition("easeinoutback", easeInOutBack); Tweener.registerTransition("easeoutinback", easeOutInBack); Tweener.registerTransition("easeinbounce", easeInBounce); Tweener.registerTransition("easeoutbounce", easeOutBounce); Tweener.registerTransition("easeinoutbounce", easeInOutBounce); Tweener.registerTransition("easeoutinbounce", easeOutInBounce); } public static function easeOutExpo(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ return (((t)==d) ? (b + c) : (((c * 1.001) * (-(Math.pow(2, ((-10 * t) / d))) + 1)) + b)); } public static function easeOutInBack(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutBack((t * 2), b, (c / 2), d, p_params)); }; return (easeInBack(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeInExpo(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ return (((t)==0) ? b : (((c * Math.pow(2, (10 * ((t / d) - 1)))) + b) - (c * 0.001))); } public static function easeInCubic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / d); return (((((c * t) * t) * t) + b)); } public static function easeInQuint(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / d); return (((((((c * t) * t) * t) * t) * t) + b)); } public static function easeInOutCirc(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / (d / 2)); if (t < 1){ return ((((-(c) / 2) * (Math.sqrt((1 - (t * t))) - 1)) + b)); }; t = (t - 2); return ((((c / 2) * (Math.sqrt((1 - (t * t))) + 1)) + b)); } public static function easeInQuad(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / d); return ((((c * t) * t) + b)); } public static function easeInBounce(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ return (((c - easeOutBounce((d - t), 0, c, d)) + b)); } public static function easeOutInExpo(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutExpo((t * 2), b, (c / 2), d, p_params)); }; return (easeInExpo(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeOutQuart(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = ((t / d) - 1); return (((-(c) * ((((t * t) * t) * t) - 1)) + b)); } public static function easeInSine(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ return ((((-(c) * Math.cos(((t / d) * (Math.PI / 2)))) + c) + b)); } public static function easeInOutQuart(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / (d / 2)); if (t < 1){ return (((((((c / 2) * t) * t) * t) * t) + b)); }; t = (t - 2); return ((((-(c) / 2) * ((((t * t) * t) * t) - 2)) + b)); } public static function easeOutQuad(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / d); return ((((-(c) * t) * (t - 2)) + b)); } public static function easeOutInElastic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutElastic((t * 2), b, (c / 2), d, p_params)); }; return (easeInElastic(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeInElastic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ var s:Number; if (t == 0){ return (b); }; t = (t / d); if (t == 1){ return ((b + c)); }; var p:Number = (((!(Boolean(p_params))) || (isNaN(p_params.period)))) ? (d * 0.3) : p_params.period; var a:Number = (((!(Boolean(p_params))) || (isNaN(p_params.amplitude)))) ? 0 : p_params.amplitude; if (((!(Boolean(a))) || ((a < Math.abs(c))))){ a = c; s = (p / 4); } else { s = ((p / (2 * Math.PI)) * Math.asin((c / a))); }; --t; return ((-(((a * Math.pow(2, (10 * t))) * Math.sin(((((t * d) - s) * (2 * Math.PI)) / p)))) + b)); } public static function easeOutCubic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = ((t / d) - 1); return (((c * (((t * t) * t) + 1)) + b)); } public static function easeOutQuint(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = ((t / d) - 1); return (((c * (((((t * t) * t) * t) * t) + 1)) + b)); } public static function easeOutInQuad(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutQuad((t * 2), b, (c / 2), d, p_params)); }; return (easeInQuad(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeOutSine(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ return (((c * Math.sin(((t / d) * (Math.PI / 2)))) + b)); } public static function easeInOutCubic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / (d / 2)); if (t < 1){ return ((((((c / 2) * t) * t) * t) + b)); }; t = (t - 2); return ((((c / 2) * (((t * t) * t) + 2)) + b)); } public static function easeInOutQuint(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / (d / 2)); if (t < 1){ return ((((((((c / 2) * t) * t) * t) * t) * t) + b)); }; t = (t - 2); return ((((c / 2) * (((((t * t) * t) * t) * t) + 2)) + b)); } public static function easeInCirc(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / d); return (((-(c) * (Math.sqrt((1 - (t * t))) - 1)) + b)); } public static function easeOutInSine(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutSine((t * 2), b, (c / 2), d, p_params)); }; return (easeInSine(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeInOutExpo(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t == 0){ return (b); }; if (t == d){ return ((b + c)); }; t = (t / (d / 2)); if (t < 1){ return (((((c / 2) * Math.pow(2, (10 * (t - 1)))) + b) - (c * 0.0005))); }; --t; return (((((c / 2) * 1.0005) * (-(Math.pow(2, (-10 * t))) + 2)) + b)); } public static function easeOutElastic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ var s:Number; if (t == 0){ return (b); }; t = (t / d); if (t == 1){ return ((b + c)); }; var p:Number = (((!(Boolean(p_params))) || (isNaN(p_params.period)))) ? (d * 0.3) : p_params.period; var a:Number = (((!(Boolean(p_params))) || (isNaN(p_params.amplitude)))) ? 0 : p_params.amplitude; if (((!(Boolean(a))) || ((a < Math.abs(c))))){ a = c; s = (p / 4); } else { s = ((p / (2 * Math.PI)) * Math.asin((c / a))); }; return (((((a * Math.pow(2, (-10 * t))) * Math.sin(((((t * d) - s) * (2 * Math.PI)) / p))) + c) + b)); } public static function easeOutCirc(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = ((t / d) - 1); return (((c * Math.sqrt((1 - (t * t)))) + b)); } public static function easeOutInQuart(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutQuart((t * 2), b, (c / 2), d, p_params)); }; return (easeInQuart(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeOutInCirc(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutCirc((t * 2), b, (c / 2), d, p_params)); }; return (easeInCirc(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } } }//package caurina.transitions
Section 78
//PropertyInfoObj (caurina.transitions.PropertyInfoObj) package caurina.transitions { public class PropertyInfoObj { public var modifierParameters:Array; public var isSpecialProperty:Boolean; public var valueComplete:Number; public var modifierFunction:Function; public var extra:Object; public var valueStart:Number; public var hasModifier:Boolean; public var arrayIndex:Number; public var originalValueComplete:Object; public function PropertyInfoObj(p_valueStart:Number, p_valueComplete:Number, p_originalValueComplete:Object, p_arrayIndex:Number, p_extra:Object, p_isSpecialProperty:Boolean, p_modifierFunction:Function, p_modifierParameters:Array){ super(); valueStart = p_valueStart; valueComplete = p_valueComplete; originalValueComplete = p_originalValueComplete; arrayIndex = p_arrayIndex; extra = p_extra; isSpecialProperty = p_isSpecialProperty; hasModifier = Boolean(p_modifierFunction); modifierFunction = p_modifierFunction; modifierParameters = p_modifierParameters; } public function toString():String{ var returnStr:String = "\n[PropertyInfoObj "; returnStr = (returnStr + ("valueStart:" + String(valueStart))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("valueComplete:" + String(valueComplete))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("originalValueComplete:" + String(originalValueComplete))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("arrayIndex:" + String(arrayIndex))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("extra:" + String(extra))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("isSpecialProperty:" + String(isSpecialProperty))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("hasModifier:" + String(hasModifier))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("modifierFunction:" + String(modifierFunction))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("modifierParameters:" + String(modifierParameters))); returnStr = (returnStr + "]\n"); return (returnStr); } public function clone():PropertyInfoObj{ var nProperty:PropertyInfoObj = new PropertyInfoObj(valueStart, valueComplete, originalValueComplete, arrayIndex, extra, isSpecialProperty, modifierFunction, modifierParameters); return (nProperty); } } }//package caurina.transitions
Section 79
//SpecialProperty (caurina.transitions.SpecialProperty) package caurina.transitions { public class SpecialProperty { public var parameters:Array; public var getValue:Function; public var preProcess:Function; public var setValue:Function; public function SpecialProperty(p_getFunction:Function, p_setFunction:Function, p_parameters:Array=null, p_preProcessFunction:Function=null){ super(); getValue = p_getFunction; setValue = p_setFunction; parameters = p_parameters; preProcess = p_preProcessFunction; } public function toString():String{ var value:String = ""; value = (value + "[SpecialProperty "); value = (value + ("getValue:" + String(getValue))); value = (value + ", "); value = (value + ("setValue:" + String(setValue))); value = (value + ", "); value = (value + ("parameters:" + String(parameters))); value = (value + ", "); value = (value + ("preProcess:" + String(preProcess))); value = (value + "]"); return (value); } } }//package caurina.transitions
Section 80
//SpecialPropertyModifier (caurina.transitions.SpecialPropertyModifier) package caurina.transitions { public class SpecialPropertyModifier { public var getValue:Function; public var modifyValues:Function; public function SpecialPropertyModifier(p_modifyFunction:Function, p_getFunction:Function){ super(); modifyValues = p_modifyFunction; getValue = p_getFunction; } public function toString():String{ var value:String = ""; value = (value + "[SpecialPropertyModifier "); value = (value + ("modifyValues:" + String(modifyValues))); value = (value + ", "); value = (value + ("getValue:" + String(getValue))); value = (value + "]"); return (value); } } }//package caurina.transitions
Section 81
//SpecialPropertySplitter (caurina.transitions.SpecialPropertySplitter) package caurina.transitions { public class SpecialPropertySplitter { public var parameters:Array; public var splitValues:Function; public function SpecialPropertySplitter(p_splitFunction:Function, p_parameters:Array){ super(); splitValues = p_splitFunction; parameters = p_parameters; } public function toString():String{ var value:String = ""; value = (value + "[SpecialPropertySplitter "); value = (value + ("splitValues:" + String(splitValues))); value = (value + ", "); value = (value + ("parameters:" + String(parameters))); value = (value + "]"); return (value); } } }//package caurina.transitions
Section 82
//Tweener (caurina.transitions.Tweener) package caurina.transitions { import flash.events.*; import flash.display.*; import flash.utils.*; public class Tweener { private static var _timeScale:Number = 1; private static var _currentTimeFrame:Number; private static var _specialPropertySplitterList:Object; private static var _engineExists:Boolean = false; private static var _specialPropertyModifierList:Object; private static var _currentTime:Number; private static var _tweenList:Array; private static var _specialPropertyList:Object; private static var _transitionList:Object; private static var _inited:Boolean = false; private static var __tweener_controller__:MovieClip; public function Tweener(){ super(); trace("Tweener is a static class and should not be instantiated."); } public static function registerSpecialPropertyModifier(p_name:String, p_modifyFunction:Function, p_getFunction:Function):void{ if (!_inited){ init(); }; var spm:SpecialPropertyModifier = new SpecialPropertyModifier(p_modifyFunction, p_getFunction); _specialPropertyModifierList[p_name] = spm; } public static function registerSpecialProperty(p_name:String, p_getFunction:Function, p_setFunction:Function, p_parameters:Array=null, p_preProcessFunction:Function=null):void{ if (!_inited){ init(); }; var sp:SpecialProperty = new SpecialProperty(p_getFunction, p_setFunction, p_parameters, p_preProcessFunction); _specialPropertyList[p_name] = sp; } public static function init(... _args):void{ _inited = true; _transitionList = new Object(); Equations.init(); _specialPropertyList = new Object(); _specialPropertyModifierList = new Object(); _specialPropertySplitterList = new Object(); } private static function updateTweens():Boolean{ var i:int; if (_tweenList.length == 0){ return (false); }; i = 0; while (i < _tweenList.length) { if ((((_tweenList[i] == undefined)) || (!(_tweenList[i].isPaused)))){ if (!updateTweenByIndex(i)){ removeTweenByIndex(i); }; if (_tweenList[i] == null){ removeTweenByIndex(i, true); i--; }; }; i++; }; return (true); } public static function addCaller(p_scopes:Object=null, p_parameters:Object=null):Boolean{ var i:Number; var rScopes:Array; var rTransition:Function; var nTween:TweenListObj; var myT:Number; var trans:String; if (!Boolean(p_scopes)){ return (false); }; if ((p_scopes is Array)){ rScopes = p_scopes.concat(); } else { rScopes = [p_scopes]; }; var p_obj:Object = p_parameters; if (!_inited){ init(); }; if (((!(_engineExists)) || (!(Boolean(__tweener_controller__))))){ startEngine(); }; var rTime:Number = (isNaN(p_obj.time)) ? 0 : p_obj.time; var rDelay:Number = (isNaN(p_obj.delay)) ? 0 : p_obj.delay; if (typeof(p_obj.transition) == "string"){ trans = p_obj.transition.toLowerCase(); rTransition = _transitionList[trans]; } else { rTransition = p_obj.transition; }; if (!Boolean(rTransition)){ rTransition = _transitionList["easeoutexpo"]; }; i = 0; while (i < rScopes.length) { if (p_obj.useFrames == true){ nTween = new TweenListObj(rScopes[i], (_currentTimeFrame + (rDelay / _timeScale)), (_currentTimeFrame + ((rDelay + rTime) / _timeScale)), true, rTransition, p_obj.transitionParams); } else { nTween = new TweenListObj(rScopes[i], (_currentTime + ((rDelay * 1000) / _timeScale)), (_currentTime + (((rDelay * 1000) + (rTime * 1000)) / _timeScale)), false, rTransition, p_obj.transitionParams); }; nTween.properties = null; nTween.onStart = p_obj.onStart; nTween.onUpdate = p_obj.onUpdate; nTween.onComplete = p_obj.onComplete; nTween.onOverwrite = p_obj.onOverwrite; nTween.onStartParams = p_obj.onStartParams; nTween.onUpdateParams = p_obj.onUpdateParams; nTween.onCompleteParams = p_obj.onCompleteParams; nTween.onOverwriteParams = p_obj.onOverwriteParams; nTween.onStartScope = p_obj.onStartScope; nTween.onUpdateScope = p_obj.onUpdateScope; nTween.onCompleteScope = p_obj.onCompleteScope; nTween.onOverwriteScope = p_obj.onOverwriteScope; nTween.onErrorScope = p_obj.onErrorScope; nTween.isCaller = true; nTween.count = p_obj.count; nTween.waitFrames = p_obj.waitFrames; _tweenList.push(nTween); if ((((rTime == 0)) && ((rDelay == 0)))){ myT = (_tweenList.length - 1); updateTweenByIndex(myT); removeTweenByIndex(myT); }; i++; }; return (true); } public static function pauseAllTweens():Boolean{ var i:uint; if (!Boolean(_tweenList)){ return (false); }; var paused:Boolean; i = 0; while (i < _tweenList.length) { pauseTweenByIndex(i); paused = true; i++; }; return (paused); } public static function removeTweens(p_scope:Object, ... _args):Boolean{ var i:uint; var properties:Array = new Array(); i = 0; while (i < _args.length) { if ((((typeof(_args[i]) == "string")) && (!(AuxFunctions.isInArray(_args[i], properties))))){ properties.push(_args[i]); }; i++; }; return (affectTweens(removeTweenByIndex, p_scope, properties)); } public static function splitTweens(p_tween:Number, p_properties:Array):uint{ var i:uint; var pName:String; var found:Boolean; var originalTween:TweenListObj = _tweenList[p_tween]; var newTween:TweenListObj = originalTween.clone(false); i = 0; while (i < p_properties.length) { pName = p_properties[i]; if (Boolean(originalTween.properties[pName])){ originalTween.properties[pName] = undefined; delete originalTween.properties[pName]; }; i++; }; for (pName in newTween.properties) { found = false; i = 0; while (i < p_properties.length) { if (p_properties[i] == pName){ found = true; break; }; i++; }; if (!found){ newTween.properties[pName] = undefined; delete newTween.properties[pName]; }; }; _tweenList.push(newTween); return ((_tweenList.length - 1)); } public static function updateFrame():void{ _currentTimeFrame++; } public static function resumeTweenByIndex(p_tween:Number):Boolean{ var tTweening:TweenListObj = _tweenList[p_tween]; if ((((tTweening == null)) || (!(tTweening.isPaused)))){ return (false); }; var cTime:Number = getCurrentTweeningTime(tTweening); tTweening.timeStart = (tTweening.timeStart + (cTime - tTweening.timePaused)); tTweening.timeComplete = (tTweening.timeComplete + (cTime - tTweening.timePaused)); tTweening.timePaused = undefined; tTweening.isPaused = false; return (true); } public static function getVersion():String{ return ("AS3 1.31.71"); } public static function onEnterFrame(e:Event):void{ updateTime(); updateFrame(); var hasUpdated:Boolean; hasUpdated = updateTweens(); if (!hasUpdated){ stopEngine(); }; } public static function updateTime():void{ _currentTime = getTimer(); } private static function updateTweenByIndex(i:Number):Boolean{ var tTweening:TweenListObj; var mustUpdate:Boolean; var nv:Number; var t:Number; var b:Number; var c:Number; var d:Number; var pName:String; var eventScope:Object; var tScope:Object; var tProperty:Object; var pv:Number; var i = i; tTweening = _tweenList[i]; if ((((tTweening == null)) || (!(Boolean(tTweening.scope))))){ return (false); }; var isOver:Boolean; var cTime:Number = getCurrentTweeningTime(tTweening); if (cTime >= tTweening.timeStart){ tScope = tTweening.scope; if (tTweening.isCaller){ do { t = (((tTweening.timeComplete - tTweening.timeStart) / tTweening.count) * (tTweening.timesCalled + 1)); b = tTweening.timeStart; c = (tTweening.timeComplete - tTweening.timeStart); d = (tTweening.timeComplete - tTweening.timeStart); nv = tTweening.transition(t, b, c, d); //unresolved if if (Boolean(tTweening.onUpdate)){ eventScope = (Boolean(tTweening.onUpdateScope)) ? tTweening.onUpdateScope : tScope; tTweening.onUpdate.apply(eventScope, tTweening.onUpdateParams); continue; var _slot1 = e; handleError(tTweening, _slot1, "onUpdate"); }; } while (tTweening.timesCalled++, !(tTweening.timesCalled >= tTweening.count)); } else { mustUpdate = (((((tTweening.skipUpdates < 1)) || (!(tTweening.skipUpdates)))) || ((tTweening.updatesSkipped >= tTweening.skipUpdates))); if (cTime >= tTweening.timeComplete){ isOver = true; mustUpdate = true; }; if (!tTweening.hasStarted){ if (Boolean(tTweening.onStart)){ eventScope = (Boolean(tTweening.onStartScope)) ? tTweening.onStartScope : tScope; tTweening.onStart.apply(eventScope, tTweening.onStartParams); //unresolved jump var _slot1 = e; handleError(tTweening, _slot1, "onStart"); }; for (pName in tTweening.properties) { if (tTweening.properties[pName].isSpecialProperty){ if (Boolean(_specialPropertyList[pName].preProcess)){ tTweening.properties[pName].valueComplete = _specialPropertyList[pName].preProcess(tScope, _specialPropertyList[pName].parameters, tTweening.properties[pName].originalValueComplete, tTweening.properties[pName].extra); }; pv = _specialPropertyList[pName].getValue(tScope, _specialPropertyList[pName].parameters, tTweening.properties[pName].extra); } else { pv = tScope[pName]; }; tTweening.properties[pName].valueStart = (isNaN(pv)) ? tTweening.properties[pName].valueComplete : pv; }; mustUpdate = true; tTweening.hasStarted = true; }; if (mustUpdate){ for (pName in tTweening.properties) { tProperty = tTweening.properties[pName]; if (isOver){ nv = tProperty.valueComplete; } else { if (tProperty.hasModifier){ t = (cTime - tTweening.timeStart); d = (tTweening.timeComplete - tTweening.timeStart); nv = tTweening.transition(t, 0, 1, d, tTweening.transitionParams); nv = tProperty.modifierFunction(tProperty.valueStart, tProperty.valueComplete, nv, tProperty.modifierParameters); } else { t = (cTime - tTweening.timeStart); b = tProperty.valueStart; c = (tProperty.valueComplete - tProperty.valueStart); d = (tTweening.timeComplete - tTweening.timeStart); nv = tTweening.transition(t, b, c, d, tTweening.transitionParams); }; }; if (tTweening.rounded){ nv = Math.round(nv); }; if (tProperty.isSpecialProperty){ _specialPropertyList[pName].setValue(tScope, nv, _specialPropertyList[pName].parameters, tTweening.properties[pName].extra); } else { tScope[pName] = nv; }; }; tTweening.updatesSkipped = 0; if (Boolean(tTweening.onUpdate)){ eventScope = (Boolean(tTweening.onUpdateScope)) ? tTweening.onUpdateScope : tScope; tTweening.onUpdate.apply(eventScope, tTweening.onUpdateParams); //unresolved jump var _slot1 = e; handleError(tTweening, _slot1, "onUpdate"); }; } else { tTweening.updatesSkipped++; }; }; if (((isOver) && (Boolean(tTweening.onComplete)))){ eventScope = (Boolean(tTweening.onCompleteScope)) ? tTweening.onCompleteScope : tScope; tTweening.onComplete.apply(eventScope, tTweening.onCompleteParams); //unresolved jump var _slot1 = e; handleError(tTweening, _slot1, "onComplete"); }; return (!(isOver)); }; return (true); } public static function setTimeScale(p_time:Number):void{ var i:Number; var cTime:Number; if (isNaN(p_time)){ p_time = 1; }; if (p_time < 1E-5){ p_time = 1E-5; }; if (p_time != _timeScale){ if (_tweenList != null){ i = 0; while (i < _tweenList.length) { cTime = getCurrentTweeningTime(_tweenList[i]); _tweenList[i].timeStart = (cTime - (((cTime - _tweenList[i].timeStart) * _timeScale) / p_time)); _tweenList[i].timeComplete = (cTime - (((cTime - _tweenList[i].timeComplete) * _timeScale) / p_time)); if (_tweenList[i].timePaused != undefined){ _tweenList[i].timePaused = (cTime - (((cTime - _tweenList[i].timePaused) * _timeScale) / p_time)); }; i++; }; }; _timeScale = p_time; }; } public static function resumeAllTweens():Boolean{ var i:uint; if (!Boolean(_tweenList)){ return (false); }; var resumed:Boolean; i = 0; while (i < _tweenList.length) { resumeTweenByIndex(i); resumed = true; i++; }; return (resumed); } private static function handleError(pTweening:TweenListObj, pError:Error, pCallBackName:String):void{ var eventScope:Object; var pTweening = pTweening; var pError = pError; var pCallBackName = pCallBackName; if (((Boolean(pTweening.onError)) && ((pTweening.onError is Function)))){ eventScope = (Boolean(pTweening.onErrorScope)) ? pTweening.onErrorScope : pTweening.scope; pTweening.onError.apply(eventScope, [pTweening.scope, pError]); //unresolved jump var _slot1 = metaError; printError(((((String(pTweening.scope) + " raised an error while executing the 'onError' handler. Original error:\n ") + pError.getStackTrace()) + "\nonError error: ") + _slot1.getStackTrace())); } else { if (!Boolean(pTweening.onError)){ printError(((((String(pTweening.scope) + " raised an error while executing the '") + pCallBackName) + "'handler. \n") + pError.getStackTrace())); }; }; } private static function startEngine():void{ _engineExists = true; _tweenList = new Array(); __tweener_controller__ = new MovieClip(); __tweener_controller__.addEventListener(Event.ENTER_FRAME, Tweener.onEnterFrame); _currentTimeFrame = 0; updateTime(); } public static function removeAllTweens():Boolean{ var i:uint; if (!Boolean(_tweenList)){ return (false); }; var removed:Boolean; i = 0; while (i < _tweenList.length) { removeTweenByIndex(i); removed = true; i++; }; return (removed); } public static function addTween(p_scopes:Object=null, p_parameters:Object=null):Boolean{ var i:Number; var j:Number; var istr:String; var rScopes:Array; var rTransition:Function; var nProperties:Object; var nTween:TweenListObj; var myT:Number; var splitProperties:Array; var splitProperties2:Array; var tempModifiedProperties:Array; var trans:String; if (!Boolean(p_scopes)){ return (false); }; if ((p_scopes is Array)){ rScopes = p_scopes.concat(); } else { rScopes = [p_scopes]; }; var p_obj:Object = TweenListObj.makePropertiesChain(p_parameters); if (!_inited){ init(); }; if (((!(_engineExists)) || (!(Boolean(__tweener_controller__))))){ startEngine(); }; var rTime:Number = (isNaN(p_obj.time)) ? 0 : p_obj.time; var rDelay:Number = (isNaN(p_obj.delay)) ? 0 : p_obj.delay; var rProperties:Array = new Array(); var restrictedWords:Object = {time:true, delay:true, useFrames:true, skipUpdates:true, transition:true, transitionParams:true, onStart:true, onUpdate:true, onComplete:true, onOverwrite:true, onError:true, rounded:true, onStartParams:true, onUpdateParams:true, onCompleteParams:true, onOverwriteParams:true, onStartScope:true, onUpdateScope:true, onCompleteScope:true, onOverwriteScope:true, onErrorScope:true}; var modifiedProperties:Object = new Object(); for (istr in p_obj) { if (!restrictedWords[istr]){ if (_specialPropertySplitterList[istr]){ splitProperties = _specialPropertySplitterList[istr].splitValues(p_obj[istr], _specialPropertySplitterList[istr].parameters); i = 0; while (i < splitProperties.length) { if (_specialPropertySplitterList[splitProperties[i].name]){ splitProperties2 = _specialPropertySplitterList[splitProperties[i].name].splitValues(splitProperties[i].value, _specialPropertySplitterList[splitProperties[i].name].parameters); j = 0; while (j < splitProperties2.length) { rProperties[splitProperties2[j].name] = {valueStart:undefined, valueComplete:splitProperties2[j].value, arrayIndex:splitProperties2[j].arrayIndex, isSpecialProperty:false}; j++; }; } else { rProperties[splitProperties[i].name] = {valueStart:undefined, valueComplete:splitProperties[i].value, arrayIndex:splitProperties[i].arrayIndex, isSpecialProperty:false}; }; i++; }; } else { if (_specialPropertyModifierList[istr] != undefined){ tempModifiedProperties = _specialPropertyModifierList[istr].modifyValues(p_obj[istr]); i = 0; while (i < tempModifiedProperties.length) { modifiedProperties[tempModifiedProperties[i].name] = {modifierParameters:tempModifiedProperties[i].parameters, modifierFunction:_specialPropertyModifierList[istr].getValue}; i++; }; } else { rProperties[istr] = {valueStart:undefined, valueComplete:p_obj[istr]}; }; }; }; }; for (istr in rProperties) { if (_specialPropertyList[istr] != undefined){ rProperties[istr].isSpecialProperty = true; } else { if (rScopes[0][istr] == undefined){ printError((((("The property '" + istr) + "' doesn't seem to be a normal object property of ") + String(rScopes[0])) + " or a registered special property.")); }; }; }; for (istr in modifiedProperties) { if (rProperties[istr] != undefined){ rProperties[istr].modifierParameters = modifiedProperties[istr].modifierParameters; rProperties[istr].modifierFunction = modifiedProperties[istr].modifierFunction; }; }; if (typeof(p_obj.transition) == "string"){ trans = p_obj.transition.toLowerCase(); rTransition = _transitionList[trans]; } else { rTransition = p_obj.transition; }; if (!Boolean(rTransition)){ rTransition = _transitionList["easeoutexpo"]; }; i = 0; while (i < rScopes.length) { nProperties = new Object(); for (istr in rProperties) { nProperties[istr] = new PropertyInfoObj(rProperties[istr].valueStart, rProperties[istr].valueComplete, rProperties[istr].valueComplete, rProperties[istr].arrayIndex, {}, rProperties[istr].isSpecialProperty, rProperties[istr].modifierFunction, rProperties[istr].modifierParameters); }; if (p_obj.useFrames == true){ nTween = new TweenListObj(rScopes[i], (_currentTimeFrame + (rDelay / _timeScale)), (_currentTimeFrame + ((rDelay + rTime) / _timeScale)), true, rTransition, p_obj.transitionParams); } else { nTween = new TweenListObj(rScopes[i], (_currentTime + ((rDelay * 1000) / _timeScale)), (_currentTime + (((rDelay * 1000) + (rTime * 1000)) / _timeScale)), false, rTransition, p_obj.transitionParams); }; nTween.properties = nProperties; nTween.onStart = p_obj.onStart; nTween.onUpdate = p_obj.onUpdate; nTween.onComplete = p_obj.onComplete; nTween.onOverwrite = p_obj.onOverwrite; nTween.onError = p_obj.onError; nTween.onStartParams = p_obj.onStartParams; nTween.onUpdateParams = p_obj.onUpdateParams; nTween.onCompleteParams = p_obj.onCompleteParams; nTween.onOverwriteParams = p_obj.onOverwriteParams; nTween.onStartScope = p_obj.onStartScope; nTween.onUpdateScope = p_obj.onUpdateScope; nTween.onCompleteScope = p_obj.onCompleteScope; nTween.onOverwriteScope = p_obj.onOverwriteScope; nTween.onErrorScope = p_obj.onErrorScope; nTween.rounded = p_obj.rounded; nTween.skipUpdates = p_obj.skipUpdates; removeTweensByTime(nTween.scope, nTween.properties, nTween.timeStart, nTween.timeComplete); _tweenList.push(nTween); if ((((rTime == 0)) && ((rDelay == 0)))){ myT = (_tweenList.length - 1); updateTweenByIndex(myT); removeTweenByIndex(myT); }; i++; }; return (true); } public static function registerTransition(p_name:String, p_function:Function):void{ if (!_inited){ init(); }; _transitionList[p_name] = p_function; } public static function printError(p_message:String):void{ trace(("## [Tweener] Error: " + p_message)); } private static function affectTweens(p_affectFunction:Function, p_scope:Object, p_properties:Array):Boolean{ var i:uint; var affectedProperties:Array; var j:uint; var objectProperties:uint; var slicedTweenIndex:uint; var affected:Boolean; if (!Boolean(_tweenList)){ return (false); }; i = 0; while (i < _tweenList.length) { if (((_tweenList[i]) && ((_tweenList[i].scope == p_scope)))){ if (p_properties.length == 0){ p_affectFunction(i); affected = true; } else { affectedProperties = new Array(); j = 0; while (j < p_properties.length) { if (Boolean(_tweenList[i].properties[p_properties[j]])){ affectedProperties.push(p_properties[j]); }; j++; }; if (affectedProperties.length > 0){ objectProperties = AuxFunctions.getObjectLength(_tweenList[i].properties); if (objectProperties == affectedProperties.length){ p_affectFunction(i); affected = true; } else { slicedTweenIndex = splitTweens(i, affectedProperties); p_affectFunction(slicedTweenIndex); affected = true; }; }; }; }; i++; }; return (affected); } public static function getTweens(p_scope:Object):Array{ var i:uint; var pName:String; if (!Boolean(_tweenList)){ return ([]); }; var tList:Array = new Array(); i = 0; while (i < _tweenList.length) { if (((Boolean(_tweenList[i])) && ((_tweenList[i].scope == p_scope)))){ for (pName in _tweenList[i].properties) { tList.push(pName); }; }; i++; }; return (tList); } public static function isTweening(p_scope:Object):Boolean{ var i:uint; if (!Boolean(_tweenList)){ return (false); }; i = 0; while (i < _tweenList.length) { if (((Boolean(_tweenList[i])) && ((_tweenList[i].scope == p_scope)))){ return (true); }; i++; }; return (false); } public static function pauseTweenByIndex(p_tween:Number):Boolean{ var tTweening:TweenListObj = _tweenList[p_tween]; if ((((tTweening == null)) || (tTweening.isPaused))){ return (false); }; tTweening.timePaused = getCurrentTweeningTime(tTweening); tTweening.isPaused = true; return (true); } public static function getCurrentTweeningTime(p_tweening:Object):Number{ return ((p_tweening.useFrames) ? _currentTimeFrame : _currentTime); } public static function getTweenCount(p_scope:Object):Number{ var i:uint; if (!Boolean(_tweenList)){ return (0); }; var c:Number = 0; i = 0; while (i < _tweenList.length) { if (((Boolean(_tweenList[i])) && ((_tweenList[i].scope == p_scope)))){ c = (c + AuxFunctions.getObjectLength(_tweenList[i].properties)); }; i++; }; return (c); } private static function stopEngine():void{ _engineExists = false; _tweenList = null; _currentTime = 0; _currentTimeFrame = 0; __tweener_controller__.removeEventListener(Event.ENTER_FRAME, Tweener.onEnterFrame); __tweener_controller__ = null; } public static function removeTweensByTime(p_scope:Object, p_properties:Object, p_timeStart:Number, p_timeComplete:Number):Boolean{ var removedLocally:Boolean; var i:uint; var pName:String; var eventScope:Object; var p_scope = p_scope; var p_properties = p_properties; var p_timeStart = p_timeStart; var p_timeComplete = p_timeComplete; var removed:Boolean; var tl:uint = _tweenList.length; i = 0; while (i < tl) { if (((Boolean(_tweenList[i])) && ((p_scope == _tweenList[i].scope)))){ if ((((p_timeComplete > _tweenList[i].timeStart)) && ((p_timeStart < _tweenList[i].timeComplete)))){ removedLocally = false; for (pName in _tweenList[i].properties) { if (Boolean(p_properties[pName])){ if (Boolean(_tweenList[i].onOverwrite)){ eventScope = (Boolean(_tweenList[i].onOverwriteScope)) ? _tweenList[i].onOverwriteScope : _tweenList[i].scope; _tweenList[i].onOverwrite.apply(eventScope, _tweenList[i].onOverwriteParams); //unresolved jump var _slot1 = e; handleError(_tweenList[i], _slot1, "onOverwrite"); }; _tweenList[i].properties[pName] = undefined; delete _tweenList[i].properties[pName]; removedLocally = true; removed = true; }; }; if (removedLocally){ if (AuxFunctions.getObjectLength(_tweenList[i].properties) == 0){ removeTweenByIndex(i); }; }; }; }; i = (i + 1); }; return (removed); } public static function registerSpecialPropertySplitter(p_name:String, p_splitFunction:Function, p_parameters:Array=null):void{ if (!_inited){ init(); }; var sps:SpecialPropertySplitter = new SpecialPropertySplitter(p_splitFunction, p_parameters); _specialPropertySplitterList[p_name] = sps; } public static function removeTweenByIndex(i:Number, p_finalRemoval:Boolean=false):Boolean{ _tweenList[i] = null; if (p_finalRemoval){ _tweenList.splice(i, 1); }; return (true); } public static function resumeTweens(p_scope:Object, ... _args):Boolean{ var i:uint; var properties:Array = new Array(); i = 0; while (i < _args.length) { if ((((typeof(_args[i]) == "string")) && (!(AuxFunctions.isInArray(_args[i], properties))))){ properties.push(_args[i]); }; i++; }; return (affectTweens(resumeTweenByIndex, p_scope, properties)); } public static function pauseTweens(p_scope:Object, ... _args):Boolean{ var i:uint; var properties:Array = new Array(); i = 0; while (i < _args.length) { if ((((typeof(_args[i]) == "string")) && (!(AuxFunctions.isInArray(_args[i], properties))))){ properties.push(_args[i]); }; i++; }; return (affectTweens(pauseTweenByIndex, p_scope, properties)); } } }//package caurina.transitions
Section 83
//TweenListObj (caurina.transitions.TweenListObj) package caurina.transitions { public class TweenListObj { public var hasStarted:Boolean; public var onUpdate:Function; public var useFrames:Boolean; public var count:Number; public var onOverwriteParams:Array; public var timeStart:Number; public var timeComplete:Number; public var onStartParams:Array; public var onUpdateScope:Object; public var rounded:Boolean; public var onUpdateParams:Array; public var properties:Object; public var onComplete:Function; public var transitionParams:Object; public var updatesSkipped:Number; public var onStart:Function; public var onOverwriteScope:Object; public var skipUpdates:Number; public var onStartScope:Object; public var scope:Object; public var isCaller:Boolean; public var timePaused:Number; public var transition:Function; public var onCompleteParams:Array; public var onError:Function; public var timesCalled:Number; public var onErrorScope:Object; public var onOverwrite:Function; public var isPaused:Boolean; public var waitFrames:Boolean; public var onCompleteScope:Object; public function TweenListObj(p_scope:Object, p_timeStart:Number, p_timeComplete:Number, p_useFrames:Boolean, p_transition:Function, p_transitionParams:Object){ super(); scope = p_scope; timeStart = p_timeStart; timeComplete = p_timeComplete; useFrames = p_useFrames; transition = p_transition; transitionParams = p_transitionParams; properties = new Object(); isPaused = false; timePaused = undefined; isCaller = false; updatesSkipped = 0; timesCalled = 0; skipUpdates = 0; hasStarted = false; } public function clone(omitEvents:Boolean):TweenListObj{ var pName:String; var nTween:TweenListObj = new TweenListObj(scope, timeStart, timeComplete, useFrames, transition, transitionParams); nTween.properties = new Array(); for (pName in properties) { nTween.properties[pName] = properties[pName].clone(); }; nTween.skipUpdates = skipUpdates; nTween.updatesSkipped = updatesSkipped; if (!omitEvents){ nTween.onStart = onStart; nTween.onUpdate = onUpdate; nTween.onComplete = onComplete; nTween.onOverwrite = onOverwrite; nTween.onError = onError; nTween.onStartParams = onStartParams; nTween.onUpdateParams = onUpdateParams; nTween.onCompleteParams = onCompleteParams; nTween.onOverwriteParams = onOverwriteParams; nTween.onStartScope = onStartScope; nTween.onUpdateScope = onUpdateScope; nTween.onCompleteScope = onCompleteScope; nTween.onOverwriteScope = onOverwriteScope; nTween.onErrorScope = onErrorScope; }; nTween.rounded = rounded; nTween.isPaused = isPaused; nTween.timePaused = timePaused; nTween.isCaller = isCaller; nTween.count = count; nTween.timesCalled = timesCalled; nTween.waitFrames = waitFrames; nTween.hasStarted = hasStarted; return (nTween); } public function toString():String{ var i:String; var returnStr:String = "\n[TweenListObj "; returnStr = (returnStr + ("scope:" + String(scope))); returnStr = (returnStr + ", properties:"); var isFirst:Boolean; for (i in properties) { if (!isFirst){ returnStr = (returnStr + ","); }; returnStr = (returnStr + ("[name:" + properties[i].name)); returnStr = (returnStr + (",valueStart:" + properties[i].valueStart)); returnStr = (returnStr + (",valueComplete:" + properties[i].valueComplete)); returnStr = (returnStr + "]"); isFirst = false; }; returnStr = (returnStr + (", timeStart:" + String(timeStart))); returnStr = (returnStr + (", timeComplete:" + String(timeComplete))); returnStr = (returnStr + (", useFrames:" + String(useFrames))); returnStr = (returnStr + (", transition:" + String(transition))); returnStr = (returnStr + (", transitionParams:" + String(transitionParams))); if (skipUpdates){ returnStr = (returnStr + (", skipUpdates:" + String(skipUpdates))); }; if (updatesSkipped){ returnStr = (returnStr + (", updatesSkipped:" + String(updatesSkipped))); }; if (Boolean(onStart)){ returnStr = (returnStr + (", onStart:" + String(onStart))); }; if (Boolean(onUpdate)){ returnStr = (returnStr + (", onUpdate:" + String(onUpdate))); }; if (Boolean(onComplete)){ returnStr = (returnStr + (", onComplete:" + String(onComplete))); }; if (Boolean(onOverwrite)){ returnStr = (returnStr + (", onOverwrite:" + String(onOverwrite))); }; if (Boolean(onError)){ returnStr = (returnStr + (", onError:" + String(onError))); }; if (onStartParams){ returnStr = (returnStr + (", onStartParams:" + String(onStartParams))); }; if (onUpdateParams){ returnStr = (returnStr + (", onUpdateParams:" + String(onUpdateParams))); }; if (onCompleteParams){ returnStr = (returnStr + (", onCompleteParams:" + String(onCompleteParams))); }; if (onOverwriteParams){ returnStr = (returnStr + (", onOverwriteParams:" + String(onOverwriteParams))); }; if (onStartScope){ returnStr = (returnStr + (", onStartScope:" + String(onStartScope))); }; if (onUpdateScope){ returnStr = (returnStr + (", onUpdateScope:" + String(onUpdateScope))); }; if (onCompleteScope){ returnStr = (returnStr + (", onCompleteScope:" + String(onCompleteScope))); }; if (onOverwriteScope){ returnStr = (returnStr + (", onOverwriteScope:" + String(onOverwriteScope))); }; if (onErrorScope){ returnStr = (returnStr + (", onErrorScope:" + String(onErrorScope))); }; if (rounded){ returnStr = (returnStr + (", rounded:" + String(rounded))); }; if (isPaused){ returnStr = (returnStr + (", isPaused:" + String(isPaused))); }; if (timePaused){ returnStr = (returnStr + (", timePaused:" + String(timePaused))); }; if (isCaller){ returnStr = (returnStr + (", isCaller:" + String(isCaller))); }; if (count){ returnStr = (returnStr + (", count:" + String(count))); }; if (timesCalled){ returnStr = (returnStr + (", timesCalled:" + String(timesCalled))); }; if (waitFrames){ returnStr = (returnStr + (", waitFrames:" + String(waitFrames))); }; if (hasStarted){ returnStr = (returnStr + (", hasStarted:" + String(hasStarted))); }; returnStr = (returnStr + "]\n"); return (returnStr); } public static function makePropertiesChain(p_obj:Object):Object{ var chainedObject:Object; var chain:Object; var currChainObj:Object; var len:Number; var i:Number; var k:Number; var baseObject:Object = p_obj.base; if (baseObject){ chainedObject = {}; if ((baseObject is Array)){ chain = []; k = 0; while (k < baseObject.length) { chain.push(baseObject[k]); k++; }; } else { chain = [baseObject]; }; chain.push(p_obj); len = chain.length; i = 0; while (i < len) { if (chain[i]["base"]){ currChainObj = AuxFunctions.concatObjects(makePropertiesChain(chain[i]["base"]), chain[i]); } else { currChainObj = chain[i]; }; chainedObject = AuxFunctions.concatObjects(chainedObject, currChainObj); i++; }; if (chainedObject["base"]){ delete chainedObject["base"]; }; return (chainedObject); //unresolved jump }; return (p_obj); } } }//package caurina.transitions
Section 84
//BoxZ (core.gfx.BoxZ) package core.gfx { import core.*; import flash.display.*; import caurina.transitions.*; public class BoxZ { private var engine:CoreEngine; private var lifeTime:int; private var time:int; private var manager:BoxZManager; private var startX:Number; public var x:Number; public var y:Number; private var skin:Sprite; private var radius:Number; public function BoxZ(x:Number, y:Number, manager:BoxZManager):void{ super(); this.x = x; this.y = y; this.manager = manager; init(); } private function createSkin():void{ var SkinClass:Class = engine.assets.getAssetClass("ZAsset"); skin = new (SkinClass); engine.canvas.joints.addChild(skin); updateSkin(); skin.alpha = 0; Tweener.addTween(skin, {alpha:1, time:0.5, transition:"linear"}); } private function updateSkin():void{ skin.x = x; skin.y = y; } public function update():void{ y = (y - 1); x = (startX + (radius * Math.sin((((time / 180) * Math.PI) * 6)))); updateSkin(); time++; if (time == (lifeTime - 15)){ Tweener.addTween(skin, {alpha:0, time:0.5, transition:"linear"}); } else { if (time >= lifeTime){ destroy(); }; }; } private function init():void{ engine = CoreEngine.getInstance(); startX = x; createSkin(); time = 0; lifeTime = 100; radius = Math.floor((5 + (Math.random() * 10))); } private function destroy():void{ skin.parent.removeChild(skin); manager.removeZ(this); } } }//package core.gfx
Section 85
//BoxZManager (core.gfx.BoxZManager) package core.gfx { import core.objects.*; public class BoxZManager { private var box:BoxBase; private var time:int; private var timeDelay:int; private var zs:Array; public function BoxZManager(box:BoxBase):void{ super(); this.box = box; init(); } private function updateZs():void{ var z:BoxZ; var i:int = (zs.length - 1); while (i >= 0) { z = zs[i]; z.update(); i--; }; } public function removeZ(z:BoxZ):void{ var index:int = zs.indexOf(z); zs.splice(index, 1); } public function update():void{ if (box.state == BoxBase.STATE_SLEEP){ time++; if (time >= timeDelay){ time = 0; createZ(); }; }; updateZs(); } private function init():void{ zs = []; time = 0; timeDelay = 40; } private function createZ():void{ var zx:Number = ((box.skin.x - 10) + (-10 + Math.floor((Math.random() * 20)))); var zy:Number = ((box.skin.y - 10) + (-10 + Math.floor((Math.random() * 20)))); var z:BoxZ = new BoxZ(zx, zy, this); zs.push(z); } } }//package core.gfx
Section 86
//BaseObject (core.objects.BaseObject) package core.objects { import core.*; import flash.display.*; public class BaseObject { protected var engine:CoreEngine; public var x:Number; public var y:Number; public var skin:Sprite; public function BaseObject(x:Number, y:Number):void{ super(); this.x = x; this.y = y; init(); } protected function init():void{ engine = CoreEngine.getInstance(); } public function update():void{ } public function destroy():void{ } } }//package core.objects
Section 87
//BodyObject (core.objects.BodyObject) package core.objects { import core.*; import flash.display.*; import core.shapes.*; import Box2D.Dynamics.*; import flash.geom.*; import Box2D.Common.Math.*; import Box2D.Collision.Shapes.*; public class BodyObject extends BaseObject { public var body:b2Body; public var isStatic:Boolean; public static const DYNAMIC_CIRCLE_CLASS_NAME:String = "DynamicCircleAsset"; public static const STICKY_CIRCLE_CLASS_NAME:String = "StickyCircleAsset"; public static const DYNAMIC_RECT_CLASS_NAME:String = "DynamicRectAsset"; public static const STATIC_CIRCLE_CLASS_NAME:String = "StaticCircleAsset"; public static const STICKY_RECT_CLASS_NAME:String = "StickyRectAsset"; public static const STATIC_RECT_CLASS_NAME:String = "StaticRectAsset"; public function BodyObject(x:Number, y:Number, isStatic:Boolean):void{ this.isStatic = isStatic; super(x, y); } protected function createRectShapeBody(shape:RectShape, gp:Point):void{ var shapeDef:b2PolygonDef = new b2PolygonDef(); var w2:Number = (shape.width / 2); var h2:Number = (shape.height / 2); shapeDef.density = (isStatic) ? 0 : 1; shapeDef.friction = 0.5; shapeDef.userData = this; shapeDef.filter.maskBits = (0xFFFF & ~(2)); shapeDef.restitution = 0.2; shapeDef.vertexCount = 4; shapeDef.vertices[0] = body.GetLocalPoint(new b2Vec2(((-(w2) + gp.x) / engine.physScale), ((-(h2) + gp.y) / engine.physScale))); shapeDef.vertices[1] = body.GetLocalPoint(new b2Vec2(((w2 + gp.x) / engine.physScale), ((-(h2) + gp.y) / engine.physScale))); shapeDef.vertices[2] = body.GetLocalPoint(new b2Vec2(((w2 + gp.x) / engine.physScale), ((h2 + gp.y) / engine.physScale))); shapeDef.vertices[3] = body.GetLocalPoint(new b2Vec2(((-(w2) + gp.x) / engine.physScale), ((h2 + gp.y) / engine.physScale))); body.CreateShape(shapeDef); body.SetMassFromShapes(); body.WakeUp(); } protected function createBody():void{ var bodyDef:b2BodyDef = new b2BodyDef(); bodyDef.position.Set((x / engine.physScale), (y / engine.physScale)); bodyDef.userData = this; body = engine.world.CreateBody(bodyDef); } protected function updateSkin():void{ var pos:b2Vec2 = body.GetPosition(); var angle:Number = body.GetAngle(); skin.x = (pos.x * engine.physScale); skin.y = (pos.y * engine.physScale); skin.rotation = ((angle * 180) / Math.PI); } override public function update():void{ if (!isStatic){ updateSkin(); }; } protected function createRectShapeSkin(shape:RectShape, gp:Point):void{ var colorInner:int; var colorOuter:int = (isStatic) ? 6972621 : 1585980; var w2:Number = Math.floor((shape.width / 2)); var h2:Number = Math.floor((shape.height / 2)); skin.graphics.lineStyle(0, colorInner); var bmd:BitmapData = (isStatic) ? CoreCanvas.staticBMD : CoreCanvas.dynamicBMD; var lp:Point = skin.globalToLocal(gp); skin.graphics.beginBitmapFill(bmd, null, true, false); skin.graphics.drawRect((lp.x - w2), (lp.y - h2), (w2 * 2), (h2 * 2)); skin.graphics.endFill(); } override protected function init():void{ super.init(); createBody(); createSkin(); } public function collideWithBodyObj(hitValue:Number):void{ } protected function createCircleShapeSkin(shape:CircleShape, gp:Point):void{ var colorInner:int; var colorOuter:int = (isStatic) ? 6972621 : 1585980; var r:Number = Math.floor(shape.radius); var bmd:BitmapData = (isStatic) ? CoreCanvas.staticBMD : CoreCanvas.dynamicBMD; var lp:Point = skin.globalToLocal(gp); skin.graphics.lineStyle(0, colorInner); skin.graphics.beginBitmapFill(bmd, null, true, false); skin.graphics.drawCircle(lp.x, lp.y, r); skin.graphics.endFill(); } protected function createSkin():void{ skin = new Sprite(); skin.graphics.clear(); engine.canvas.objects.addChild(skin); updateSkin(); } override public function destroy():void{ engine.world.DestroyBody(body); } public function addRectShape(shape:RectShape, gp:Point):void{ createRectShapeBody(shape, gp); createRectShapeSkin(shape, gp); } protected function createCircleShapeBody(shape:CircleShape, gp:Point):void{ var shapeDef:b2CircleDef = new b2CircleDef(); shapeDef.radius = (shape.radius / engine.physScale); shapeDef.density = (isStatic) ? 0 : 1; shapeDef.friction = 0.5; shapeDef.restitution = 0.2; shapeDef.userData = this; shapeDef.filter.maskBits = (0xFFFF & ~(2)); shapeDef.localPosition = body.GetLocalPoint(new b2Vec2((gp.x / engine.physScale), (gp.y / engine.physScale))); body.CreateShape(shapeDef); body.SetMassFromShapes(); body.WakeUp(); } public function addCircleShape(shape:CircleShape, gp:Point):void{ createCircleShapeBody(shape, gp); createCircleShapeSkin(shape, gp); } } }//package core.objects
Section 88
//Box (core.objects.Box) package core.objects { import flash.display.*; import Box2D.Dynamics.*; import Box2D.Collision.Shapes.*; public class Box extends BoxBase { protected var width:Number;// = 78 protected var height:Number;// = 75 public static const SKIN_CLASS_NAME:String = "BoxAsset"; public function Box(x:Number, y:Number):void{ super(x, y); } override protected function init():void{ super.init(); leftLeg = new BoxLeg((x - 18), (y + 37), this, skinLeftLeg); rightLeg = new BoxLeg((x + 18), (y + 37), this, skinRightLeg); } override protected function createBody():void{ var shapeDef:b2PolygonDef = new b2PolygonDef(); var w2:Number = ((width / engine.physScale) / 2); var h2:Number = ((height / engine.physScale) / 2); shapeDef.SetAsBox(w2, h2); shapeDef.density = 1; shapeDef.friction = 0.5; shapeDef.restitution = 0.2; shapeDef.userData = this; var bodyDef:b2BodyDef = new b2BodyDef(); bodyDef.position.Set((x / engine.physScale), (y / engine.physScale)); bodyDef.userData = this; body = engine.world.CreateBody(bodyDef); body.CreateShape(shapeDef); body.SetMassFromShapes(); } override protected function createSkin():void{ var SkinClass:Class = engine.assets.getAssetClass(SKIN_CLASS_NAME); skin = new (SkinClass); engine.canvas.player.addChild(skin); updateSkin(); skinInner = (skin.getChildByName("inner") as MovieClip); skinLeftLeg = (skinInner.getChildByName("leftLeg") as Sprite); skinRightLeg = (skinInner.getChildByName("rightLeg") as Sprite); skinInner.stop(); skinDist = new Sprite(); skinDist.graphics.clear(); skinDist.graphics.lineStyle(0, 0xFF0000, 0.7); engine.canvas.support.addChild(skinDist); } } }//package core.objects
Section 89
//BoxBase (core.objects.BoxBase) package core.objects { import flash.display.*; import flash.geom.*; import Box2D.Common.Math.*; import core.view.*; import core.gfx.*; public class BoxBase extends BodyObject { protected var skinDist:Sprite; protected var leftLeg:BoxLeg; public var totalDist:Number; protected var skinLeftLeg:Sprite; protected var rightLeg:BoxLeg; protected var zManager:BoxZManager; public var state:String; protected var wakeupMeter:WakeupMeter; protected var lastPoint:Point; protected var skinInner:MovieClip; protected var skinRightLeg:Sprite; public static const STATE_DISTURBED:String = "StateDisturbed"; public static const REQUIRED_DISTANCE:Number = 100; public static const STATE_SLEEP:String = "StateSleep"; public static const STATE_AWAKE:String = "StateAwake"; public function BoxBase(x:Number, y:Number):void{ super(x, y, false); } protected function updateState():void{ var lv:Number; var pos:b2Vec2 = body.GetPosition(); var px:Number = (pos.x * engine.physScale); var py:Number = (pos.y * engine.physScale); var lastDist:Number = (((lastPoint.x - px) * (lastPoint.x - px)) + ((lastPoint.y - py) * (lastPoint.y - py))); if (lastDist > 1){ }; lastPoint.x = px; lastPoint.y = py; totalDist = (totalDist + lastDist); if ((((totalDist > REQUIRED_DISTANCE)) && (!((state == STATE_AWAKE))))){ state = STATE_AWAKE; skinInner.gotoAndStop(2); engine.boxAwakened(); }; if (state == STATE_SLEEP){ lv = body.m_linearVelocity.Length(); if (lv > 0.2){ state = STATE_DISTURBED; skinInner.gotoAndStop(3); }; } else { if (state == STATE_DISTURBED){ if (body.IsSleeping()){ state = STATE_SLEEP; skinInner.gotoAndStop(1); }; }; }; } override public function update():void{ updateState(); updateSkin(); leftLeg.update(); rightLeg.update(); zManager.update(); wakeupMeter.update(); } override protected function init():void{ super.init(); totalDist = 0; state = BoxBase.STATE_SLEEP; lastPoint = new Point(x, y); zManager = new BoxZManager(this); wakeupMeter = new WakeupMeter(this); } } }//package core.objects
Section 90
//BoxLeg (core.objects.BoxLeg) package core.objects { import flash.display.*; import Box2D.Dynamics.*; import Box2D.Common.Math.*; import Box2D.Dynamics.Joints.*; import Box2D.Collision.Shapes.*; public class BoxLeg extends BaseObject { private var body:b2Body; private var joint:b2RevoluteJoint; private var box:BoxBase; public function BoxLeg(x:Number, y:Number, box:BoxBase, skin:Sprite):void{ this.box = box; this.skin = skin; super(x, y); } override protected function init():void{ super.init(); createBody(); } override public function update():void{ updateSkin(); } private function updateSkin():void{ var angle:Number = body.GetAngle(); skin.rotation = (-(box.skin.rotation) + ((angle * 180) / Math.PI)); } private function createBody():void{ var shapeDef:b2PolygonDef = new b2PolygonDef(); var width:Number = 10; var height:Number = 40; shapeDef.SetAsBox(((width / 2) / engine.physScale), ((height / 2) / engine.physScale)); shapeDef.density = 0.001; shapeDef.userData = this; shapeDef.filter.categoryBits = 2; var bodyDef:b2BodyDef = new b2BodyDef(); bodyDef.position.Set((x / engine.physScale), ((y + (height / 2)) / engine.physScale)); bodyDef.angularDamping = 5; bodyDef.userData = this; body = engine.world.CreateBody(bodyDef); body.CreateShape(shapeDef); body.SetMassFromShapes(); var rjd:b2RevoluteJointDef = new b2RevoluteJointDef(); var anchor:b2Vec2 = new b2Vec2((x / engine.physScale), (y / engine.physScale)); rjd.Initialize(box.body, body, anchor); joint = (engine.world.CreateJoint(rjd) as b2RevoluteJoint); } } }//package core.objects
Section 91
//BoxSon (core.objects.BoxSon) package core.objects { import flash.display.*; import Box2D.Dynamics.*; import Box2D.Common.Math.*; import Box2D.Collision.Shapes.*; public class BoxSon extends BoxBase { protected var radius:Number;// = 40 public static const SKIN_CLASS_NAME:String = "BoxSonAsset"; public function BoxSon(x:Number, y:Number):void{ super(x, y); } override protected function init():void{ super.init(); leftLeg = new BoxLeg((x - 18), (y + 37), this, skinLeftLeg); rightLeg = new BoxLeg((x + 18), (y + 37), this, skinRightLeg); } override protected function createSkin():void{ var SkinClass:Class = engine.assets.getAssetClass(SKIN_CLASS_NAME); skin = new (SkinClass); engine.canvas.player.addChild(skin); updateSkin(); skinInner = (skin.getChildByName("inner") as MovieClip); skinLeftLeg = (skinInner.getChildByName("leftLeg") as Sprite); skinRightLeg = (skinInner.getChildByName("rightLeg") as Sprite); skinInner.stop(); skinDist = new Sprite(); skinDist.graphics.clear(); skinDist.graphics.lineStyle(0, 0xFF0000, 0.7); engine.canvas.support.addChild(skinDist); } override protected function createBody():void{ var shapeDef:b2PolygonDef = new b2PolygonDef(); shapeDef.vertexCount = 3; var v1:b2Vec2 = new b2Vec2(0, (-37 / engine.physScale)); var v2:b2Vec2 = new b2Vec2((40 / engine.physScale), (37 / engine.physScale)); var v3:b2Vec2 = new b2Vec2((-40 / engine.physScale), (37 / engine.physScale)); shapeDef.vertices = [v1, v2, v3]; shapeDef.density = 1; shapeDef.friction = 0.5; shapeDef.restitution = 0.2; shapeDef.userData = this; var bodyDef:b2BodyDef = new b2BodyDef(); bodyDef.position.Set((x / engine.physScale), (y / engine.physScale)); bodyDef.userData = this; body = engine.world.CreateBody(bodyDef); body.CreateShape(shapeDef); body.SetMassFromShapes(); } } }//package core.objects
Section 92
//BoxWife (core.objects.BoxWife) package core.objects { import flash.display.*; import Box2D.Dynamics.*; import Box2D.Collision.Shapes.*; public class BoxWife extends BoxBase { protected var radius:Number;// = 40 public static const SKIN_CLASS_NAME:String = "BoxWifeAsset"; public function BoxWife(x:Number, y:Number):void{ super(x, y); } override protected function init():void{ super.init(); leftLeg = new BoxLeg((x - 13), (y + 32), this, skinLeftLeg); rightLeg = new BoxLeg((x + 13), (y + 32), this, skinRightLeg); } override protected function createSkin():void{ var SkinClass:Class = engine.assets.getAssetClass(SKIN_CLASS_NAME); skin = new (SkinClass); engine.canvas.player.addChild(skin); updateSkin(); skinInner = (skin.getChildByName("inner") as MovieClip); skinLeftLeg = (skinInner.getChildByName("leftLeg") as Sprite); skinRightLeg = (skinInner.getChildByName("rightLeg") as Sprite); skinInner.stop(); skinDist = new Sprite(); skinDist.graphics.clear(); skinDist.graphics.lineStyle(0, 0xFF0000, 0.7); engine.canvas.support.addChild(skinDist); } override protected function createBody():void{ var shapeDef:b2CircleDef = new b2CircleDef(); shapeDef.radius = (radius / engine.physScale); shapeDef.density = 1; shapeDef.friction = 0.5; shapeDef.restitution = 0.2; shapeDef.userData = this; var bodyDef:b2BodyDef = new b2BodyDef(); bodyDef.position.Set((x / engine.physScale), (y / engine.physScale)); bodyDef.userData = this; body = engine.world.CreateBody(bodyDef); body.CreateShape(shapeDef); body.SetMassFromShapes(); } } }//package core.objects
Section 93
//DistanceJoint (core.objects.DistanceJoint) package core.objects { import flash.display.*; import Box2D.Dynamics.*; import flash.geom.*; import Box2D.Common.Math.*; import Box2D.Dynamics.Joints.*; public class DistanceJoint extends BaseObject { private var skinAnchor2:Sprite; private var skinContainer:Sprite; protected var joint:b2DistanceJoint; private var y2:Number; private var x2:Number; private var skinAnchor1:Sprite; public static const SKIN_CLASS_NAME:String = "DistanceJointAsset"; public function DistanceJoint(x:Number, y:Number, x2:Number, y2:Number):void{ this.x2 = x2; this.y2 = y2; super(x, y); } protected function getBodyByPoint(p:Point):b2Body{ var obj:BaseObject; var bodyObj:BodyObject; var i:int; while (i < engine.objects.length) { obj = engine.objects[i]; if ((obj is BodyObject)){ bodyObj = (obj as BodyObject); if (bodyObj.skin.hitTestPoint(p.x, p.y, true)){ return (bodyObj.body); }; }; i++; }; return (engine.world.m_groundBody); } private function updateSkin():void{ var a1:b2Vec2 = joint.GetAnchor1().Copy(); var a2:b2Vec2 = joint.GetAnchor2().Copy(); a1.Multiply(engine.physScale); a2.Multiply(engine.physScale); var angle:Number = Math.atan2((a2.y - a1.y), (a2.x - a1.x)); skinContainer.x = a1.x; skinContainer.y = a1.y; skinContainer.rotation = ((angle * 180) / Math.PI); skinAnchor1.x = a1.x; skinAnchor1.y = a1.y; skinAnchor2.x = a2.x; skinAnchor2.y = a2.y; } override public function update():void{ if (joint){ updateSkin(); }; } protected function createJoint():void{ var djd:b2DistanceJointDef; var anchor1:b2Vec2; var anchor2:b2Vec2; var body1:b2Body = getBodyByPoint(new Point(x, y)); var body2:b2Body = getBodyByPoint(new Point(x2, y2)); if (((body1) && (body2))){ djd = new b2DistanceJointDef(); anchor1 = new b2Vec2((x / engine.physScale), (y / engine.physScale)); anchor2 = new b2Vec2((x2 / engine.physScale), (y2 / engine.physScale)); djd.Initialize(body1, body2, anchor1, anchor2); djd.userData = this; djd.collideConnected = true; joint = (engine.world.CreateJoint(djd) as b2DistanceJoint); }; } override protected function init():void{ super.init(); createJoint(); createSkin(); } protected function createSkin():void{ var a1:b2Vec2; var a2:b2Vec2; var dist:Number; var SkinClass:Class = engine.assets.getAssetClass(SKIN_CLASS_NAME); skin = new (SkinClass); skinAnchor1 = (skin.getChildByName("vertex1") as Sprite); skinAnchor2 = (skin.getChildByName("vertex2") as Sprite); skinContainer = (skin.getChildByName("container") as Sprite); var DistJointBMDClass:Class = engine.assets.getAssetClass("DistJointLineAsset"); var distJointBMD:BitmapData = new DistJointBMDClass(0, 0); if (joint){ a1 = joint.GetAnchor1().Copy(); a2 = joint.GetAnchor2().Copy(); a1.Multiply(engine.physScale); a2.Multiply(engine.physScale); dist = Math.sqrt((((a2.x - a1.x) * (a2.x - a1.x)) + ((a2.y - a1.y) * (a2.y - a1.y)))); skinContainer.graphics.clear(); skinContainer.graphics.beginBitmapFill(distJointBMD, null, true, true); skinContainer.graphics.drawRect(0, -2, dist, 2); skinContainer.graphics.endFill(); updateSkin(); } else { skin.alpha = 0.2; }; engine.canvas.joints.addChild(skin); } override public function destroy():void{ if (joint){ engine.world.DestroyJoint(joint); }; } } }//package core.objects
Section 94
//Hinge (core.objects.Hinge) package core.objects { import Box2D.Dynamics.*; import flash.geom.*; import Box2D.Common.Math.*; import Box2D.Dynamics.Joints.*; public class Hinge extends BaseObject { protected var obj1:BodyObject; protected var joint:b2RevoluteJoint; protected var obj2:BodyObject; public static const SKIN_CLASS_NAME:String = "HingeAsset"; public function Hinge(x:Number, y:Number):void{ super(x, y); } protected function updateSkin():void{ var a1:b2Vec2 = joint.GetAnchor1().Copy(); a1.Multiply(engine.physScale); skin.x = a1.x; skin.y = a1.y; } override public function update():void{ if (joint){ updateSkin(); }; } protected function createJoint():void{ var body2:b2Body; var rjd:b2RevoluteJointDef; var anchor:b2Vec2; var p:Point = new Point(x, y); obj1 = getBodyObjByPoint(p); if (obj1){ obj2 = getOtherBodyObjByPoint(obj1, p); if (obj2){ body2 = obj2.body; } else { body2 = engine.world.m_groundBody; }; rjd = new b2RevoluteJointDef(); anchor = new b2Vec2((x / engine.physScale), (y / engine.physScale)); rjd.Initialize(obj1.body, body2, anchor); rjd.userData = this; joint = (engine.world.CreateJoint(rjd) as b2RevoluteJoint); }; } override protected function init():void{ super.init(); createJoint(); createSkin(); } override public function destroy():void{ if (joint){ engine.world.DestroyJoint(joint); }; } protected function createSkin():void{ var SkinClass:Class = engine.assets.getAssetClass(SKIN_CLASS_NAME); skin = new (SkinClass); skin.x = x; skin.y = y; if (!joint){ skin.alpha = 0.2; }; engine.canvas.joints.addChild(skin); } protected function getBodyObjByPoint(p:Point):BodyObject{ var obj:BaseObject; var bodyObj:BodyObject; var i:int; while (i < engine.objects.length) { obj = engine.objects[i]; if ((obj is BodyObject)){ bodyObj = (obj as BodyObject); if (bodyObj.skin.hitTestPoint(p.x, p.y, true)){ return (bodyObj); }; }; i++; }; return (null); } protected function getOtherBodyObjByPoint(bodyObj1:BodyObject, p:Point):BodyObject{ var obj:BaseObject; var bodyObj:BodyObject; var i:int; while (i < engine.objects.length) { obj = engine.objects[i]; if ((obj is BodyObject)){ bodyObj = (obj as BodyObject); if (((!((bodyObj == bodyObj1))) && (bodyObj.skin.hitTestPoint(p.x, p.y, true)))){ return (bodyObj); }; }; i++; }; return (null); } } }//package core.objects
Section 95
//Motor (core.objects.Motor) package core.objects { import flash.display.*; import Box2D.Dynamics.*; import flash.geom.*; import Box2D.Common.Math.*; import Box2D.Dynamics.Joints.*; public class Motor extends Hinge { private var skinCw:Sprite; private var skinCcw:Sprite; public var torque:Number; public static const SKIN_CLASS_NAME:String = "MotorAsset"; public function Motor(x:Number, y:Number, torque:Number):void{ this.torque = torque; super(x, y); } override protected function createSkin():void{ var SkinClass:Class = engine.assets.getAssetClass(SKIN_CLASS_NAME); skin = new (SkinClass); skin.x = x; skin.y = y; if (!joint){ skin.alpha = 0.2; }; skinCw = (skin.getChildByName("cw") as Sprite); skinCcw = (skin.getChildByName("ccw") as Sprite); skinCw.visible = false; skinCcw.visible = false; if (torque > 0){ skinCw.visible = true; } else { skinCcw.visible = true; }; engine.canvas.joints.addChild(skin); } override protected function createJoint():void{ var p:Point; var body2:b2Body; var rjd:b2RevoluteJointDef; var anchor:b2Vec2; p = new Point(x, y); obj1 = getBodyObjByPoint(p); if (obj1){ obj2 = getOtherBodyObjByPoint(obj1, p); if (obj2){ body2 = obj2.body; } else { body2 = engine.world.m_groundBody; }; rjd = new b2RevoluteJointDef(); anchor = new b2Vec2((x / engine.physScale), (y / engine.physScale)); rjd.Initialize(obj1.body, body2, anchor); rjd.userData = this; rjd.enableMotor = true; rjd.motorSpeed = (-(torque) * 2); rjd.maxMotorTorque = 1000; joint = (engine.world.CreateJoint(rjd) as b2RevoluteJoint); }; } } }//package core.objects
Section 96
//ShapeSensor (core.objects.ShapeSensor) package core.objects { import core.shapes.*; import Box2D.Dynamics.*; import Box2D.Common.Math.*; import Box2D.Dynamics.Joints.*; import Box2D.Collision.Shapes.*; import Box2D.Dynamics.Contacts.*; public class ShapeSensor extends BaseObject { public var body:b2Body; private var mouseJoint:b2MouseJoint; public var stickyObj:StickyBodyObject; private var contactObjects:Array; private var bodyShape:b2Shape; public function ShapeSensor(x:Number, y:Number):void{ super(x, y); } public function createRectShape(shape:RectShape):void{ if (bodyShape){ body.DestroyShape(bodyShape); bodyShape = null; }; var shapeDef:b2PolygonDef = new b2PolygonDef(); var w2:Number = (shape.width / 2); var h2:Number = (shape.height / 2); shapeDef.density = 1; shapeDef.friction = 0.5; shapeDef.userData = this; shapeDef.isSensor = true; shapeDef.filter.maskBits = (0xFFFF & ~(2)); shapeDef.SetAsBox((w2 / engine.physScale), (h2 / engine.physScale)); bodyShape = body.CreateShape(shapeDef); body.SetMassFromShapes(); } override public function update():void{ var obj1:BaseObject; var obj2:BaseObject; var obj:BaseObject; contactObjects = []; var count:int; var c:b2Contact = engine.world.m_contactList; while (c) { obj1 = c.m_shape1.m_userData; obj2 = c.m_shape2.m_userData; if ((((obj1 == this)) && ((c.GetManifoldCount() > 0)))){ addContactObj(obj2, c); }; if ((((obj2 == this)) && ((c.GetManifoldCount() > 0)))){ addContactObj(obj1, c); }; c = c.m_next; }; stickyObj = null; if (contactObjects.length == 1){ obj = contactObjects[0]; if ((obj is StickyBodyObject)){ stickyObj = (obj as StickyBodyObject); }; }; } public function preUpdate():void{ body.WakeUp(); var target:b2Vec2 = new b2Vec2((engine.canvas.level.mouseX / engine.physScale), (engine.canvas.level.mouseY / engine.physScale)); body.SetXForm(target, 0); } private function createBody():void{ var bodyDef:b2BodyDef = new b2BodyDef(); bodyDef.userData = this; body = engine.world.CreateBody(bodyDef); } override protected function init():void{ super.init(); contactObjects = []; createBody(); } public function createCircleShape(shape:CircleShape):void{ if (bodyShape){ body.DestroyShape(bodyShape); bodyShape = null; }; var shapeDef:b2CircleDef = new b2CircleDef(); shapeDef.radius = (shape.radius / engine.physScale); shapeDef.density = 1; shapeDef.isSensor = true; shapeDef.userData = this; shapeDef.filter.maskBits = (0xFFFF & ~(2)); bodyShape = body.CreateShape(shapeDef); body.SetMassFromShapes(); } private function addContactObj(obj:BaseObject, c:b2Contact):void{ var index:int = contactObjects.indexOf(obj); if (index == -1){ contactObjects.push(obj); }; } private function createMouseJoint():void{ var mx:Number = engine.canvas.level.mouseX; var my:Number = engine.canvas.level.mouseY; var pos:b2Vec2 = new b2Vec2((mx / engine.physScale), (my / engine.physScale)); body.SetXForm(pos, 0); if (mouseJoint){ engine.world.DestroyJoint(mouseJoint); mouseJoint = null; }; var md:b2MouseJointDef = new b2MouseJointDef(); md.body1 = engine.world.GetGroundBody(); md.body2 = body; md.target.Set((mx / engine.physScale), (my / engine.physScale)); md.maxForce = (3000 * body.GetMass()); md.timeStep = engine.timeStep; md.dampingRatio = 0; md.frequencyHz = 5; mouseJoint = (engine.world.CreateJoint(md) as b2MouseJoint); } override public function destroy():void{ if (body){ engine.world.DestroyBody(body); }; if (mouseJoint){ engine.world.DestroyJoint(mouseJoint); mouseJoint = null; }; } } }//package core.objects
Section 97
//StickyBodyObject (core.objects.StickyBodyObject) package core.objects { import core.*; import flash.display.*; import core.shapes.*; import flash.geom.*; public class StickyBodyObject extends BodyObject { public function StickyBodyObject(x:Number, y:Number):void{ super(x, y, false); } override protected function createSkin():void{ super.createSkin(); } override protected function createCircleShapeSkin(shape:CircleShape, gp:Point):void{ var shapeSkin:Sprite = new Sprite(); var bmd:BitmapData = CoreCanvas.stickyBMD; var lp:Point = skin.globalToLocal(gp); var color = 4796186; shapeSkin.graphics.lineStyle(0, color); shapeSkin.graphics.beginBitmapFill(bmd, null, true, false); shapeSkin.graphics.drawCircle(0, 0, (shape.radius - 1)); shapeSkin.graphics.endFill(); shapeSkin.x = lp.x; shapeSkin.y = lp.y; skin.addChild(shapeSkin); shapeSkin.graphics.lineStyle(0, 10446390); shapeSkin.graphics.drawCircle(0, 0, shape.radius); } override protected function createRectShapeSkin(shape:RectShape, gp:Point):void{ var innerColor = 4796186; var outerColor = 10446390; var w2:Number = Math.floor((shape.width / 2)); var h2:Number = Math.floor((shape.height / 2)); var shapeSkin:Sprite = new Sprite(); var bmd:BitmapData = CoreCanvas.stickyBMD; var lp:Point = skin.globalToLocal(gp); shapeSkin.graphics.lineStyle(0, innerColor); shapeSkin.graphics.beginBitmapFill(bmd, null, true, false); shapeSkin.graphics.drawRect((-(w2) + 1), (-(h2) + 1), ((w2 * 2) - 2), ((h2 * 2) - 2)); shapeSkin.graphics.endFill(); shapeSkin.x = lp.x; shapeSkin.y = lp.y; shapeSkin.rotation = -(skin.rotation); skin.addChild(shapeSkin); shapeSkin.graphics.lineStyle(0, outerColor); shapeSkin.graphics.drawRoundRect(-(w2), -(h2), (w2 * 2), (h2 * 2), 6, 6); } } }//package core.objects
Section 98
//BaseShape (core.shapes.BaseShape) package core.shapes { public class BaseShape { public function BaseShape():void{ super(); init(); } protected function init():void{ } public function getStringDef():String{ return (""); } } }//package core.shapes
Section 99
//CircleShape (core.shapes.CircleShape) package core.shapes { public class CircleShape extends BaseShape { public var radius:Number; public static const NAME:String = "CircleShape"; public static const SKIN_CLASS_NAME:String = "ShapeCircleAsset"; public function CircleShape(radius:Number):void{ this.radius = radius; super(); } override public function getStringDef():String{ var def = (NAME + "_"); def = (def + radius); return (def); } public static function parseStringDef(stringDef:String):CircleShape{ var props:Array = stringDef.split("_"); var radius:Number = props[1]; var shape:CircleShape = new CircleShape(radius); return (shape); } } }//package core.shapes
Section 100
//RectShape (core.shapes.RectShape) package core.shapes { public class RectShape extends BaseShape { public var width:Number; public var height:Number; public static const NAME:String = "RectShape"; public static const SKIN_CLASS_NAME:String = "ShapeRectAsset"; public function RectShape(width:Number, height:Number):void{ this.width = width; this.height = height; super(); } override public function getStringDef():String{ var def = (NAME + "_"); def = (def + (width + "_")); def = (def + height); return (def); } public static function parseStringDef(stringDef:String):RectShape{ var props:Array = stringDef.split("_"); var width:Number = props[1]; var height:Number = props[2]; var shape:RectShape = new RectShape(width, height); return (shape); } } }//package core.shapes
Section 101
//AddShapeTool (core.tools.AddShapeTool) package core.tools { import flash.events.*; import core.*; import flash.display.*; import core.shapes.*; import core.objects.*; import flash.geom.*; public class AddShapeTool extends BaseTool { private var potentialObj:StickyBodyObject; private var skinCross:Sprite; private var mouseDown:Boolean; private var currentShape:BaseShape; private var skinShape:Sprite; public var shapes:Array; private var sensor:ShapeSensor; private var skinShapeContainer:Sprite; public function AddShapeTool():void{ super(); } public function update():void{ var gp:Point; var mp:Point = new Point(engine.canvas.container.mouseX, engine.canvas.container.mouseY); skinShape.x = mp.x; skinShape.y = mp.y; check3(); if (potentialObj){ skinCross.visible = false; } else { skinCross.visible = true; }; if (((mouseDown) && (potentialObj))){ gp = mp.clone(); engine.shapeUsed(currentShape); shapes.splice(0, 1); if ((currentShape is CircleShape)){ potentialObj.addCircleShape((currentShape as CircleShape), gp); getNextShape(); } else { if ((currentShape is RectShape)){ potentialObj.addRectShape((currentShape as RectShape), gp); getNextShape(); }; }; engine.sounds.playSound(engine.sounds.sndAddShape, 1); }; mouseDown = false; } private function mouseUpHandler(e:MouseEvent):void{ } public function preUpdate():void{ sensor.preUpdate(); } private function check3():void{ sensor.update(); potentialObj = sensor.stickyObj; } public function destroy():void{ if (skinShape.parent){ skinShape.parent.removeChild(skinShape); }; sensor.destroy(); engine.canvas.container.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); engine.canvas.container.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } private function createSensor():void{ if ((currentShape is CircleShape)){ sensor.createCircleShape((currentShape as CircleShape)); } else { if ((currentShape is RectShape)){ sensor.createRectShape((currentShape as RectShape)); }; }; } override protected function init():void{ super.init(); var AddShapeClass:Class = engine.assets.getAssetClass("AddShapeAsset"); skinShape = new (AddShapeClass); skinShapeContainer = (skinShape.getChildByName("container") as Sprite); skinCross = (skinShape.getChildByName("cross") as Sprite); skinShapeContainer.alpha = 0.5; engine.canvas.shapes.addChild(skinShape); sensor = new ShapeSensor(0, 0); engine.canvas.container.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); engine.canvas.container.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } private function drawRectCross():void{ skinCross.graphics.clear(); skinCross.graphics.lineStyle(2, 10040115); var w:Number = skinShapeContainer.width; var h:Number = skinShapeContainer.height; var min:Number = ((w >= h)) ? h : w; var off:Number = 5; skinCross.graphics.moveTo(((-(min) / 2) - off), ((-(min) / 2) - off)); skinCross.graphics.lineTo(((min / 2) + off), ((min / 2) + off)); skinCross.graphics.moveTo(((min / 2) + off), ((-(min) / 2) - off)); skinCross.graphics.lineTo(((-(min) / 2) - off), ((min / 2) + off)); } public function start():void{ getNextShape(); } private function mouseDownHandler(e:MouseEvent):void{ mouseDown = true; } public function initShapes(shapes:Array):void{ this.shapes = shapes; } private function drawCircleCross():void{ skinCross.graphics.clear(); skinCross.graphics.lineStyle(2, 10040115); var w:Number = skinShapeContainer.width; var h:Number = skinShapeContainer.height; var off:Number = -2; skinCross.graphics.moveTo(((-(w) / 2) - off), ((-(h) / 2) - off)); skinCross.graphics.lineTo(((w / 2) + off), ((h / 2) + off)); skinCross.graphics.moveTo(((w / 2) + off), ((-(h) / 2) - off)); skinCross.graphics.lineTo(((-(w) / 2) - off), ((h / 2) + off)); } private function getBodyObjectUnderPoint(p:Point):BodyObject{ var obj:BodyObject; var i:int; while (i < engine.objects.length) { obj = engine.objects[i]; if ((((obj is BodyObject)) && (obj.skin.hitTestPoint(p.x, p.y, true)))){ return (obj); }; i++; }; return (null); } private function getNextShape():void{ var innerColor:int; var outerColor:int; var color:int; var circleShape:CircleShape; var rectShape:RectShape; if (shapes.length > 0){ currentShape = shapes[0]; innerColor = 4796186; outerColor = 10446390; skinShapeContainer.graphics.clear(); color = 0; skinShapeContainer.graphics.lineStyle(0, innerColor); skinShapeContainer.graphics.beginBitmapFill(CoreCanvas.stickyBMD); if ((currentShape is CircleShape)){ circleShape = (currentShape as CircleShape); skinShapeContainer.graphics.drawCircle(0, 0, (circleShape.radius - 1)); skinShapeContainer.graphics.endFill(); skinShapeContainer.graphics.lineStyle(0, outerColor); skinShapeContainer.graphics.drawCircle(0, 0, circleShape.radius); drawCircleCross(); } else { if ((currentShape is RectShape)){ rectShape = (currentShape as RectShape); skinShapeContainer.graphics.drawRect(((-(rectShape.width) / 2) + 1), ((-(rectShape.height) / 2) + 1), (rectShape.width - 2), (rectShape.height - 2)); skinShapeContainer.graphics.endFill(); skinShapeContainer.graphics.lineStyle(0, outerColor); skinShapeContainer.graphics.drawRoundRect((-(rectShape.width) / 2), (-(rectShape.height) / 2), rectShape.width, rectShape.height, 6, 6); drawRectCross(); }; }; engine.shapeSelected(currentShape); createSensor(); } else { destroy(); }; } private function getStickyObjBySprite(objSkin:Sprite):StickyBodyObject{ var obj:BaseObject; var stickyObj:StickyBodyObject; var i:int; while (i < engine.objects.length) { obj = engine.objects[i]; if ((obj is StickyBodyObject)){ stickyObj = (obj as StickyBodyObject); if (stickyObj.skin == objSkin){ return (stickyObj); }; }; i++; }; return (null); } } }//package core.tools
Section 102
//BaseTool (core.tools.BaseTool) package core.tools { import core.*; public class BaseTool { protected var engine:CoreEngine; public function BaseTool():void{ super(); init(); } protected function init():void{ engine = CoreEngine.getInstance(); } } }//package core.tools
Section 103
//ObjectTool (core.tools.ObjectTool) package core.tools { import flash.events.*; import flash.display.*; import Box2D.Dynamics.*; import core.objects.*; import flash.geom.*; import Box2D.Common.Math.*; import Box2D.Dynamics.Joints.*; public class ObjectTool extends BaseTool { private var mouseJoint:b2MouseJoint; public function ObjectTool(){ super(); } override protected function init():void{ super.init(); engine.canvas.level.stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); } private function mouseDownHandler(e:MouseEvent):void{ var mx:Number = engine.canvas.level.mouseX; var my:Number = engine.canvas.level.mouseY; var bodyObj:BodyObject = getBodyObjByPoint(new Point(mx, my)); if (bodyObj){ run(bodyObj, false); }; } public function update():void{ var target:b2Vec2; var gr:Graphics; var a1:b2Vec2; var a2:b2Vec2; if (mouseJoint){ target = new b2Vec2((engine.canvas.level.mouseX / engine.physScale), (engine.canvas.level.mouseY / engine.physScale)); mouseJoint.SetTarget(target); gr = engine.canvas.gui.graphics; a1 = mouseJoint.GetAnchor1().Copy(); a2 = mouseJoint.GetAnchor2().Copy(); a1.Multiply(engine.physScale); a2.Multiply(engine.physScale); gr.clear(); gr.lineStyle(0, 1, 1); gr.moveTo(a1.x, a1.y); gr.lineTo(a2.x, a2.y); gr.beginFill(0, 1); gr.drawCircle(a1.x, a1.y, 3); gr.drawCircle(a2.x, a2.y, 3); gr.endFill(); }; } private function mouseUpHandler(e:MouseEvent):void{ engine.world.DestroyJoint(mouseJoint); mouseJoint = null; engine.canvas.level.stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); var gr:Graphics = engine.canvas.gui.graphics; gr.clear(); } protected function getBodyObjByPoint(p:Point):BodyObject{ var obj:BaseObject; var bodyObj:BodyObject; var i:int; while (i < engine.objects.length) { obj = engine.objects[i]; if ((obj is BodyObject)){ bodyObj = (obj as BodyObject); if (bodyObj.skin.hitTestPoint(p.x, p.y, true)){ return (bodyObj); }; }; i++; }; return (null); } public function run(obj:BaseObject, ctrl:Boolean):void{ var body:b2Body; var md:b2MouseJointDef; if (ctrl){ } else { body = engine.getBodyFromObj(obj); if (body){ md = new b2MouseJointDef(); md.body1 = engine.world.GetGroundBody(); md.body2 = body; md.target.Set((engine.canvas.level.mouseX / engine.physScale), (engine.canvas.level.mouseY / engine.physScale)); md.maxForce = (300 * body.GetMass()); md.timeStep = engine.timeStep; mouseJoint = (engine.world.CreateJoint(md) as b2MouseJoint); body.WakeUp(); engine.canvas.level.stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); }; }; } } }//package core.tools
Section 104
//ShapeItem (core.view.ShapeItem) package core.view { import core.*; import flash.display.*; import core.shapes.*; public class ShapeItem extends Sprite { public var shape:BaseShape; private var back:MovieClip; private var container:Sprite; private var engine:CoreEngine; private var skinShape:Sprite; private var window:Sprite; public function ShapeItem(shape:BaseShape):void{ super(); this.shape = shape; init(); } private function createShape():void{ var w:Number; var h:Number; var longest:Number; var ratio:Number; var maxSize:Number = 50; if ((shape is CircleShape)){ skinShape = new Sprite(); skinShape.graphics.lineStyle(0, 0); skinShape.graphics.beginBitmapFill(CoreCanvas.stickyBMD); skinShape.graphics.drawCircle(0, 0, (shape as CircleShape).radius); skinShape.graphics.endFill(); skinShape.width = (skinShape.height = ((shape as CircleShape).radius * 2)); if (skinShape.width > maxSize){ skinShape.width = (skinShape.height = maxSize); }; } else { if ((shape is RectShape)){ w = (shape as RectShape).width; h = (shape as RectShape).height; skinShape = new Sprite(); skinShape.graphics.lineStyle(0, 0); skinShape.graphics.beginBitmapFill(CoreCanvas.stickyBMD); skinShape.graphics.drawRect((-(w) / 2), (-(h) / 2), w, h); if ((((skinShape.width > maxSize)) || ((skinShape.height > maxSize)))){ longest = ((skinShape.width >= skinShape.height)) ? skinShape.width : skinShape.height; ratio = (maxSize / longest); skinShape.width = (skinShape.width * ratio); skinShape.height = (skinShape.height * ratio); }; }; }; container.addChild(skinShape); } private function init():void{ engine = CoreEngine.getInstance(); var WindowClass:Class = engine.assets.getAssetClass("ShapePreviewItemAsset"); window = new (WindowClass); addChild(window); back = (window.getChildByName("back") as MovieClip); container = (window.getChildByName("container") as Sprite); back.stop(); createShape(); } public function hide():void{ visible = false; } public function select():void{ back.gotoAndStop(2); } } }//package core.view
Section 105
//ShapesPreview (core.view.ShapesPreview) package core.view { import core.*; import flash.display.*; import core.shapes.*; public class ShapesPreview extends Sprite { private var itemsContainer:Sprite; private var engine:CoreEngine; private var items:Array; private var window:Sprite; public function ShapesPreview():void{ super(); init(); } public function selectShape(shape:BaseShape):void{ var item:ShapeItem = getItemByShape(shape); item.select(); } private function getItemByShape(shape:BaseShape):ShapeItem{ var item:ShapeItem; var i:int; while (i < items.length) { item = items[i]; if (item.shape == shape){ return (item); }; i++; }; return (null); } private function createItems():void{ var item:ShapeItem; var shapes:Array = engine.addShapeTool.shapes; items = []; var i:int; while (i < shapes.length) { item = new ShapeItem(shapes[i]); item.x = (i * 55); itemsContainer.addChild(item); items.push(item); i++; }; } private function init():void{ engine = CoreEngine.getInstance(); var WindowClass:Class = engine.assets.getAssetClass("ShapesPreviewWindow"); window = new (WindowClass); engine.canvas.gui.addChild(window); itemsContainer = (window.getChildByName("itemsContainer") as Sprite); itemsContainer.x = 5; itemsContainer.y = 5; createItems(); } public function hideShape(shape:BaseShape):void{ var item:ShapeItem = getItemByShape(shape); item.hide(); } } }//package core.view
Section 106
//WakeupMeter (core.view.WakeupMeter) package core.view { import core.*; import flash.display.*; import core.objects.*; public class WakeupMeter { private var skinInner:Sprite; private var engine:CoreEngine; private var skinBar:Sprite; private var progressWidth:Number; private var boxBase:BoxBase; private var skin:Sprite; public function WakeupMeter(boxBase:BoxBase):void{ super(); this.boxBase = boxBase; init(); } public function update():void{ var progress:Number = (boxBase.totalDist / BoxBase.REQUIRED_DISTANCE); if (progress > 1){ progress = 1; }; skinBar.x = (progress * progressWidth); } private function init():void{ var obj:BaseObject; engine = CoreEngine.getInstance(); var boxesBefore:int; var i:int; while (i < engine.objects.length) { obj = engine.objects[i]; if ((obj is BoxBase)){ boxesBefore++; }; i++; }; progressWidth = 82; var SkinClass:Class = engine.assets.getAssetClass("WakeupAsset"); skin = new (SkinClass); engine.canvas.gui.addChild(skin); skin.x = (470 - (boxesBefore * (progressWidth + 20))); skin.y = 5; skinInner = (skin.getChildByName("inner") as Sprite); skinBar = (skinInner.getChildByName("bar") as Sprite); skinBar.x = 0; } } }//package core.view
Section 107
//ContactsManager (core.ContactsManager) package core { import Box2D.Dynamics.*; import core.objects.*; import Box2D.Collision.*; import Box2D.Common.Math.*; import Box2D.Collision.Shapes.*; import Box2D.Dynamics.Contacts.*; public class ContactsManager extends b2ContactListener { private var engine:CoreEngine; public function ContactsManager():void{ super(); engine = CoreEngine.getInstance(); } override public function Add(point:b2ContactPoint):void{ checkBodyObjects(point.shape1, point.shape2, point); } private function checkBodyObjects(shape1:b2Shape, shape2:b2Shape, point:b2ContactPoint):void{ var body1:b2Body; var body2:b2Body; var hitValue:Number; var pos:b2Vec2; var obj1:BaseObject = shape1.m_userData; var obj2:BaseObject = shape2.m_userData; if ((obj1 is BodyObject)){ if ((obj2 is BodyObject)){ body1 = engine.getBodyFromObj(obj1); body2 = engine.getBodyFromObj(obj2); if (((body1) && (body2))){ hitValue = getHitValue(body1, body2, point.normal); pos = point.position.Copy(); pos.Multiply(engine.physScale); (obj1 as BodyObject).collideWithBodyObj(hitValue); }; }; }; } protected function getHitValue(body1:b2Body, body2:b2Body, normal:b2Vec2):Number{ var v1:b2Vec2 = body1.m_linearVelocity.Copy(); var v2:b2Vec2 = body2.m_linearVelocity.Copy(); v1.Subtract(v2); var hitValue:Number = Math.abs(b2Math.b2Dot(v1, normal)); hitValue = (hitValue / 10); if (hitValue > 1){ hitValue = 1; }; hitValue = (hitValue * 0.5); return (hitValue); } private function checkCollides(shape1:b2Shape, shape2:b2Shape, point:b2ContactResult):void{ var body1:b2Body; var body2:b2Body; var hitValue:Number; var pos:b2Vec2; var obj1:BaseObject = shape1.m_userData; var obj2:BaseObject = shape2.m_userData; if ((obj1 is Box)){ if ((obj2 is BodyObject)){ body1 = engine.getBodyFromObj(obj1); body2 = engine.getBodyFromObj(obj2); if (((body1) && (body2))){ hitValue = getHitValue(body1, body2, point.normal); pos = point.position.Copy(); pos.Multiply(engine.physScale); (obj1 as Box).collideWithBodyObj(hitValue); }; }; }; } } }//package core
Section 108
//CoreAssets (core.CoreAssets) package core { import flash.events.*; import flash.display.*; import flash.system.*; public class CoreAssets extends EventDispatcher { private var Assets:Class; private var appDomain:ApplicationDomain; public var inited:Boolean; private static var instance:CoreAssets; public function CoreAssets():void{ Assets = CoreAssets_Assets; super(); inited = false; } public function init():void{ var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.INIT, assetsInitHandler); loader.loadBytes(new Assets()); } private function assetsInitHandler(e:Event):void{ appDomain = e.target.content.loaderInfo.applicationDomain; inited = true; dispatchEvent(new Event(Event.INIT)); } public function getAssetClass(name:String):Class{ if (!appDomain.hasDefinition(name)){ trace((("*Error*: There is no definition of class '" + name) + "'")); return (null); }; return ((appDomain.getDefinition(name) as Class)); } public static function getInstance():CoreAssets{ if (!instance){ instance = new (CoreAssets); }; return (instance); } } }//package core
Section 109
//CoreAssets_Assets (core.CoreAssets_Assets) package core { import mx.core.*; public class CoreAssets_Assets extends ByteArrayAsset { } }//package core
Section 110
//CoreCanvas (core.CoreCanvas) package core { import flash.display.*; import flash.geom.*; import flash.filters.*; public class CoreCanvas { public var player:Sprite; public var container:Sprite; public var joints:Sprite; public var shapes:Sprite; public var level:Sprite; public var objects:Sprite; public var support:Sprite; public var backGfx:Sprite; public var debug:Sprite; public var gui:Sprite; public static var stickyBMD:BitmapData; public static var dynamicBMD:BitmapData; public static var staticBMD:BitmapData; public function CoreCanvas(container:Sprite):void{ super(); this.container = container; level = new Sprite(); container.addChild(level); backGfx = new Sprite(); level.addChild(backGfx); var shadows:Sprite = new Sprite(); level.addChild(shadows); objects = new Sprite(); shadows.addChild(objects); player = new Sprite(); shadows.addChild(player); joints = new Sprite(); shadows.addChild(joints); shapes = new Sprite(); level.addChild(shapes); support = new Sprite(); level.addChild(support); gui = new Sprite(); level.addChild(gui); debug = new Sprite(); level.addChild(debug); shadows.scrollRect = new Rectangle(0, 0, 640, 480); var shadow:DropShadowFilter = new DropShadowFilter(8, 45, 0, 0.3, 0, 0, 2, 2); shadows.filters = [shadow]; } public static function init():void{ var engine:CoreEngine = CoreEngine.getInstance(); var StaticBMDClass:Class = engine.assets.getAssetClass("StaticBMDAsset"); staticBMD = new StaticBMDClass(0, 0); var DynamicBMDClass:Class = engine.assets.getAssetClass("DynamicBMDAsset"); dynamicBMD = new DynamicBMDClass(0, 0); var StickyBMDClass:Class = engine.assets.getAssetClass("StickyBMDAsset"); stickyBMD = new StickyBMDClass(0, 0); } } }//package core
Section 111
//CoreEngine (core.CoreEngine) package core { import flash.events.*; import flash.display.*; import core.shapes.*; import Box2D.Dynamics.*; import core.objects.*; import flash.geom.*; import Box2D.Collision.*; import Box2D.Common.Math.*; import core.view.*; import core.tools.*; public class CoreEngine extends EventDispatcher { public var hintsManager:HintsManager; public var assets:CoreAssets; public var sounds:SoundsManager; private var currentLevel:CoreLevel; public var objects:Array; public var canvas:CoreCanvas; public var world:b2World; private var contactsManager:ContactsManager; public var physScale:Number;// = 30 public var elapsedTime:int; public var isLevelRestart:Boolean; public var shapesPreview:ShapesPreview; public var addShapeTool:AddShapeTool; public var timeStep:Number;// = 0.0333333333333333 private var iterations:int;// = 10 private var objectTool:ObjectTool; public static const LEVEL_COMPLETE:String = "LevelComplete"; private static var instance:CoreEngine; public function CoreEngine():void{ super(); init(); } public function levelStart(level:CoreLevel, container:Sprite):void{ currentLevel = level; canvas = new CoreCanvas(container); initBox2d(); hintsManager = new HintsManager(); elapsedTime = 0; canvas.level.addEventListener(Event.ENTER_FRAME, efHandler); } public function destroy():void{ } public function levelAbort():void{ var obj:BaseObject; canvas.level.removeEventListener(Event.ENTER_FRAME, efHandler); var i:int; while (i < objects.length) { obj = objects[i]; obj.destroy(); i++; }; if (addShapeTool){ addShapeTool.destroy(); }; } private function initBox2d():void{ var worldAABB:b2AABB = new b2AABB(); worldAABB.lowerBound.Set(-1000, -1000); worldAABB.upperBound.Set(1000, 1000); var gravity:b2Vec2 = new b2Vec2(0, 10); var doSleep:Boolean; world = new b2World(worldAABB, gravity, doSleep); var dbgDraw:b2DebugDraw = new b2DebugDraw(); var dbgDrawContainer:Sprite = canvas.debug; dbgDrawContainer.mouseEnabled = false; dbgDrawContainer.mouseChildren = false; dbgDraw.m_sprite = dbgDrawContainer; dbgDraw.m_drawScale = physScale; dbgDraw.m_fillAlpha = 0.7; dbgDraw.m_lineThickness = 1; dbgDraw.m_drawFlags = ((b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit) | b2DebugDraw.e_pairBit); contactsManager = new ContactsManager(); world.SetContactListener(contactsManager); } private function init():void{ } public function boxAwakened():void{ var obj:BaseObject; var boxBase:BoxBase; var i:int; while (i < objects.length) { obj = objects[i]; if ((obj is BoxBase)){ boxBase = (obj as BoxBase); if (boxBase.state != BoxBase.STATE_AWAKE){ return; }; }; i++; }; dispatchEvent(new CoreEvent(LEVEL_COMPLETE)); } public function initialize():void{ assets = CoreAssets.getInstance(); sounds = SoundsManager.getInstance(); CoreCanvas.init(); } private function createWalls():void{ var wall:BodyObject; var thickness:Number = 40; var wallShape:RectShape = new RectShape(1, 1); var px:Array = [(-(thickness) / 2), (640 + (thickness / 2)), 320, 320]; var py:Array = [240, 240, (-(thickness) / 2), (480 + (thickness / 2))]; var widths:Array = [thickness, thickness, 640, 640]; var heights:Array = [480, 480, thickness, thickness]; var i:int; while (i < 4) { wall = new BodyObject(px[i], py[i], true); wallShape.width = widths[i]; wallShape.height = heights[i]; wall.addRectShape(wallShape, new Point(px[i], py[i])); objects.push(wall); i++; }; } public function shapeUsed(shape:BaseShape):void{ shapesPreview.hideShape(shape); } private function efHandler(e:Event):void{ if (addShapeTool){ addShapeTool.preUpdate(); }; world.Step(timeStep, iterations); updateObjects(); if (addShapeTool){ addShapeTool.update(); }; hintsManager.update(); elapsedTime++; } private function updateObjects():void{ var obj:BaseObject; var i:uint; while (i < objects.length) { obj = objects[i]; obj.update(); i++; }; } public function shapeSelected(shape:BaseShape):void{ shapesPreview.selectShape(shape); } public function getBodyFromObj(obj:BaseObject):b2Body{ var body:b2Body; if ((obj is BodyObject)){ body = (obj as BodyObject).body; } else { if ((obj is ShapeSensor)){ body = (obj as ShapeSensor).body; }; }; return (body); } public static function getInstance():CoreEngine{ if (instance == null){ instance = new (CoreEngine); }; return (instance); } } }//package core
Section 112
//CoreEvent (core.CoreEvent) package core { import flash.events.*; public class CoreEvent extends Event { public var data:Object; public function CoreEvent(type:String, data:Object=null, bubbles:Boolean=false, cancelable:Boolean=false):void{ super(type, bubbles, cancelable); this.data = data; } } }//package core
Section 113
//CoreLevel (core.CoreLevel) package core { public class CoreLevel { public var isCompleted:Boolean; public var isOpen:Boolean; public var score:int; public var id:int; public var completeTime:int; public function CoreLevel(id:int):void{ super(); this.id = id; isCompleted = false; isOpen = false; score = 0; } public function complete(time:int):void{ isCompleted = true; completeTime = time; var newScore:int = (500 - Math.floor((completeTime / 10))); if (newScore > score){ score = newScore; }; } } }//package core
Section 114
//HintsManager (core.HintsManager) package core { import flash.display.*; import caurina.transitions.*; public class HintsManager { private var engine:CoreEngine; private var hints:Array; private var time:int; private var delayTime:int; public function HintsManager():void{ super(); init(); } private function startHint():void{ var hint:Sprite = hints[0]; hints.splice(0, 1); var hintY:Number = hint.y; hint.y = (hint.y - 30); Tweener.addTween(hint, {alpha:1, y:hintY, time:1, transition:"easeoutquad"}); } public function update():void{ if (time >= delayTime){ time = 0; if (hints.length > 0){ startHint(); }; }; time++; } private function init():void{ engine = CoreEngine.getInstance(); delayTime = 100; time = (delayTime - 10); hints = []; } public function parseHints(levelSprite:Sprite):void{ var i:int; var hint:Sprite; var hintsSprite:Sprite = (levelSprite.getChildByName("hints") as Sprite); if (hintsSprite){ engine.canvas.gui.addChild(hintsSprite); i = 0; while (i < hintsSprite.numChildren) { hint = (hintsSprite.getChildByName(("h" + i)) as Sprite); if (hint){ hint.alpha = 0; hints.push(hint); } else { break; }; i++; }; }; } } }//package core
Section 115
//SoundsManager (core.SoundsManager) package core { import game.model.*; import flash.media.*; public class SoundsManager { public var sndHitBox:Sound; private var engine:CoreEngine; public var sndAddShape:Sound; public var sndImpact:Sound; private var sndChannel:SoundChannel; private static var instance:SoundsManager; public function SoundsManager():void{ super(); init(); } private function init():void{ engine = CoreEngine.getInstance(); var SndImpactClass:Class = engine.assets.getAssetClass("SndImpact"); sndImpact = new (SndImpactClass); var SndHitBoxClass:Class = engine.assets.getAssetClass("SndHitBox"); sndHitBox = new (SndHitBoxClass); var SndAddShapeClass:Class = engine.assets.getAssetClass("SndAddShape"); sndAddShape = new (SndAddShapeClass); } public function playSound(snd:Sound, volume:Number):void{ if (SaveData.getInstance().soundEnabled){ sndChannel = snd.play(0, 0, new SoundTransform(volume)); }; } public static function getInstance():SoundsManager{ if (instance == null){ instance = new (SoundsManager); }; return (instance); } } }//package core
Section 116
//EditorCloseCommand (editor.controller.EditorCloseCommand) package editor.controller { import org.puremvc.as3.interfaces.*; import editor.model.*; import org.puremvc.as3.patterns.command.*; import editor.view.*; public class EditorCloseCommand extends SimpleCommand implements ICommand { public function EditorCloseCommand(){ super(); } override public function execute(note:INotification):void{ var editorMed:EditorMediator = (facade.retrieveMediator(EditorMediator.NAME) as EditorMediator); editorMed.destroy(); var gridProxy:GridProxy = (facade.retrieveProxy(GridProxy.NAME) as GridProxy); gridProxy.destroy(); var editorProxy:EditorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); editorProxy.destroy(); facade.removeProxy(LevelProxy.NAME); } } }//package editor.controller
Section 117
//EditorStartCommand (editor.controller.EditorStartCommand) package editor.controller { import org.puremvc.as3.interfaces.*; import editor.model.*; import editor.view.components.*; import org.puremvc.as3.patterns.command.*; import game.view.*; import editor.view.*; public class EditorStartCommand extends SimpleCommand implements ICommand { public function EditorStartCommand(){ super(); } override public function execute(note:INotification):void{ var editorProxy:EditorProxy = new EditorProxy(); facade.registerProxy(editorProxy); var levelProxy:LevelProxy = new LevelProxy(); facade.registerProxy(levelProxy); var gridProxy:GridProxy = new GridProxy(); facade.registerProxy(gridProxy); var editorView:EditorView = new EditorView(); var appMed:AppMediator = (facade.retrieveMediator(AppMediator.NAME) as AppMediator); appMed.getViewContainer().addChild(editorView); var editorMed:EditorMediator = new EditorMediator(editorView); facade.registerMediator(editorMed); } } }//package editor.controller
Section 118
//ELevelAbortCommand (editor.controller.ELevelAbortCommand) package editor.controller { import org.puremvc.as3.interfaces.*; import editor.model.*; import org.puremvc.as3.patterns.command.*; import editor.view.*; public class ELevelAbortCommand extends SimpleCommand implements ICommand { public function ELevelAbortCommand(){ super(); } override public function execute(note:INotification):void{ var levelProxy:LevelProxy = (facade.retrieveProxy(LevelProxy.NAME) as LevelProxy); levelProxy.levelAbort(); var levelTestMed:LevelTestMediator = (facade.retrieveMediator(LevelTestMediator.NAME) as LevelTestMediator); levelTestMed.destroy(); var levelCompleteMed:ELevelCompleteMediator = (facade.retrieveMediator(ELevelCompleteMediator.NAME) as ELevelCompleteMediator); if (levelCompleteMed){ levelCompleteMed.destroy(); }; } } }//package editor.controller
Section 119
//ELevelCompleteCommand (editor.controller.ELevelCompleteCommand) package editor.controller { import org.puremvc.as3.interfaces.*; import editor.model.*; import editor.view.components.*; import org.puremvc.as3.patterns.command.*; import game.view.*; import editor.view.*; public class ELevelCompleteCommand extends SimpleCommand implements ICommand { public function ELevelCompleteCommand(){ super(); } override public function execute(note:INotification):void{ var levelProxy:LevelProxy = (facade.retrieveProxy(LevelProxy.NAME) as LevelProxy); var appMed:AppMediator = (facade.retrieveMediator(AppMediator.NAME) as AppMediator); var levelCompleteView:ELevelCompleteView = new ELevelCompleteView(); appMed.getViewContainer().addChild(levelCompleteView); var levelCompleteMed:ELevelCompleteMediator = new ELevelCompleteMediator(levelCompleteView); facade.registerMediator(levelCompleteMed); } } }//package editor.controller
Section 120
//ELevelStartCommand (editor.controller.ELevelStartCommand) package editor.controller { import org.puremvc.as3.interfaces.*; import editor.model.*; import editor.view.components.*; import org.puremvc.as3.patterns.command.*; import game.view.*; import editor.view.*; public class ELevelStartCommand extends SimpleCommand implements ICommand { public function ELevelStartCommand(){ super(); } override public function execute(note:INotification):void{ var levelTestView:LevelTestView = new LevelTestView(); var appMed:AppMediator = (facade.retrieveMediator(AppMediator.NAME) as AppMediator); appMed.getViewContainer().addChild(levelTestView); var levelTestMed:LevelTestMediator = new LevelTestMediator(levelTestView); facade.registerMediator(levelTestMed); var levelProxy:LevelProxy = (facade.retrieveProxy(LevelProxy.NAME) as LevelProxy); levelProxy.levelStart((note.getBody() as Boolean)); } } }//package editor.controller
Section 121
//ObjectAddCommand (editor.controller.ObjectAddCommand) package editor.controller { import org.puremvc.as3.interfaces.*; import editor.model.*; import editor.model.objects.*; import org.puremvc.as3.patterns.command.*; public class ObjectAddCommand extends SimpleCommand implements ICommand { public function ObjectAddCommand(){ super(); } override public function execute(note:INotification):void{ var editorProxy:EditorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); editorProxy.objectAdd((note.getBody() as BaseObjectDef)); } } }//package editor.controller
Section 122
//ObjectRemoveCommand (editor.controller.ObjectRemoveCommand) package editor.controller { import org.puremvc.as3.interfaces.*; import editor.model.*; import editor.model.objects.*; import org.puremvc.as3.patterns.command.*; public class ObjectRemoveCommand extends SimpleCommand implements ICommand { public function ObjectRemoveCommand(){ super(); } override public function execute(note:INotification):void{ var editorProxy:EditorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); editorProxy.objectRemove((note.getBody() as BaseObjectDef)); } } }//package editor.controller
Section 123
//ObjectsSelectCommand (editor.controller.ObjectsSelectCommand) package editor.controller { import org.puremvc.as3.interfaces.*; import editor.model.*; import org.puremvc.as3.patterns.command.*; public class ObjectsSelectCommand extends SimpleCommand implements ICommand { public function ObjectsSelectCommand(){ super(); } override public function execute(note:INotification):void{ var editorProxy:EditorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); editorProxy.objectsSelect((note.getBody() as Array)); } } }//package editor.controller
Section 124
//ShapeAddCommand (editor.controller.ShapeAddCommand) package editor.controller { import org.puremvc.as3.interfaces.*; import editor.model.*; import core.shapes.*; import org.puremvc.as3.patterns.command.*; public class ShapeAddCommand extends SimpleCommand implements ICommand { public function ShapeAddCommand(){ super(); } override public function execute(note:INotification):void{ var editorProxy:EditorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); var params:Array = (note.getBody() as Array); var shape:BaseShape = params[0]; var index:int = params[1]; editorProxy.shapeAdd(shape, index); } } }//package editor.controller
Section 125
//ToolSelectCommand (editor.controller.ToolSelectCommand) package editor.controller { import org.puremvc.as3.interfaces.*; import editor.model.*; import org.puremvc.as3.patterns.command.*; public class ToolSelectCommand extends SimpleCommand implements ICommand { public function ToolSelectCommand(){ super(); } override public function execute(note:INotification):void{ var editorProxy:EditorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); editorProxy.selectedTool = (note.getBody() as Tool); } } }//package editor.controller
Section 126
//BaseObjectDef (editor.model.objects.BaseObjectDef) package editor.model.objects { import flash.display.*; import flash.geom.*; public class BaseObjectDef { public var x:Number; public var y:Number; public var skin:Sprite; public static const TYPE_WOOD:String = "TypeWood"; public static const TYPE_METAL:String = "TypeMetal"; public static const TYPE_BRICK:String = "TypeBrick"; public function BaseObjectDef(x:Number, y:Number):void{ super(); this.x = x; this.y = y; } public function isPointInside(p:Point):Boolean{ return (false); } public function isRectInside(rect:Rectangle):Boolean{ return (false); } public function getSkin():Sprite{ return (skin); } public function translate(dx:Number, dy:Number):void{ x = (x + dx); y = (y + dy); } public function getBoundingBox():Rectangle{ return (new Rectangle(-10, -10, 20, 20)); } public function getStringDef():String{ return (""); } } }//package editor.model.objects
Section 127
//CircleDef (editor.model.objects.CircleDef) package editor.model.objects { import flash.geom.*; public class CircleDef extends BaseObjectDef { public var r:Number; public var type:String; public static const NAME:String = "CircleDef"; public function CircleDef(x:Number, y:Number, r:Number, type:String):void{ this.r = r; this.type = type; super(x, y); } override public function getBoundingBox():Rectangle{ return (new Rectangle(-(r), -(r), (r * 2), (r * 2))); } override public function isPointInside(p:Point):Boolean{ var dist:Number = Math.sqrt((((p.x - x) * (p.x - x)) + ((p.y - y) * (p.y - y)))); return (((dist < r)) ? true : false); } override public function isRectInside(rect:Rectangle):Boolean{ return ((((((((x > rect.x)) && ((x < (rect.x + rect.width))))) && ((y > rect.y)))) && ((y < (rect.y + rect.height))))); } override public function getStringDef():String{ var def = (NAME + "_"); def = (def + (x + "_")); def = (def + (y + "_")); def = (def + (r + "_")); def = (def + type); return (def); } public static function parseStringDef(stringDef:String):CircleDef{ var props:Array = stringDef.split("_"); var x:Number = props[1]; var y:Number = props[2]; var r:Number = props[3]; var type:String = props[4]; var def:CircleDef = new CircleDef(x, y, r, type); return (def); } } }//package editor.model.objects
Section 128
//DistJointDef (editor.model.objects.DistJointDef) package editor.model.objects { import flash.geom.*; public class DistJointDef extends BaseObjectDef { public var x1:Number; public var y1:Number; public var y2:Number; public var x2:Number; public static const NAME:String = "DistJointDef"; public function DistJointDef(x:Number, y:Number, x1:Number, y1:Number, x2:Number, y2:Number):void{ this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; super(x, y); } override public function isPointInside(p:Point):Boolean{ var segment1:Boolean; var segment2:Boolean; if ((((((p.x > (x1 - 2))) && ((p.x < (x2 + 2))))) || ((((p.x > (x2 - 2))) && ((p.x < (x1 + 2))))))){ segment1 = true; }; if ((((((p.y > (y1 - 2))) && ((p.y < (y2 + 2))))) || ((((p.y > (y2 - 2))) && ((p.y < (y1 + 2))))))){ segment2 = true; }; if (((!(segment1)) || (!(segment2)))){ return (false); }; var length:Number = Math.sqrt((((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)))); var dist1:Number = Math.sqrt((((p.x - x1) * (p.x - x1)) + ((p.y - y1) * (p.y - y1)))); var dist2:Number = Math.sqrt((((p.x - x2) * (p.x - x2)) + ((p.y - y2) * (p.y - y2)))); return ((((dist1 + dist2) - length) < 2)); } override public function isRectInside(rect:Rectangle):Boolean{ return ((((((((x > rect.x)) && ((x < (rect.x + rect.width))))) && ((y > rect.y)))) && ((y < (rect.y + rect.height))))); } override public function translate(dx:Number, dy:Number):void{ x = (x + dx); y = (y + dy); x1 = (x1 + dx); y1 = (y1 + dy); x2 = (x2 + dx); y2 = (y2 + dy); } override public function getStringDef():String{ var def = (NAME + "_"); def = (def + (x + "_")); def = (def + (y + "_")); def = (def + (x1 + "_")); def = (def + (y1 + "_")); def = (def + (x2 + "_")); def = (def + y2); return (def); } public static function parseStringDef(stringDef:String):DistJointDef{ var props:Array = stringDef.split("_"); var x:uint = props[1]; var y:uint = props[2]; var x1:Number = props[3]; var y1:Number = props[4]; var x2:Number = props[5]; var y2:Number = props[6]; var def:DistJointDef = new DistJointDef(x, y, x1, y1, x2, y2); return (def); } } }//package editor.model.objects
Section 129
//MotorDef (editor.model.objects.MotorDef) package editor.model.objects { public class MotorDef extends RevJointDef { public var torque:Number; public static const NAME:String = "Motor"; public function MotorDef(x:Number, y:Number, torque:Number=0):void{ this.torque = torque; super(x, y); } override public function getStringDef():String{ var def = (NAME + "_"); def = (def + (x + "_")); def = (def + (y + "_")); def = (def + torque); return (def); } public static function parseStringDef(stringDef:String):MotorDef{ var props:Array = stringDef.split("_"); var x:Number = props[1]; var y:Number = props[2]; var torque:Number = props[3]; var def:MotorDef = new MotorDef(x, y, torque); return (def); } } }//package editor.model.objects
Section 130
//PlayerDef (editor.model.objects.PlayerDef) package editor.model.objects { public class PlayerDef extends RectDef { public static const NAME:String = "PlayerDef"; public function PlayerDef(x:Number, y:Number):void{ super(x, y, 64, 50, BaseObjectDef.TYPE_METAL); } override public function getStringDef():String{ var def = (NAME + "_"); def = (def + (x + "_")); def = (def + y); return (def); } public static function parseStringDef(stringDef:String):PlayerDef{ var props:Array = stringDef.split("_"); var x:Number = props[1]; var y:Number = props[2]; var def:PlayerDef = new PlayerDef(x, y); return (def); } } }//package editor.model.objects
Section 131
//RectDef (editor.model.objects.RectDef) package editor.model.objects { import flash.geom.*; public class RectDef extends BaseObjectDef { public var width:Number; public var height:Number; public var type:String; public var rotation:Number;// = 0 public static const NAME:String = "RectDef"; public function RectDef(x:Number, y:Number, width:Number, height:Number, type:String):void{ this.width = width; this.height = height; this.type = type; super(x, y); } override public function isPointInside(p:Point):Boolean{ return ((((((((p.x > (x - (width / 2)))) && ((p.x < (x + (width / 2)))))) && ((p.y > (y - (height / 2)))))) && ((p.y < (y + (height / 2)))))); } override public function getStringDef():String{ var def = (NAME + "_"); def = (def + (x + "_")); def = (def + (y + "_")); def = (def + (width + "_")); def = (def + (height + "_")); def = (def + type); return (def); } override public function isRectInside(rect:Rectangle):Boolean{ return ((((((((x > rect.x)) && ((x < (rect.x + rect.width))))) && ((y > rect.y)))) && ((y < (rect.y + rect.height))))); } override public function getBoundingBox():Rectangle{ return (new Rectangle((-(width) / 2), (-(height) / 2), width, height)); } public static function parseStringDef(stringDef:String):RectDef{ var props:Array = stringDef.split("_"); var x:Number = props[1]; var y:Number = props[2]; var width:Number = props[3]; var height:Number = props[4]; var type:String = props[5]; var def:RectDef = new RectDef(x, y, width, height, type); return (def); } } }//package editor.model.objects
Section 132
//RevJointDef (editor.model.objects.RevJointDef) package editor.model.objects { import flash.geom.*; public class RevJointDef extends BaseObjectDef { public static const NAME:String = "RevJoint"; public function RevJointDef(x:Number, y:Number):void{ super(x, y); } override public function getBoundingBox():Rectangle{ return (new Rectangle(-10, -10, (10 * 2), (10 * 2))); } override public function isPointInside(p:Point):Boolean{ var dist:Number = Math.sqrt((((p.x - x) * (p.x - x)) + ((p.y - y) * (p.y - y)))); return (((dist < 5)) ? true : false); } override public function isRectInside(rect:Rectangle):Boolean{ return ((((((((x > rect.x)) && ((x < (rect.x + rect.width))))) && ((y > rect.y)))) && ((y < (rect.y + rect.height))))); } override public function getStringDef():String{ var def = (NAME + "_"); def = (def + (x + "_")); def = (def + y); return (def); } public static function parseStringDef(stringDef:String):RevJointDef{ var props:Array = stringDef.split("_"); var x:Number = props[1]; var y:Number = props[2]; var def:RevJointDef = new RevJointDef(x, y); return (def); } } }//package editor.model.objects
Section 133
//EditorAssets (editor.model.EditorAssets) package editor.model { import flash.events.*; import flash.display.*; import flash.system.*; public class EditorAssets extends EventDispatcher { private var Assets:Class; private var appDomain:ApplicationDomain; private static var instance:EditorAssets; public function EditorAssets(){ Assets = EditorAssets_Assets; super(); } public function init():void{ var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.INIT, assetsInitHandler); loader.loadBytes(new Assets()); } public function GameAssets():void{ } private function assetsInitHandler(e:Event):void{ appDomain = e.target.content.loaderInfo.applicationDomain; dispatchEvent(new Event(Event.INIT)); } public function getAssetClass(name:String):Class{ if (!appDomain.hasDefinition(name)){ trace((("*Error*: There is no definition of class '" + name) + "'")); return (null); }; return ((appDomain.getDefinition(name) as Class)); } public static function getInstance():EditorAssets{ if (!instance){ instance = new (EditorAssets); }; return (instance); } } }//package editor.model
Section 134
//EditorAssets_Assets (editor.model.EditorAssets_Assets) package editor.model { import mx.core.*; public class EditorAssets_Assets extends ByteArrayAsset { } }//package editor.model
Section 135
//EditorProxy (editor.model.EditorProxy) package editor.model { import flash.display.*; import game.model.*; import core.shapes.*; import editor.model.objects.*; import flash.geom.*; import editor.view.components.*; import org.puremvc.as3.patterns.proxy.*; import editor.controller.*; import editor.view.*; public class EditorProxy extends Proxy { private var canvasScale:Number; public var selectedTool:Tool; private var objects:Array; private var selectedObjs:Array; private var tools:Array; public var levelID:int; private var notesProxy:NotesProxy; public var levelName:String; public var cuts:int; public var shapes:Array; public var levelDesc:String; private var isPublishing:Boolean; public static const OBJECT_ADD:String = "ObjectAdd"; public static const TOOL_SELECT:String = "ToolSelect"; public static const OBJECT_REMOVE:String = "ObjectRemove"; public static const EDITOR_CLOSE:String = "EditorClose"; public static const OBJECTS_SELECT:String = "ObjectsSelect"; public static const OBJECT_UPDATE:String = "ObjectUpdate"; public static const NAME:String = "EditorProxy"; public static const ELEVEL_ABORT:String = "ELevelAbort"; public static const ELEVEL_COMPLETE:String = "EditorLevelComplete"; public static const ELEVEL_START:String = "ELevelStart"; public static const SHAPE_ADD:String = "ShapeAdd"; public static const SAVE_COMPLETE:String = "SaveComplete"; public function EditorProxy():void{ super(NAME); init(); } public function shapeAdd(shape:BaseShape, index:int):void{ shapes[index] = shape; } public function deleteObjects():void{ var obj:BaseObjectDef; var i:int = (objects.length - 1); while (i >= 0) { obj = objects[i]; if ((obj is PlayerDef)){ obj.x = 100; obj.y = 100; notesProxy.push(OBJECT_UPDATE, obj); } else { notesProxy.push(EditorProxy.OBJECT_REMOVE, obj); }; i--; }; } public function getObjsUnderRect(rect:Rectangle):Array{ var obj:BaseObjectDef; var objs:Array = []; var i:uint; while (i < objects.length) { obj = objects[i]; if (obj.isRectInside(rect)){ objs.push(obj); }; i++; }; return (objs); } private function someLevels():void{ } public function getLevelDef():String{ var i:int; var obj:BaseObjectDef; var objDef:String; var shape:BaseShape; var objectsDef:String = ""; i = 0; while (i < objects.length) { obj = objects[i]; objDef = obj.getStringDef(); objectsDef = (objectsDef + (objDef + "|")); i++; }; var shapesDef:String = ""; i = 0; while (i < shapes.length) { shape = shapes[i]; if (shape){ shapesDef = (shapesDef + (shape.getStringDef() + "|")); }; i++; }; var levelDef:String = ((objectsDef + " ") + shapesDef); return (levelDef); } public function loadLevel(levelDef:String):void{ deleteObjects(); var defs:Array = levelDef.split(" "); var objectsDef:String = defs[0]; var shapesDef:String = defs[1]; var oDefs:Array = objectsDef.split("|"); loadObjects(oDefs); var sDefs:Array = shapesDef.split("|"); loadShapes(sDefs); } private function checkRectRect(rect1:Rectangle, rect2:Rectangle):Boolean{ var hcollide:Boolean; var vcollide:Boolean; if ((((((rect1.x < rect2.x)) && (((rect1.x + rect1.width) > rect2.x)))) || ((((rect1.x > rect2.x)) && ((rect1.x < (rect2.x + rect2.width))))))){ hcollide = true; }; if ((((((rect1.y < rect2.y)) && (((rect1.y + rect1.height) > rect2.y)))) || ((((rect1.y > rect2.y)) && ((rect1.y < (rect2.y + rect2.height))))))){ vcollide = true; }; return ((((hcollide) && (vcollide))) ? true : false); } public function getSelectedObjects():Array{ return (selectedObjs); } public function getObjects():Array{ return (objects); } private function initTools():void{ tools = []; var selectionTool:Tool = new Tool(0, Tool.TYPE_SELECTION); tools.push(selectionTool); var circleTool:Tool = new Tool(1, Tool.TYPE_CIRCLE); tools.push(circleTool); var rectTool:Tool = new Tool(2, Tool.TYPE_RECT); tools.push(rectTool); var distJointTool:Tool = new Tool(3, Tool.TYPE_DIST_JOINT); tools.push(distJointTool); var revJointTool:Tool = new Tool(4, Tool.TYPE_REV_JOINT); tools.push(revJointTool); var motorTool:Tool = new Tool(5, Tool.TYPE_MOTOR); tools.push(motorTool); } private function loadObjects(objs:Array):void{ var objDef:String; var params:Array; var objName:String; var obj:BaseObjectDef; var playerObj:PlayerDef; var i:uint; while (i < objs.length) { objDef = objs[i]; params = objDef.split("_"); objName = params[0]; obj = null; switch (objName){ case CircleDef.NAME: obj = CircleDef.parseStringDef(objDef); break; case RectDef.NAME: obj = RectDef.parseStringDef(objDef); break; case PlayerDef.NAME: obj = PlayerDef.parseStringDef(objDef); break; case DistJointDef.NAME: obj = DistJointDef.parseStringDef(objDef); break; case RevJointDef.NAME: obj = RevJointDef.parseStringDef(objDef); break; case MotorDef.NAME: obj = MotorDef.parseStringDef(objDef); break; }; if ((obj is PlayerDef)){ playerObj = objects[0]; playerObj.x = obj.x; playerObj.y = obj.y; notesProxy.push(OBJECT_UPDATE, playerObj); } else { if (obj != null){ notesProxy.push(OBJECT_ADD, obj); }; }; i++; }; } private function init():void{ if (!facade.hasCommand(OBJECT_ADD)){ facade.registerCommand(OBJECT_ADD, ObjectAddCommand); }; if (!facade.hasCommand(OBJECTS_SELECT)){ facade.registerCommand(OBJECTS_SELECT, ObjectsSelectCommand); }; if (!facade.hasCommand(ELEVEL_START)){ facade.registerCommand(ELEVEL_START, ELevelStartCommand); }; if (!facade.hasCommand(ELEVEL_ABORT)){ facade.registerCommand(ELEVEL_ABORT, ELevelAbortCommand); }; if (!facade.hasCommand(ELEVEL_COMPLETE)){ facade.registerCommand(ELEVEL_COMPLETE, ELevelCompleteCommand); }; if (!facade.hasCommand(OBJECT_REMOVE)){ facade.registerCommand(OBJECT_REMOVE, ObjectRemoveCommand); }; if (!facade.hasCommand(EDITOR_CLOSE)){ facade.registerCommand(EDITOR_CLOSE, EditorCloseCommand); }; if (!facade.hasCommand(TOOL_SELECT)){ facade.registerCommand(TOOL_SELECT, ToolSelectCommand); }; if (!facade.hasCommand(SHAPE_ADD)){ facade.registerCommand(SHAPE_ADD, ShapeAddCommand); }; notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); initTools(); objects = []; selectedObjs = []; canvasScale = 1; var playerObj:PlayerDef = new PlayerDef(100, 100); notesProxy.push(OBJECT_ADD, playerObj); levelID = 0; levelDesc = "Description"; levelName = "name"; someLevels(); shapes = []; } public function deleteSelectedObjects():void{ var obj:BaseObjectDef; var obj2:BaseObjectDef; var objs:Array = getSelectedObjects(); var objsToRemove:Array = []; var i:uint; while (i < objs.length) { obj = objs[i]; if ((obj is PlayerDef)){ } else { objsToRemove.push(obj); }; i++; }; while (objsToRemove.length > 0) { obj2 = objsToRemove.pop(); notesProxy.push(OBJECT_REMOVE, obj2); }; } public function canvasTranslate(dx:Number, dy:Number):void{ var editorMed:EditorMediator = (facade.retrieveMediator(EditorMediator.NAME) as EditorMediator); var editorView:EditorView = (editorMed.getViewComponent() as EditorView); var canvas:Sprite = editorView.canvas; canvas.x = (canvas.x + dx); canvas.y = (canvas.y + dy); editorView.support.x = canvas.x; editorView.support.y = canvas.y; } public function destroy():void{ facade.retrieveProxy(NAME); } public function objectRemove(obj:BaseObjectDef):void{ var index:int = objects.indexOf(obj); if (index != -1){ objects.splice(index, 1); }; var index2:int = selectedObjs.indexOf(obj); if (index2 != -1){ selectedObjs.splice(index2, 1); }; } public function getTools():Array{ return (tools); } public function objectAdd(obj:BaseObjectDef):void{ objects.push(obj); } public function objectsSelect(objs:Array):void{ selectedObjs = objs; } private function loadShapes(shapeDefs:Array):void{ var shapeDef:String; var params:Array; var shapeName:String; var shape:BaseShape; shapes = []; var i:int; while (i < shapeDefs.length) { shapeDef = shapeDefs[i]; params = shapeDef.split("_"); shapeName = params[0]; shape = null; switch (shapeName){ case CircleShape.NAME: shape = CircleShape.parseStringDef(shapeDef); break; case RectShape.NAME: shape = RectShape.parseStringDef(shapeDef); break; }; if (shape){ notesProxy.push(SHAPE_ADD, [shape, i]); }; i++; }; } public function getObjUnderPoint(p:Point):BaseObjectDef{ var i:int; var obj:BaseObjectDef; var playerObj:PlayerDef = objects[0]; if (playerObj.isPointInside(p)){ return (playerObj); }; i = (objects.length - 1); while (i >= 0) { obj = objects[i]; if ((((obj is DistJointDef)) || ((obj is RevJointDef)))){ if (obj.isPointInside(p)){ return (obj); }; }; i--; }; i = (objects.length - 1); while (i >= 0) { obj = objects[i]; if (obj.isPointInside(p)){ return (obj); }; i--; }; return (null); } private function checkRectPoint(rect:Rectangle, p:Point):Boolean{ if ((((((((p.x > rect.x)) && ((p.x < (rect.x + rect.width))))) && ((p.y > rect.y)))) && ((p.y < (rect.y + rect.height))))){ return (true); }; return (false); } } }//package editor.model
Section 136
//GridProxy (editor.model.GridProxy) package editor.model { import flash.geom.*; import org.puremvc.as3.patterns.proxy.*; public class GridProxy extends Proxy { public var showGrid:Boolean; public var cellWidth:Number; public var cellHeight:Number; public var snap:Boolean; public static const NAME:String = "GridProxy"; public function GridProxy():void{ super(NAME); init(); } private function init():void{ showGrid = false; snap = true; cellWidth = 5; cellHeight = 5; } public function destroy():void{ facade.removeProxy(NAME); } public function getSnapPoint(p:Point):Point{ var x:Number; var y:Number; if (snap){ x = (Math.round((p.x / cellWidth)) * cellWidth); y = (Math.round((p.y / cellHeight)) * cellHeight); return (new Point(x, y)); }; return (p); } } }//package editor.model
Section 137
//LevelProxy (editor.model.LevelProxy) package editor.model { import core.*; import game.model.*; import org.puremvc.as3.patterns.proxy.*; import editor.view.*; public class LevelProxy extends Proxy { private var engine:CoreEngine; private var notesProxy:NotesProxy; public var publish:Boolean; public static const SPLIT_NOT_AVAILABLE:String = "SplitNotAvailable"; public static const NAME:String = "LevelProxy"; public static const SPLIT_SUCCESS:String = "SplitSuccess"; public function LevelProxy():void{ super(NAME); init(); } private function init():void{ engine = CoreEngine.getInstance(); notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); } public function levelStart(publish:Boolean=false):void{ this.publish = publish; var levelTestMed:LevelTestMediator = (facade.retrieveMediator(LevelTestMediator.NAME) as LevelTestMediator); var editorProxy:EditorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); var level:CoreLevel = new CoreLevel(0); engine.levelStart(level, levelTestMed.getLevelContainer()); engine.addEventListener(CoreEngine.LEVEL_COMPLETE, levelCompleteHandler); var levelDef:String = editorProxy.getLevelDef(); LevelStringParser.getInstance().parse(levelDef); } public function levelAbort():void{ engine.removeEventListener(CoreEngine.LEVEL_COMPLETE, levelCompleteHandler); engine.levelAbort(); } private function levelCompleteHandler(e:CoreEvent):void{ notesProxy.push(EditorProxy.ELEVEL_COMPLETE); } } }//package editor.model
Section 138
//LevelStringParser (editor.model.LevelStringParser) package editor.model { import core.*; import core.shapes.*; import core.objects.*; import editor.model.objects.*; import flash.geom.*; import core.view.*; import core.tools.*; public class LevelStringParser { private var engine:CoreEngine; private static var instance:LevelStringParser; public function LevelStringParser():void{ super(); init(); } private function createRect(rectDef:RectDef):void{ var obj:BodyObject; var rectShape:RectShape = new RectShape(rectDef.width, rectDef.height); if (rectDef.type == BaseObjectDef.TYPE_BRICK){ obj = new BodyObject(rectDef.x, rectDef.y, true); } else { if (rectDef.type == BaseObjectDef.TYPE_METAL){ obj = new BodyObject(rectDef.x, rectDef.y, false); } else { if (rectDef.type == BaseObjectDef.TYPE_WOOD){ obj = new StickyBodyObject(rectDef.x, rectDef.y); }; }; }; obj.addRectShape(rectShape, new Point(rectDef.x, rectDef.y)); engine.objects.push(obj); } private function parseObjects(objectsDef:String):void{ var i:int; var objDef:String; var obj:BaseObjectDef; var defs:Array = objectsDef.split("|"); engine.objects = []; i = 0; while (i < defs.length) { objDef = defs[i]; obj = parseObjectDef(objDef); if ((obj is PlayerDef)){ createBox((obj as PlayerDef)); } else { if ((obj is CircleDef)){ createCircle((obj as CircleDef)); } else { if ((obj is RectDef)){ createRect((obj as RectDef)); }; }; }; i++; }; i = 0; while (i < defs.length) { objDef = defs[i]; obj = parseObjectDef(objDef); if ((obj is DistJointDef)){ createDistJoint((obj as DistJointDef)); } else { if ((obj is MotorDef)){ createMotor((obj as MotorDef)); } else { if ((obj is RevJointDef)){ createHinge((obj as RevJointDef)); }; }; }; i++; }; } private function parseShapes(shapesDef:String):void{ var shape:BaseShape; engine.addShapeTool = new AddShapeTool(); var defs:Array = shapesDef.split("|"); var shapes:Array = []; var i:int; while (i < defs.length) { shape = parseShapeDef(defs[i]); if (shape){ shapes.push(shape); }; i++; }; engine.addShapeTool.initShapes(shapes); engine.shapesPreview = new ShapesPreview(); engine.addShapeTool.start(); } private function createDistJoint(distJointDef:DistJointDef):void{ var distJoint:DistanceJoint = new DistanceJoint(distJointDef.x1, distJointDef.y1, distJointDef.x2, distJointDef.y2); engine.objects.push(distJoint); trace("GG"); } private function createCircle(circleDef:CircleDef):void{ var obj:BodyObject; var circleShape:CircleShape = new CircleShape(circleDef.r); if (circleDef.type == BaseObjectDef.TYPE_BRICK){ obj = new BodyObject(circleDef.x, circleDef.y, true); } else { if (circleDef.type == BaseObjectDef.TYPE_METAL){ obj = new BodyObject(circleDef.x, circleDef.y, false); } else { if (circleDef.type == BaseObjectDef.TYPE_WOOD){ obj = new StickyBodyObject(circleDef.x, circleDef.y); }; }; }; obj.addCircleShape(circleShape, new Point(circleDef.x, circleDef.y)); engine.objects.push(obj); } private function createBox(def:PlayerDef):void{ var box:Box = new Box(def.x, def.y); engine.objects.push(box); } private function init():void{ engine = CoreEngine.getInstance(); } private function createHinge(hingeDef:RevJointDef):void{ var hinge:Hinge = new Hinge(hingeDef.x, hingeDef.y); engine.objects.push(hinge); } private function parseShapeDef(shapeDef:String):BaseShape{ var props:Array = shapeDef.split("_"); var name:String = props[0]; switch (name){ case CircleShape.NAME: return (CircleShape.parseStringDef(shapeDef)); case RectShape.NAME: return (RectShape.parseStringDef(shapeDef)); }; return (null); } private function createMotor(motorDef:MotorDef):void{ var motor:Motor = new Motor(motorDef.x, motorDef.y, motorDef.torque); engine.objects.push(motor); } public function parse(levelDef:String):void{ trace(levelDef); var defs:Array = levelDef.split(" "); var objectsDef:String = defs[0]; var shapesDef:String = defs[1]; parseObjects(objectsDef); parseShapes(shapesDef); } public static function parseObjectDef(objDef:String):BaseObjectDef{ var props:Array = objDef.split("_"); var name:String = props[0]; switch (name){ case CircleDef.NAME: return (CircleDef.parseStringDef(objDef)); case PlayerDef.NAME: return (PlayerDef.parseStringDef(objDef)); case RectDef.NAME: return (RectDef.parseStringDef(objDef)); case DistJointDef.NAME: return (DistJointDef.parseStringDef(objDef)); case RevJointDef.NAME: return (RevJointDef.parseStringDef(objDef)); case MotorDef.NAME: return (MotorDef.parseStringDef(objDef)); }; return (null); } public static function getInstance():LevelStringParser{ if (instance == null){ instance = new (LevelStringParser); }; return (instance); } } }//package editor.model
Section 139
//Tool (editor.model.Tool) package editor.model { public class Tool { public var type:String; public var id:uint; public static const TYPE_PLAYER:String = "TypePlayer"; public static const TYPE_SELECTION:String = "TypeSelection"; public static const TYPE_REV_JOINT:String = "TypeRevJoint"; public static const TYPE_RECT:String = "TypeRect"; public static const TYPE_CIRCLE:String = "TypeCircle"; public static const TYPE_DIST_JOINT:String = "TypeDistJoint"; public static const TYPE_MOTOR:String = "TypeMotor"; public function Tool(id:uint, type:String):void{ super(); this.id = id; this.type = type; } } }//package editor.model
Section 140
//CircleView (editor.view.components.obj.CircleView) package editor.view.components.obj { import editor.model.*; import flash.display.*; import editor.model.objects.*; import editor.view.components.support.*; public class CircleView extends ObjView { private var circleObj:CircleDef; private var scale:CircleScaleSup; public function CircleView(obj:CircleDef):void{ circleObj = obj; super(obj); } override protected function createSupportStuff():void{ scale = new CircleScaleSup(circleObj); } override protected function updateSkin():void{ var MaterialClass:Class; if (circleObj.type == BaseObjectDef.TYPE_BRICK){ MaterialClass = EditorAssets.getInstance().getAssetClass("StaticBMDAsset"); } else { if (circleObj.type == BaseObjectDef.TYPE_METAL){ MaterialClass = EditorAssets.getInstance().getAssetClass("DynamicBMDAsset"); } else { if (circleObj.type == BaseObjectDef.TYPE_WOOD){ MaterialClass = EditorAssets.getInstance().getAssetClass("StickyBMDAsset"); }; }; }; var skinData:BitmapData = (new MaterialClass(0, 0) as BitmapData); skin.graphics.clear(); skin.graphics.beginBitmapFill(skinData, null, true, true); skin.graphics.lineStyle(0, 0, 1); skin.graphics.drawCircle(0, 0, circleObj.r); skin.graphics.endFill(); } override public function update():void{ super.update(); scale.update(); } override public function select():void{ super.select(); if (editorProxy.getSelectedObjects().length > 1){ return; }; scale.select(); } override public function deselect():void{ super.deselect(); scale.deselect(); } override protected function destroySupportStuff():void{ scale.destroy(); } } }//package editor.view.components.obj
Section 141
//DistJointView (editor.view.components.obj.DistJointView) package editor.view.components.obj { import editor.model.objects.*; import flash.geom.*; import editor.view.components.support.*; public class DistJointView extends ObjView { public var jointObj:DistJointDef; private var anchor1:DistJointTargetSup; private var anchor2:DistJointTargetSup; public function DistJointView(obj:DistJointDef):void{ this.jointObj = obj; super(obj); } override protected function createSupportStuff():void{ anchor1 = new DistJointTargetSup(jointObj, DistJointTargetSup.POS_FIRST); anchor2 = new DistJointTargetSup(jointObj, DistJointTargetSup.POS_SECOND); anchor1.visible = false; anchor2.visible = false; } override public function select():void{ super.select(); if (editorProxy.getSelectedObjects().length > 1){ return; }; anchor1.select(); anchor2.select(); } override protected function updateFrame():void{ frame.x = obj.x; frame.y = obj.y; var box:Rectangle = obj.getBoundingBox(); frame.graphics.clear(); frame.graphics.lineStyle(0, 6710937); frame.graphics.drawRect(box.x, box.y, box.width, box.height); } override protected function updateSkin():void{ skin.graphics.clear(); skin.graphics.lineStyle(2, 0x666600); skin.graphics.moveTo(jointObj.x1, jointObj.y1); skin.graphics.lineTo(jointObj.x2, jointObj.y2); super.updateSkin(); } override public function update():void{ anchor1.update(); anchor2.update(); updateSkin(); updateFrame(); } override public function deselect():void{ super.deselect(); anchor1.deselect(); anchor2.deselect(); } override protected function destroySupportStuff():void{ anchor1.destroy(); anchor2.destroy(); } } }//package editor.view.components.obj
Section 142
//MotorView (editor.view.components.obj.MotorView) package editor.view.components.obj { import editor.model.*; import flash.display.*; import editor.model.objects.*; import editor.view.components.support.*; public class MotorView extends ObjView { private var motorObj:MotorDef; private var torque:MotorTorqueSup; private var skinCw:Sprite; private var skinCcw:Sprite; public function MotorView(obj:MotorDef):void{ motorObj = obj; super(obj); } override protected function createSupportStuff():void{ torque = new MotorTorqueSup(motorObj, skinCw, skinCcw); } override public function update():void{ super.update(); torque.update(); } override protected function createSkin():void{ var SkinClass:Class = EditorAssets.getInstance().getAssetClass("MotorAsset"); skin = new (SkinClass); addChild(skin); skinCw = (skin.getChildByName("cw") as Sprite); skinCcw = (skin.getChildByName("ccw") as Sprite); } override public function select():void{ super.select(); if (editorProxy.getSelectedObjects().length > 1){ return; }; torque.select(); } override public function deselect():void{ super.deselect(); torque.deselect(); } override protected function destroySupportStuff():void{ torque.destroy(); } } }//package editor.view.components.obj
Section 143
//ObjView (editor.view.components.obj.ObjView) package editor.view.components.obj { import flash.events.*; import editor.model.*; import flash.display.*; import game.model.*; import editor.model.objects.*; import flash.geom.*; import editor.view.components.*; import editor.view.*; public class ObjView extends Sprite { protected var editorProxy:EditorProxy; protected var skin:Sprite; protected var support:Sprite; protected var canvas:Sprite; protected var frame:Sprite; protected var notesProxy:NotesProxy; public var obj:BaseObjectDef; public function ObjView(obj:BaseObjectDef):void{ super(); this.obj = obj; init(); } protected function createSupportStuff():void{ } public function update():void{ x = obj.x; y = obj.y; updateSkin(); updateFrame(); } protected function mouseUpHandler(e:MouseEvent):void{ obj.x = parent.mouseX; obj.y = parent.mouseY; stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); notesProxy.push(EditorProxy.OBJECT_UPDATE, obj); } protected function init():void{ var facade:ApplicationFacade = ApplicationFacade.getInstance(); notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); var editorMed:EditorMediator = (facade.retrieveMediator(EditorMediator.NAME) as EditorMediator); canvas = (editorMed.getViewComponent() as EditorView).canvas; support = (editorMed.getViewComponent() as EditorView).support; editorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); createSkin(); frame = new Sprite(); addChild(frame); createSupportStuff(); frame.visible = false; update(); } public function destroy():void{ parent.removeChild(this); destroySupportStuff(); } protected function mouseMoveHandler(e:MouseEvent):void{ } protected function createSkin():void{ skin = new Sprite(); addChild(skin); } protected function mouseDownHandler(e:MouseEvent):void{ notesProxy.push(EditorProxy.OBJECTS_SELECT, [obj]); stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } protected function updateFrame():void{ var box:Rectangle = obj.getBoundingBox(); var lp:Point = frame.globalToLocal(new Point(box.x, box.y)); frame.graphics.clear(); frame.graphics.lineStyle(0, 6710937); frame.graphics.drawRect(box.x, box.y, box.width, box.height); frame.graphics.lineStyle(0, 0); frame.graphics.moveTo(-3, 0); frame.graphics.lineTo(3, 0); frame.graphics.moveTo(0, -3); frame.graphics.lineTo(0, 3); } protected function updateSkin():void{ } public function select():void{ frame.visible = true; } public function deselect():void{ frame.visible = false; } protected function destroySupportStuff():void{ } } }//package editor.view.components.obj
Section 144
//RectView (editor.view.components.obj.RectView) package editor.view.components.obj { import editor.model.*; import flash.display.*; import editor.model.objects.*; import editor.view.components.support.*; public class RectView extends ObjView { private var rectObj:RectDef; private var scale:RectScaleSup; public function RectView(obj:RectDef):void{ rectObj = obj; super(obj); } override protected function init():void{ super.init(); } override protected function createSupportStuff():void{ scale = new RectScaleSup(rectObj); } override public function deselect():void{ super.deselect(); scale.deselect(); } override public function update():void{ super.update(); scale.update(); } override public function select():void{ super.select(); if (editorProxy.getSelectedObjects().length > 1){ return; }; scale.select(); } override protected function updateSkin():void{ var MaterialClass:Class; if (rectObj.type == BaseObjectDef.TYPE_BRICK){ MaterialClass = EditorAssets.getInstance().getAssetClass("StaticBMDAsset"); } else { if (rectObj.type == BaseObjectDef.TYPE_METAL){ MaterialClass = EditorAssets.getInstance().getAssetClass("DynamicBMDAsset"); } else { MaterialClass = EditorAssets.getInstance().getAssetClass("StickyBMDAsset"); }; }; var skinData:BitmapData = (new MaterialClass(0, 0) as BitmapData); skin.graphics.clear(); skin.graphics.beginBitmapFill(skinData, null, true, true); skin.graphics.lineStyle(0, 0, 1); skin.graphics.drawRect((-(rectObj.width) / 2), (-(rectObj.height) / 2), rectObj.width, rectObj.height); skin.graphics.endFill(); } override protected function destroySupportStuff():void{ scale.destroy(); } } }//package editor.view.components.obj
Section 145
//SimpleView (editor.view.components.obj.SimpleView) package editor.view.components.obj { import editor.model.*; import flash.display.*; import editor.model.objects.*; public class SimpleView extends ObjView { public function SimpleView(obj:BaseObjectDef):void{ super(obj); } override protected function createSkin():void{ var SkinClass:Class; super.createSkin(); var assets:EditorAssets = EditorAssets.getInstance(); if ((obj is PlayerDef)){ SkinClass = assets.getAssetClass("PlayerAsset"); } else { if ((obj is RevJointDef)){ SkinClass = assets.getAssetClass("HingeAsset"); } else { return; }; }; var skinInner:Sprite = new (SkinClass); skin.addChild(skinInner); } } }//package editor.view.components.obj
Section 146
//CirclePropsView (editor.view.components.props.CirclePropsView) package editor.view.components.props { import flash.display.*; import editor.model.objects.*; public class CirclePropsView extends ObjPropsView { private var circleObj:CircleDef; private var woodMat:MaterialProp; private var metallMat:MaterialProp; private var brickMat:MaterialProp; public function CirclePropsView(obj:CircleDef):void{ circleObj = obj; super(obj); } override public function destroy():void{ super.destroy(); woodMat.destroy(); metallMat.destroy(); brickMat.destroy(); } override public function update():void{ woodMat.deselect(); metallMat.deselect(); brickMat.deselect(); if (circleObj.type == BaseObjectDef.TYPE_WOOD){ woodMat.select(); } else { if (circleObj.type == BaseObjectDef.TYPE_METAL){ metallMat.select(); } else { if (circleObj.type == BaseObjectDef.TYPE_BRICK){ brickMat.select(); }; }; }; } override protected function createSkin():void{ super.createSkin(); var woodSprite:Sprite = (window.getChildByName("woodMat") as Sprite); var metallSprite:Sprite = (window.getChildByName("metallMat") as Sprite); var brickSprite:Sprite = (window.getChildByName("brickMat") as Sprite); woodMat = new MaterialProp(woodSprite, circleObj, BaseObjectDef.TYPE_WOOD); metallMat = new MaterialProp(metallSprite, circleObj, BaseObjectDef.TYPE_METAL); brickMat = new MaterialProp(brickSprite, circleObj, BaseObjectDef.TYPE_BRICK); } override protected function getWindowClassName():String{ return ("CirclePropsWindow"); } } }//package editor.view.components.props
Section 147
//MaterialProp (editor.view.components.props.MaterialProp) package editor.view.components.props { import flash.events.*; import editor.model.*; import flash.display.*; import game.model.*; import editor.model.objects.*; public class MaterialProp extends EventDispatcher { private var type:String; private var notesProxy:NotesProxy; private var window:Sprite; private var obj:BaseObjectDef; private var frame:Sprite; public function MaterialProp(window:Sprite, obj:BaseObjectDef, type:String):void{ super(); this.window = window; this.obj = obj; this.type = type; init(); } public function select():void{ frame.visible = true; } public function destroy():void{ window.removeEventListener(MouseEvent.CLICK, windowClickHandler); } private function windowClickHandler(e:MouseEvent):void{ if ((obj is CircleDef)){ (obj as CircleDef).type = type; } else { if ((obj is RectDef)){ (obj as RectDef).type = type; }; }; notesProxy.push(EditorProxy.OBJECT_UPDATE, obj); } public function deselect():void{ frame.visible = false; } private function init():void{ var facade:ApplicationFacade = ApplicationFacade.getInstance(); notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); frame = (window.getChildByName("frame") as Sprite); frame.visible = false; window.addEventListener(MouseEvent.CLICK, windowClickHandler); } } }//package editor.view.components.props
Section 148
//ObjPropsView (editor.view.components.props.ObjPropsView) package editor.view.components.props { import flash.events.*; import editor.model.*; import flash.display.*; import game.model.*; import editor.model.objects.*; public class ObjPropsView extends Sprite { protected var facade:ApplicationFacade; protected var delete_bt:SimpleButton; protected var notesProxy:NotesProxy; protected var window:Sprite; public var obj:BaseObjectDef; public function ObjPropsView(obj:BaseObjectDef):void{ super(); this.obj = obj; init(); } public function update():void{ } public function destroy():void{ delete_bt.removeEventListener(MouseEvent.CLICK, deleteClickHandler); window.parent.removeChild(window); } protected function createSkin():void{ var WindowClass:Class = EditorAssets.getInstance().getAssetClass(getWindowClassName()); window = new (WindowClass); addChild(window); delete_bt = (window.getChildByName("delete_bt") as SimpleButton); delete_bt.addEventListener(MouseEvent.CLICK, deleteClickHandler); } protected function deleteClickHandler(e:MouseEvent):void{ notesProxy.push(EditorProxy.OBJECT_REMOVE, obj); } protected function getWindowClassName():String{ return ("ObjPropsWindow"); } protected function init():void{ facade = ApplicationFacade.getInstance(); notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); createSkin(); update(); } } }//package editor.view.components.props
Section 149
//RectPropsView (editor.view.components.props.RectPropsView) package editor.view.components.props { import flash.display.*; import editor.model.objects.*; public class RectPropsView extends ObjPropsView { private var rectObj:RectDef; private var woodMat:MaterialProp; private var metallMat:MaterialProp; private var brickMat:MaterialProp; public function RectPropsView(obj:RectDef):void{ rectObj = obj; super(obj); } override public function destroy():void{ super.destroy(); woodMat.destroy(); metallMat.destroy(); brickMat.destroy(); } override public function update():void{ woodMat.deselect(); metallMat.deselect(); brickMat.deselect(); if (rectObj.type == BaseObjectDef.TYPE_WOOD){ woodMat.select(); } else { if (rectObj.type == BaseObjectDef.TYPE_METAL){ metallMat.select(); } else { if (rectObj.type == BaseObjectDef.TYPE_BRICK){ brickMat.select(); }; }; }; } override protected function createSkin():void{ super.createSkin(); var woodSprite:Sprite = (window.getChildByName("woodMat") as Sprite); var metallSprite:Sprite = (window.getChildByName("metallMat") as Sprite); var brickSprite:Sprite = (window.getChildByName("brickMat") as Sprite); woodMat = new MaterialProp(woodSprite, rectObj, BaseObjectDef.TYPE_WOOD); metallMat = new MaterialProp(metallSprite, rectObj, BaseObjectDef.TYPE_METAL); brickMat = new MaterialProp(brickSprite, rectObj, BaseObjectDef.TYPE_BRICK); } override protected function getWindowClassName():String{ return ("RectPropsWindow"); } } }//package editor.view.components.props
Section 150
//SeveralObjsPropsView (editor.view.components.props.SeveralObjsPropsView) package editor.view.components.props { import flash.events.*; import editor.model.*; import editor.model.objects.*; public class SeveralObjsPropsView extends ObjPropsView { public function SeveralObjsPropsView(obj:BaseObjectDef):void{ super(obj); } override protected function deleteClickHandler(e:MouseEvent):void{ var editorProxy:EditorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); editorProxy.deleteSelectedObjects(); } override protected function getWindowClassName():String{ return ("SeveralObjsPropsWindow"); } } }//package editor.view.components.props
Section 151
//ShapeHolderItem (editor.view.components.shapes.ShapeHolderItem) package editor.view.components.shapes { import editor.model.*; import core.*; import flash.display.*; import core.shapes.*; import editor.model.objects.*; public class ShapeHolderItem extends Sprite { private var container:Sprite; private var skinShape:Sprite; private var window:Sprite; public var id:int; public function ShapeHolderItem(id:int):void{ super(); this.id = id; init(); } public function isObjectInside(obj:BaseObjectDef):Boolean{ if (window.hitTestPoint(obj.x, obj.y, true)){ return (true); }; return (false); } public function addShape(shape:BaseShape):void{ createShape(shape); } private function createShape(shape:BaseShape):void{ var w:Number; var h:Number; var longest:Number; var ratio:Number; var maxSize:Number = 50; if ((shape is CircleShape)){ skinShape = new Sprite(); skinShape.graphics.lineStyle(0, 0); skinShape.graphics.beginBitmapFill(CoreCanvas.stickyBMD); skinShape.graphics.drawCircle(0, 0, (shape as CircleShape).radius); skinShape.graphics.endFill(); skinShape.width = (skinShape.height = ((shape as CircleShape).radius * 2)); if (skinShape.width > maxSize){ skinShape.width = (skinShape.height = maxSize); }; } else { if ((shape is RectShape)){ w = (shape as RectShape).width; h = (shape as RectShape).height; skinShape = new Sprite(); skinShape.graphics.lineStyle(0, 0); skinShape.graphics.beginBitmapFill(CoreCanvas.stickyBMD); skinShape.graphics.drawRect((-(w) / 2), (-(h) / 2), w, h); if ((((skinShape.width > maxSize)) || ((skinShape.height > maxSize)))){ longest = ((skinShape.width >= skinShape.height)) ? skinShape.width : skinShape.height; ratio = (maxSize / longest); skinShape.width = (skinShape.width * ratio); skinShape.height = (skinShape.height * ratio); }; }; }; container.addChild(skinShape); } private function init():void{ var WindowClass:Class = EditorAssets.getInstance().getAssetClass("ShapeHolderItemWindow"); window = new (WindowClass); addChild(window); container = (window.getChildByName("container") as Sprite); } } }//package editor.view.components.shapes
Section 152
//CircleScaleSup (editor.view.components.support.CircleScaleSup) package editor.view.components.support { import flash.events.*; import editor.model.*; import editor.model.objects.*; import flash.geom.*; public class CircleScaleSup extends ObjSup { private var radius:Number; private var circleObj:CircleDef; public function CircleScaleSup(obj:CircleDef):void{ circleObj = obj; super(obj); } override public function update():void{ x = (circleObj.x + circleObj.r); y = circleObj.y; } private function mouseUpHandler(e:MouseEvent):void{ circleObj.r = radius; notesProxy.push(EditorProxy.OBJECT_UPDATE, circleObj); support.graphics.clear(); stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } override protected function createSkin():void{ var SkinClass:Class = EditorAssets.getInstance().getAssetClass("ScaleAsset"); skin = new (SkinClass); addChild(skin); support.addChild(this); } private function mouseDownHandler(e:MouseEvent):void{ stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } private function mouseMoveHandler(e:MouseEvent):void{ support.graphics.clear(); support.graphics.lineStyle(0, 1); radius = gridProxy.getSnapPoint(new Point((support.mouseX - circleObj.x), 0)).x; if (radius < 1){ radius = 1; }; support.graphics.drawCircle(circleObj.x, circleObj.y, radius); } override public function destroy():void{ super.destroy(); removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); } override protected function initListeners():void{ addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); } } }//package editor.view.components.support
Section 153
//DistJointTargetSup (editor.view.components.support.DistJointTargetSup) package editor.view.components.support { import flash.events.*; import editor.model.*; import editor.model.objects.*; import flash.geom.*; public class DistJointTargetSup extends ObjSup { private var pos:String; private var jointObj:DistJointDef; public static const POS_FIRST:String = "PosFirst"; public static const POS_SECOND:String = "PosSecond"; public function DistJointTargetSup(obj:DistJointDef, pos:String):void{ jointObj = obj; this.pos = pos; super(obj); } override public function update():void{ if (pos == POS_FIRST){ x = jointObj.x1; y = jointObj.y1; } else { x = jointObj.x2; y = jointObj.y2; }; } private function mouseUpHandler(e:MouseEvent):void{ var mp:Point = gridProxy.getSnapPoint(new Point(support.mouseX, support.mouseY)); if (pos == POS_FIRST){ jointObj.x1 = mp.x; jointObj.y1 = mp.y; } else { jointObj.x2 = mp.x; jointObj.y2 = mp.y; }; jointObj.x = (jointObj.x1 + ((jointObj.x2 - jointObj.x1) / 2)); jointObj.y = (jointObj.y1 + ((jointObj.y2 - jointObj.y1) / 2)); notesProxy.push(EditorProxy.OBJECT_UPDATE, jointObj); stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } private function mouseDownHandler(e:MouseEvent):void{ stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } override protected function createSkin():void{ var SkinClass:Class = EditorAssets.getInstance().getAssetClass("DistanceJointVertex"); skin = new (SkinClass); addChild(skin); support.addChild(this); buttonMode = true; } private function mouseMoveHandler(e:MouseEvent):void{ var mp:Point = gridProxy.getSnapPoint(new Point(support.mouseX, support.mouseY)); x = mp.x; y = mp.y; } override public function destroy():void{ super.destroy(); removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); } override protected function initListeners():void{ addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); } } }//package editor.view.components.support
Section 154
//MotorTorqueSup (editor.view.components.support.MotorTorqueSup) package editor.view.components.support { import flash.events.*; import editor.model.*; import flash.display.*; import editor.model.objects.*; public class MotorTorqueSup extends ObjSup { private var motorObj:MotorDef; private var skinCw:Sprite; private var skinBar:Sprite; private var skinCcw:Sprite; public function MotorTorqueSup(obj:MotorDef, skinCw:Sprite, skinCcw:Sprite):void{ motorObj = obj; this.skinCw = skinCw; this.skinCcw = skinCcw; super(obj); } override public function destroy():void{ super.destroy(); removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); } private function mouseDownHandler(e:MouseEvent):void{ stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } private function mouseUpHandler(e:MouseEvent):void{ stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); motorObj.torque = skinBar.scaleX; notesProxy.push(EditorProxy.OBJECT_UPDATE, motorObj); } override protected function initListeners():void{ addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); } override public function update():void{ x = motorObj.x; y = (motorObj.y - 20); skinBar.scaleX = motorObj.torque; if (motorObj.torque == 0){ skinCw.visible = true; skinCcw.visible = false; } else { if (motorObj.torque > 0){ skinCw.visible = true; skinCcw.visible = false; } else { skinCw.visible = false; skinCcw.visible = true; }; }; } override protected function createSkin():void{ var SkinClass:Class = EditorAssets.getInstance().getAssetClass("RevJointTorqueAsset"); skin = new (SkinClass); addChild(skin); support.addChild(this); skinBar = (skin.getChildByName("bar") as Sprite); buttonMode = true; } private function mouseMoveHandler(e:MouseEvent):void{ var mx:Number = skin.mouseX; if (mx > 50){ mx = 50; }; if (mx < -50){ mx = -50; }; mx = (Math.round((mx / 5)) * 5); skinBar.scaleX = (mx / 50); } } }//package editor.view.components.support
Section 155
//ObjSup (editor.view.components.support.ObjSup) package editor.view.components.support { import editor.model.*; import flash.display.*; import game.model.*; import editor.model.objects.*; import editor.view.components.*; import editor.view.*; public class ObjSup extends Sprite { protected var gridProxy:GridProxy; protected var notesProxy:NotesProxy; protected var support:Sprite; protected var skin:Sprite; public var obj:BaseObjectDef; public function ObjSup(Obj:BaseObjectDef):void{ super(); this.obj = obj; init(); } public function deselect():void{ visible = false; } public function update():void{ } public function destroy():void{ parent.removeChild(this); } protected function initListeners():void{ } protected function init():void{ var facade:ApplicationFacade = ApplicationFacade.getInstance(); var editorMed:EditorMediator = (facade.retrieveMediator(EditorMediator.NAME) as EditorMediator); support = (editorMed.getViewComponent() as EditorView).support; notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); gridProxy = (facade.retrieveProxy(GridProxy.NAME) as GridProxy); createSkin(); initListeners(); deselect(); } protected function createSkin():void{ } public function select():void{ visible = true; } } }//package editor.view.components.support
Section 156
//RectScaleSup (editor.view.components.support.RectScaleSup) package editor.view.components.support { import flash.events.*; import editor.model.*; import editor.model.objects.*; import flash.geom.*; public class RectScaleSup extends ObjSup { private var h:Number; private var rectObj:RectDef; private var w:Number; public function RectScaleSup(obj:RectDef):void{ rectObj = obj; super(obj); } override public function destroy():void{ super.destroy(); removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); } private function mouseDownHandler(e:MouseEvent):void{ stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } override public function update():void{ x = (rectObj.x + (rectObj.width / 2)); y = (rectObj.y + (rectObj.height / 2)); } private function mouseUpHandler(e:MouseEvent):void{ rectObj.width = w; rectObj.height = h; notesProxy.push(EditorProxy.OBJECT_UPDATE, rectObj); support.graphics.clear(); stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } override protected function initListeners():void{ addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); } private function mouseMoveHandler(e:MouseEvent):void{ var mp:Point = gridProxy.getSnapPoint(new Point(support.mouseX, support.mouseY)); var dx:Number = Math.abs(Math.round((mp.x - rectObj.x))); var dy:Number = Math.abs(Math.round((mp.y - rectObj.y))); support.graphics.clear(); support.graphics.lineStyle(0, 1); support.graphics.drawRect((rectObj.x - dx), (rectObj.y - dy), (dx * 2), (dy * 2)); w = (dx * 2); h = (dy * 2); } override protected function createSkin():void{ var SkinClass:Class = EditorAssets.getInstance().getAssetClass("ScaleAsset"); skin = new (SkinClass); addChild(skin); support.addChild(this); } } }//package editor.view.components.support
Section 157
//CircleTool (editor.view.components.tools.CircleTool) package editor.view.components.tools { import flash.events.*; import editor.model.*; import flash.display.*; import editor.model.objects.*; import flash.geom.*; public class CircleTool extends ToolView { private var circle:Sprite; private var isDrawing:Boolean; public function CircleTool(window:Sprite, tool:Tool):void{ super(window, tool); } override protected function mouseMoveHandler(e:MouseEvent):void{ circle.graphics.clear(); circle.graphics.lineStyle(0, 0); var mouse:Point = gridProxy.getSnapPoint(new Point(circle.mouseX, 0)); circle.graphics.drawCircle(0, 0, mouse.x); } override protected function init():void{ super.init(); isDrawing = false; } private function keyDownHandler(e:KeyboardEvent):void{ if (((isDrawing) && ((e.keyCode == 27)))){ canvas.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); canvas.stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); circle.parent.removeChild(circle); notesProxy.push(EditorProxy.TOOL_SELECT, editorProxy.getTools()[0]); }; } override protected function mouseUpHandler(e:MouseEvent):void{ var circleDef:CircleDef; super.mouseUpHandler(e); circle.parent.removeChild(circle); isDrawing = false; var r:Number = Math.round((circle.width / 2)); if (r > 0){ circleDef = new CircleDef(circle.x, circle.y, r, BaseObjectDef.TYPE_WOOD); notesProxy.push(EditorProxy.OBJECT_ADD, circleDef); }; } override protected function canvasMouseDownHandler(e:MouseEvent):void{ super.canvasMouseDownHandler(e); circle = new Sprite(); var start:Point = gridProxy.getSnapPoint(new Point(canvas.mouseX, canvas.mouseY)); circle.x = start.x; circle.y = start.y; bodies.addChild(circle); isDrawing = true; } override public function select():void{ super.select(); window.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); } override public function deselect():void{ super.deselect(); isDrawing = false; window.stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); } } }//package editor.view.components.tools
Section 158
//DistJointTool (editor.view.components.tools.DistJointTool) package editor.view.components.tools { import flash.events.*; import editor.model.*; import flash.display.*; import editor.model.objects.*; import flash.geom.*; public class DistJointTool extends ToolView { private var y1:Number; private var x1:Number; public function DistJointTool(window:Sprite, tool:Tool):void{ super(window, tool); } override protected function mouseMoveHandler(e:MouseEvent):void{ canvasTop.graphics.clear(); canvasTop.graphics.lineStyle(2, 0x666600); canvasTop.graphics.moveTo(x1, y1); var mouse:Point = gridProxy.getSnapPoint(new Point(canvas.mouseX, canvas.mouseY)); canvasTop.graphics.lineTo(mouse.x, mouse.y); } override protected function mouseUpHandler(e:MouseEvent):void{ var x2:Number; var y2:Number; var jx:Number; var jy:Number; var def:DistJointDef; super.mouseUpHandler(e); canvasTop.graphics.clear(); var pt:Point = gridProxy.getSnapPoint(new Point(canvas.mouseX, canvas.mouseY)); x2 = pt.x; y2 = pt.y; if (!(((x1 == x2)) && ((y1 == y2)))){ jx = (x1 + ((x2 - x1) / 2)); jy = (y1 + ((y2 - y1) / 2)); def = new DistJointDef(jx, jy, x1, y1, x2, y2); notesProxy.push(EditorProxy.OBJECT_ADD, def); }; } override protected function canvasMouseDownHandler(e:MouseEvent):void{ super.canvasMouseDownHandler(e); var start:Point = gridProxy.getSnapPoint(new Point(canvas.mouseX, canvas.mouseY)); x1 = start.x; y1 = start.y; } } }//package editor.view.components.tools
Section 159
//RectTool (editor.view.components.tools.RectTool) package editor.view.components.tools { import flash.events.*; import editor.model.*; import flash.display.*; import editor.model.objects.*; import flash.geom.*; public class RectTool extends ToolView { private var isDrawing:Boolean; private var rect:Sprite; public function RectTool(window:Sprite, tool:Tool):void{ super(window, tool); } override protected function init():void{ super.init(); isDrawing = false; } override protected function canvasMouseDownHandler(e:MouseEvent):void{ super.canvasMouseDownHandler(e); rect = new Sprite(); var start:Point = gridProxy.getSnapPoint(new Point(canvas.mouseX, canvas.mouseY)); rect.x = start.x; rect.y = start.y; bodies.addChild(rect); isDrawing = true; } override protected function mouseMoveHandler(e:MouseEvent):void{ rect.graphics.clear(); rect.graphics.lineStyle(0, 0); var mp:Point = gridProxy.getSnapPoint(new Point(rect.mouseX, rect.mouseY)); rect.graphics.drawRect(0, 0, mp.x, mp.y); } private function keyDownHandler(e:KeyboardEvent):void{ if (((isDrawing) && ((e.keyCode == 27)))){ rect.parent.removeChild(rect); canvas.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); canvas.stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); notesProxy.push(EditorProxy.TOOL_SELECT, editorProxy.getTools()[0]); }; } override protected function mouseUpHandler(e:MouseEvent):void{ var rectDef:RectDef; super.mouseUpHandler(e); rect.parent.removeChild(rect); var posX:Number = ((rect.x < canvas.mouseX)) ? rect.x : canvas.mouseX; var posY:Number = ((rect.y < canvas.mouseY)) ? rect.y : canvas.mouseY; var width:Number = Math.round(rect.width); var height:Number = Math.round(rect.height); posX = (posX + Math.round((width / 2))); posY = (posY + Math.round((height / 2))); isDrawing = false; if ((((width > 0)) && ((height > 0)))){ rectDef = new RectDef(posX, posY, width, height, BaseObjectDef.TYPE_WOOD); notesProxy.push(EditorProxy.OBJECT_ADD, rectDef); }; } override public function select():void{ super.select(); window.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); } override public function deselect():void{ super.deselect(); isDrawing = false; window.stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); } } }//package editor.view.components.tools
Section 160
//SelectionTool (editor.view.components.tools.SelectionTool) package editor.view.components.tools { import flash.events.*; import editor.model.*; import flash.display.*; import editor.model.objects.*; import flash.geom.*; import flash.ui.*; public class SelectionTool extends ToolView { private var startPoint:Point; public function SelectionTool(window:Sprite, tool:Tool):void{ super(window, tool); } private function translateMouseMoveHandler(e:MouseEvent):void{ var obj:BaseObjectDef; var box:Rectangle; var objs:Array = editorProxy.getSelectedObjects(); canvasTop.graphics.clear(); canvasTop.graphics.lineStyle(0, 0, 0.5); var currentPoint:Point = gridProxy.getSnapPoint(new Point(canvas.mouseX, canvas.mouseY)); var dx:Number = (currentPoint.x - startPoint.x); var dy:Number = (currentPoint.y - startPoint.y); var i:uint; while (i < objs.length) { obj = objs[i]; box = obj.getBoundingBox(); canvasTop.graphics.drawRect(((obj.x + box.x) + dx), ((obj.y + box.y) + dy), box.width, box.height); i++; }; } private function handMouseMoveHandler(e:MouseEvent):void{ var dx:Number = Math.round((canvas.mouseX - startPoint.x)); var dy:Number = Math.round((canvas.mouseY - startPoint.y)); editorProxy.canvasTranslate(dx, dy); } private function selectMouseUpHandler(e:MouseEvent):void{ canvas.stage.removeEventListener(MouseEvent.MOUSE_MOVE, selectMouseMoveHandler); canvas.stage.removeEventListener(MouseEvent.MOUSE_UP, selectMouseUpHandler); canvasTop.graphics.clear(); var endPoint:Point = new Point(canvas.mouseX, canvas.mouseY); var rectX:Number = ((endPoint.x > startPoint.x)) ? startPoint.x : endPoint.x; var rectY:Number = ((endPoint.y > startPoint.y)) ? startPoint.y : endPoint.y; var rectWidth:Number = Math.abs((endPoint.x - startPoint.x)); var rectHeight:Number = Math.abs((endPoint.y - startPoint.y)); var rect:Rectangle = new Rectangle(rectX, rectY, rectWidth, rectHeight); var objs2:Array = editorProxy.getObjsUnderRect(rect); notesProxy.push(EditorProxy.OBJECTS_SELECT, objs2); } private function removeObjects():void{ editorProxy.deleteSelectedObjects(); } private function keyDownHandler(e:KeyboardEvent):void{ var trans:Point = new Point(0, 0); if (e.keyCode == Keyboard.LEFT){ translateObjects(-1, 0); } else { if (e.keyCode == Keyboard.RIGHT){ translateObjects(1, 0); } else { if (e.keyCode == Keyboard.UP){ translateObjects(0, -1); } else { if (e.keyCode == Keyboard.DOWN){ translateObjects(0, 1); } else { if (e.keyCode == Keyboard.DELETE){ removeObjects(); }; }; }; }; }; } private function translateObjects(dx:Number, dy:Number):void{ var i:uint; var obj:BaseObjectDef; var objs:Array = editorProxy.getSelectedObjects(); if (objs.length != 0){ i = 0; while (i < objs.length) { obj = objs[i]; obj.translate(dx, dy); notesProxy.push(EditorProxy.OBJECT_UPDATE, obj); i++; }; }; } override protected function init():void{ super.init(); } private function selectMouseMoveHandler(e:MouseEvent):void{ var rectWidth:Number = (canvas.mouseX - startPoint.x); var rectHeight:Number = (canvas.mouseY - startPoint.y); canvasTop.graphics.clear(); canvasTop.graphics.lineStyle(0, 0); canvasTop.graphics.beginFill(6710937, 0.3); canvasTop.graphics.drawRect(startPoint.x, startPoint.y, rectWidth, rectHeight); canvasTop.graphics.endFill(); } private function translateMouseUpHandler(e:MouseEvent):void{ var obj:BaseObjectDef; var i:uint; var newObjs:Array; canvasTop.graphics.clear(); var endPoint:Point = gridProxy.getSnapPoint(new Point(canvas.mouseX, canvas.mouseY)); var objs:Array = editorProxy.getSelectedObjects(); if (e.ctrlKey){ newObjs = []; i = 0; while (i < objs.length) { obj = objs[i]; if ((obj is PlayerDef)){ } else { obj = LevelStringParser.parseObjectDef(obj.getStringDef()); obj.translate((endPoint.x - startPoint.x), (endPoint.y - startPoint.y)); newObjs.push(obj); notesProxy.push(EditorProxy.OBJECT_ADD, obj); }; i++; }; notesProxy.push(EditorProxy.OBJECTS_SELECT, newObjs); } else { i = 0; while (i < objs.length) { obj = objs[i]; obj.translate((endPoint.x - startPoint.x), (endPoint.y - startPoint.y)); notesProxy.push(EditorProxy.OBJECT_UPDATE, obj); i++; }; }; canvas.stage.removeEventListener(MouseEvent.MOUSE_UP, translateMouseUpHandler); canvas.stage.removeEventListener(MouseEvent.MOUSE_MOVE, translateMouseMoveHandler); } private function handMouseUpHandler(e:MouseEvent):void{ canvas.stage.removeEventListener(MouseEvent.MOUSE_MOVE, handMouseMoveHandler); canvas.stage.removeEventListener(MouseEvent.MOUSE_UP, handMouseUpHandler); } override protected function canvasMouseDownHandler(e:MouseEvent):void{ var selectedObjs:Array; startPoint = gridProxy.getSnapPoint(new Point(canvas.mouseX, canvas.mouseY)); var obj:BaseObjectDef = editorProxy.getObjUnderPoint(new Point(canvas.mouseX, canvas.mouseY)); if (obj){ selectedObjs = editorProxy.getSelectedObjects(); if (selectedObjs.indexOf(obj) == -1){ notesProxy.push(EditorProxy.OBJECTS_SELECT, [obj]); }; canvas.stage.addEventListener(MouseEvent.MOUSE_MOVE, translateMouseMoveHandler); canvas.stage.addEventListener(MouseEvent.MOUSE_UP, translateMouseUpHandler); } else { notesProxy.push(EditorProxy.OBJECTS_SELECT, []); canvas.stage.addEventListener(MouseEvent.MOUSE_MOVE, selectMouseMoveHandler); canvas.stage.addEventListener(MouseEvent.MOUSE_UP, selectMouseUpHandler); }; } override public function select():void{ super.select(); window.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); } override public function deselect():void{ super.deselect(); window.stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); } private function keyUpHandler(e:KeyboardEvent):void{ window.stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler); } } }//package editor.view.components.tools
Section 161
//SimpleTool (editor.view.components.tools.SimpleTool) package editor.view.components.tools { import flash.events.*; import editor.model.*; import flash.display.*; import editor.model.objects.*; import flash.geom.*; public class SimpleTool extends ToolView { public function SimpleTool(window:Sprite, tool:Tool):void{ super(window, tool); } override protected function mouseUpHandler(e:MouseEvent):void{ var def:BaseObjectDef; super.mouseUpHandler(e); var start:Point = gridProxy.getSnapPoint(new Point(canvas.mouseX, canvas.mouseY)); if (tool.type == Tool.TYPE_REV_JOINT){ def = new RevJointDef(start.x, start.y); } else { if (tool.type == Tool.TYPE_MOTOR){ def = new MotorDef(start.x, start.y, 0.5); } else { return; }; }; notesProxy.push(EditorProxy.OBJECT_ADD, def); } } }//package editor.view.components.tools
Section 162
//ToolView (editor.view.components.tools.ToolView) package editor.view.components.tools { import flash.events.*; import editor.model.*; import flash.display.*; import game.model.*; import editor.view.components.*; import editor.view.*; public class ToolView extends EventDispatcher { protected var bodies:Sprite; protected var editorProxy:EditorProxy; protected var windowBack:MovieClip; protected var gridProxy:GridProxy; protected var support:Sprite; public var tool:Tool; protected var canvasTop:Sprite; protected var canvasBack:Sprite; protected var facade:ApplicationFacade; protected var canvas:Sprite; protected var notesProxy:NotesProxy; protected var window:Sprite; public static const SELECT:String = "Select"; public function ToolView(window:Sprite, tool:Tool):void{ super(); this.window = window; this.tool = tool; init(); } protected function mouseUpHandler(e:MouseEvent):void{ canvas.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); canvas.stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } protected function mouseMoveHandler(e:MouseEvent):void{ } protected function init():void{ windowBack = (window.getChildByName("back") as MovieClip); windowBack.stop(); window.addEventListener(MouseEvent.CLICK, windowClickHandler); facade = ApplicationFacade.getInstance(); var editorMed:EditorMediator = (facade.retrieveMediator(EditorMediator.NAME) as EditorMediator); var editorView:EditorView = (editorMed.getViewComponent() as EditorView); var objectsMed:ObjectsMediator = (facade.retrieveMediator(ObjectsMediator.NAME) as ObjectsMediator); var objectsView:ObjectsView = (objectsMed.getViewComponent() as ObjectsView); canvas = editorView.canvas; canvasBack = editorView.canvasBack; canvasTop = editorView.canvasTop; support = editorView.support; bodies = objectsView.bodies; notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); editorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); gridProxy = (facade.retrieveProxy(GridProxy.NAME) as GridProxy); } protected function canvasMouseDownHandler(e:MouseEvent):void{ canvas.stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); canvas.stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } protected function windowClickHandler(e:MouseEvent):void{ dispatchEvent(new Event(SELECT)); } public function select():void{ windowBack.gotoAndStop(2); canvas.addEventListener(MouseEvent.MOUSE_DOWN, canvasMouseDownHandler); } public function deselect():void{ windowBack.gotoAndStop(1); canvas.removeEventListener(MouseEvent.MOUSE_DOWN, canvasMouseDownHandler); } } }//package editor.view.components.tools
Section 163
//EditorView (editor.view.components.EditorView) package editor.view.components { import editor.model.*; import flash.display.*; public class EditorView extends Sprite { public var exitConfirm:Sprite; public var grid:Sprite; public var load_bt:SimpleButton; public var support:Sprite; public var exitNo_bt:SimpleButton; public var save_bt:SimpleButton; public var canvas:Sprite; public var tools:Sprite; public var canvasTop:Sprite; public var canvasBack:Sprite; public var exitYes_bt:SimpleButton; private var window:Sprite; public var shapes:Sprite; public var menu_bt:SimpleButton; public var play_bt:SimpleButton; public var props:Sprite; public function EditorView():void{ super(); init(); } private function init():void{ var WindowClass:Class = EditorAssets.getInstance().getAssetClass("EditorWindow"); window = new (WindowClass); addChild(window); canvas = (window.getChildByName("canvas") as Sprite); canvasBack = (canvas.getChildByName("back") as Sprite); canvasTop = (canvas.getChildByName("canvasTop") as Sprite); tools = (window.getChildByName("tools") as Sprite); props = (window.getChildByName("props") as Sprite); shapes = (window.getChildByName("shapes") as Sprite); support = (window.getChildByName("support") as Sprite); grid = (canvas.getChildByName("grid") as Sprite); play_bt = (window.getChildByName("play_bt") as SimpleButton); save_bt = (window.getChildByName("save_bt") as SimpleButton); load_bt = (window.getChildByName("load_bt") as SimpleButton); menu_bt = (window.getChildByName("menu_bt") as SimpleButton); exitConfirm = (window.getChildByName("exitConfirm") as Sprite); exitYes_bt = (exitConfirm.getChildByName("yes_bt") as SimpleButton); exitNo_bt = (exitConfirm.getChildByName("no_bt") as SimpleButton); } } }//package editor.view.components
Section 164
//ELevelCompleteView (editor.view.components.ELevelCompleteView) package editor.view.components { import editor.model.*; import flash.display.*; public class ELevelCompleteView extends Sprite { private var window:Sprite; public var restart_bt:SimpleButton; public var inner:Sprite; public var back:Sprite; public var editor_bt:SimpleButton; public function ELevelCompleteView():void{ super(); init(); } private function init():void{ var WindowClass:Class = EditorAssets.getInstance().getAssetClass("LevelCompleteWindow"); window = new (WindowClass); addChild(window); back = (window.getChildByName("back") as Sprite); inner = (window.getChildByName("inner") as Sprite); restart_bt = (inner.getChildByName("restart_bt") as SimpleButton); editor_bt = (inner.getChildByName("editor_bt") as SimpleButton); } } }//package editor.view.components
Section 165
//GridView (editor.view.components.GridView) package editor.view.components { import flash.display.*; public class GridView { public var window:Sprite; public var container:Sprite; public function GridView(window:Sprite):void{ super(); this.window = window; init(); } private function init():void{ container = new Sprite(); window.addChild(container); } } }//package editor.view.components
Section 166
//LevelLoadView (editor.view.components.LevelLoadView) package editor.view.components { import editor.model.*; import flash.display.*; import flash.text.*; public class LevelLoadView extends Sprite { private var window:Sprite; public var inner:Sprite; public var levelDef_tf:TextField; public var load_bt:SimpleButton; public var cancel_bt:SimpleButton; public function LevelLoadView():void{ super(); init(); } private function init():void{ var WindowClass:Class = EditorAssets.getInstance().getAssetClass("LevelLoadWindow"); window = new (WindowClass); addChild(window); inner = (window.getChildByName("inner") as Sprite); levelDef_tf = (inner.getChildByName("levelDef_tf") as TextField); load_bt = (inner.getChildByName("load_bt") as SimpleButton); cancel_bt = (inner.getChildByName("cancel_bt") as SimpleButton); } } }//package editor.view.components
Section 167
//LevelSaveView (editor.view.components.LevelSaveView) package editor.view.components { import editor.model.*; import flash.display.*; import flash.text.*; public class LevelSaveView extends Sprite { private var window:Sprite; public var ok_bt:SimpleButton; public var inner:Sprite; public var levelDef_tf:TextField; public function LevelSaveView():void{ super(); init(); } private function init():void{ var WindowClass:Class = EditorAssets.getInstance().getAssetClass("LevelSaveWindow"); window = new (WindowClass); addChild(window); inner = (window.getChildByName("inner") as Sprite); levelDef_tf = (inner.getChildByName("levelDef_tf") as TextField); ok_bt = (inner.getChildByName("ok_bt") as SimpleButton); } } }//package editor.view.components
Section 168
//LevelTestView (editor.view.components.LevelTestView) package editor.view.components { import editor.model.*; import flash.display.*; public class LevelTestView extends Sprite { private var window:Sprite; public var restart_bt:SimpleButton; public var back_bt:SimpleButton; public var levelContainer:Sprite; public function LevelTestView():void{ super(); init(); } private function init():void{ var WindowClass:Class = EditorAssets.getInstance().getAssetClass("LevelTestWindow"); window = new (WindowClass); addChild(window); levelContainer = (window.getChildByName("levelContainer") as Sprite); back_bt = (window.getChildByName("back_bt") as SimpleButton); restart_bt = (window.getChildByName("restart_bt") as SimpleButton); } } }//package editor.view.components
Section 169
//ObjectsView (editor.view.components.ObjectsView) package editor.view.components { import flash.display.*; public class ObjectsView { public var window:Sprite; public var player:Sprite; public var bodies:Sprite; public var joints:Sprite; public function ObjectsView(window:Sprite):void{ super(); this.window = window; init(); } private function init():void{ bodies = (window.getChildByName("bodies") as Sprite); player = (window.getChildByName("player") as Sprite); joints = (window.getChildByName("joints") as Sprite); } } }//package editor.view.components
Section 170
//PropsView (editor.view.components.PropsView) package editor.view.components { import flash.display.*; public class PropsView { public var window:Sprite; public var container:Sprite; public function PropsView(window:Sprite):void{ super(); this.window = window; init(); } private function init():void{ container = (window.getChildByName("container") as Sprite); } } }//package editor.view.components
Section 171
//ShapesView (editor.view.components.ShapesView) package editor.view.components { import flash.display.*; public class ShapesView { public var window:Sprite; public var itemsContainer:Sprite; public var show_bt:SimpleButton; public var inner:Sprite; public var hide_bt:SimpleButton; public function ShapesView(window:Sprite):void{ super(); this.window = window; init(); } private function init():void{ show_bt = (window.getChildByName("show_bt") as SimpleButton); inner = (window.getChildByName("inner") as Sprite); itemsContainer = (inner.getChildByName("itemsContainer") as Sprite); hide_bt = (inner.getChildByName("hide_bt") as SimpleButton); } } }//package editor.view.components
Section 172
//ToolsView (editor.view.components.ToolsView) package editor.view.components { import flash.display.*; public class ToolsView { public var rectTool:Sprite; public var selectionTool:Sprite; public var revJointTool:Sprite; public var motorTool:Sprite; public var circleTool:Sprite; public var window:Sprite; public var playerTool:Sprite; public var distJointTool:Sprite; public function ToolsView(window:Sprite):void{ super(); this.window = window; init(); } private function init():void{ selectionTool = (window.getChildByName("selection") as Sprite); circleTool = (window.getChildByName("circle") as Sprite); rectTool = (window.getChildByName("rect") as Sprite); distJointTool = (window.getChildByName("distJoint") as Sprite); playerTool = (window.getChildByName("player") as Sprite); revJointTool = (window.getChildByName("revJoint") as Sprite); motorTool = (window.getChildByName("motor") as Sprite); } } }//package editor.view.components
Section 173
//EditorMediator (editor.view.EditorMediator) package editor.view { import flash.events.*; import org.puremvc.as3.interfaces.*; import editor.model.*; import game.model.*; import editor.view.components.*; import org.puremvc.as3.patterns.mediator.*; import game.view.*; public class EditorMediator extends Mediator implements IMediator { private var editorProxy:EditorProxy; private var _view:EditorView; private var notesProxy:NotesProxy; public static const NAME:String = "EditorMediator"; public function EditorMediator(viewComponent:EditorView):void{ super(NAME, viewComponent); init(); } override public function listNotificationInterests():Array{ return ([]); } private function exitNoClickHandler(e:MouseEvent):void{ _view.exitConfirm.visible = false; } override public function onRegister():void{ var objectsView:ObjectsView = new ObjectsView(_view.canvas); var objectsMed:ObjectsMediator = new ObjectsMediator(objectsView); facade.registerMediator(objectsMed); var toolsView:ToolsView = new ToolsView(_view.tools); var toolsMed:ToolsMediator = new ToolsMediator(toolsView); facade.registerMediator(toolsMed); var propsView:PropsView = new PropsView(_view.props); var propsMed:PropsMediator = new PropsMediator(propsView); facade.registerMediator(propsMed); var shapesView:ShapesView = new ShapesView(_view.shapes); var shapesMed:ShapesMediator = new ShapesMediator(shapesView); facade.registerMediator(shapesMed); var gridView:GridView = new GridView(_view.grid); var gridMed:GridMediator = new GridMediator(gridView); facade.registerMediator(gridMed); notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); editorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); _view.exitConfirm.visible = false; _view.play_bt.addEventListener(MouseEvent.CLICK, playClickHandler); _view.save_bt.addEventListener(MouseEvent.CLICK, saveClickHandler); _view.load_bt.addEventListener(MouseEvent.CLICK, loadClickHandler); _view.menu_bt.addEventListener(MouseEvent.CLICK, menuClickHandler); _view.exitYes_bt.addEventListener(MouseEvent.CLICK, exitYesClickHandler); _view.exitNo_bt.addEventListener(MouseEvent.CLICK, exitNoClickHandler); } private function exitYesClickHandler(e:MouseEvent):void{ notesProxy.push(EditorProxy.EDITOR_CLOSE); } private function loadClickHandler(e:MouseEvent):void{ notesProxy.push(EditorProxy.OBJECTS_SELECT, []); var loadView:LevelLoadView = new LevelLoadView(); var appMed:AppMediator = (facade.retrieveMediator(AppMediator.NAME) as AppMediator); appMed.getViewContainer().addChild(loadView); var loadMed:LevelLoadMediator = new LevelLoadMediator(loadView); facade.registerMediator(loadMed); } private function init():void{ _view = (getViewComponent() as EditorView); } public function destroy():void{ var objectsMed:ObjectsMediator = (facade.retrieveMediator(ObjectsMediator.NAME) as ObjectsMediator); objectsMed.destroy(); var toolsMed:ToolsMediator = (facade.retrieveMediator(ToolsMediator.NAME) as ToolsMediator); toolsMed.destroy(); var shapesMed:ShapesMediator = (facade.retrieveMediator(ShapesMediator.NAME) as ShapesMediator); shapesMed.destroy(); _view.play_bt.removeEventListener(MouseEvent.CLICK, playClickHandler); _view.save_bt.removeEventListener(MouseEvent.CLICK, saveClickHandler); _view.menu_bt.removeEventListener(MouseEvent.CLICK, menuClickHandler); _view.exitYes_bt.removeEventListener(MouseEvent.CLICK, exitYesClickHandler); _view.exitNo_bt.removeEventListener(MouseEvent.CLICK, exitNoClickHandler); _view.parent.removeChild(_view); facade.removeMediator(NAME); } override public function handleNotification(note:INotification):void{ } private function playClickHandler(e:MouseEvent):void{ notesProxy.push(EditorProxy.OBJECTS_SELECT, []); notesProxy.push(EditorProxy.ELEVEL_START); } private function menuClickHandler(e:MouseEvent):void{ _view.exitConfirm.visible = true; } private function saveClickHandler(e:MouseEvent):void{ trace("save"); notesProxy.push(EditorProxy.OBJECTS_SELECT, []); var saveView:LevelSaveView = new LevelSaveView(); var appMed:AppMediator = (facade.retrieveMediator(AppMediator.NAME) as AppMediator); appMed.getViewContainer().addChild(saveView); var saveMed:LevelSaveMediator = new LevelSaveMediator(saveView); facade.registerMediator(saveMed); } } }//package editor.view
Section 174
//ELevelCompleteMediator (editor.view.ELevelCompleteMediator) package editor.view { import flash.events.*; import org.puremvc.as3.interfaces.*; import game.view.components.*; import editor.model.*; import game.model.*; import editor.view.components.*; import org.puremvc.as3.patterns.mediator.*; import caurina.transitions.*; public class ELevelCompleteMediator extends Mediator implements IMediator { private var _view:ELevelCompleteView; private var notesProxy:NotesProxy; public static const NAME:String = "ELevelCompleteMediator"; public function ELevelCompleteMediator(viewComponent:ELevelCompleteView):void{ super(NAME, viewComponent); init(); } override public function listNotificationInterests():Array{ return ([]); } override public function handleNotification(note:INotification):void{ } private function editorClickHandler(e:MouseEvent):void{ Fader.getInstance().fade(abortLevel); } private function init():void{ _view = (getViewComponent() as ELevelCompleteView); notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); _view.restart_bt.addEventListener(MouseEvent.CLICK, restartClickHandler); _view.editor_bt.addEventListener(MouseEvent.CLICK, editorClickHandler); _view.back.alpha = 0; Tweener.addTween(_view.back, {alpha:1, time:1, transition:"linear"}); var innerY:Number = _view.inner.y; _view.inner.y = -(_view.inner.height); Tweener.addTween(_view.inner, {y:innerY, time:1, delay:0.5, transition:"easeoutback"}); } private function restartClickHandler(e:MouseEvent):void{ Fader.getInstance().fade(restartLevel); } private function abortLevel():void{ notesProxy.push(EditorProxy.ELEVEL_ABORT); } private function restartLevel():void{ notesProxy.push(EditorProxy.ELEVEL_ABORT); notesProxy.push(EditorProxy.ELEVEL_START); } public function destroy():void{ _view.parent.removeChild(_view); facade.removeMediator(NAME); } } }//package editor.view
Section 175
//GridMediator (editor.view.GridMediator) package editor.view { import org.puremvc.as3.interfaces.*; import editor.model.*; import flash.display.*; import editor.view.components.*; import org.puremvc.as3.patterns.mediator.*; public class GridMediator extends Mediator implements IMediator { private var _view:GridView; private var gridProxy:GridProxy; public static const NAME:String = "GridMediator"; public function GridMediator(viewComponent:GridView):void{ super(NAME, viewComponent); init(); } override public function onRegister():void{ } override public function listNotificationInterests():Array{ return ([]); } private function drawGrid():void{ var i:uint; var cellsX:uint = Math.round((640 / gridProxy.cellWidth)); var cellsY:uint = Math.round((480 / gridProxy.cellHeight)); var gr:Graphics = _view.container.graphics; gr.clear(); gr.lineStyle(0, 0xEEEEEE, 0.2); i = 0; while (i < cellsX) { gr.moveTo((i * gridProxy.cellWidth), 0); gr.lineTo((i * gridProxy.cellWidth), 480); i++; }; i = 0; while (i < cellsY) { gr.moveTo(0, (i * gridProxy.cellHeight)); gr.lineTo(640, (i * gridProxy.cellHeight)); i++; }; } override public function handleNotification(note:INotification):void{ } private function init():void{ _view = (getViewComponent() as GridView); gridProxy = (facade.retrieveProxy(GridProxy.NAME) as GridProxy); drawGrid(); } public function destroy():void{ facade.removeMediator(NAME); } } }//package editor.view
Section 176
//LevelLoadMediator (editor.view.LevelLoadMediator) package editor.view { import flash.events.*; import org.puremvc.as3.interfaces.*; import editor.model.*; import editor.view.components.*; import org.puremvc.as3.patterns.mediator.*; public class LevelLoadMediator extends Mediator implements IMediator { private var _view:LevelLoadView; public static const NAME:String = "LevelLoadMediator"; public function LevelLoadMediator(viewComponent:LevelLoadView):void{ super(NAME, viewComponent); init(); } private function init():void{ _view = (getViewComponent() as LevelLoadView); _view.levelDef_tf.text = ""; _view.load_bt.addEventListener(MouseEvent.CLICK, loadClickHandler); _view.cancel_bt.addEventListener(MouseEvent.CLICK, cancelClickHandler); } override public function listNotificationInterests():Array{ return ([]); } private function destroy():void{ _view.parent.removeChild(_view); facade.removeMediator(NAME); } override public function handleNotification(note:INotification):void{ } private function cancelClickHandler(e:MouseEvent):void{ destroy(); } private function loadClickHandler(e:MouseEvent):void{ var editorProxy:EditorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); var levelDef:String = _view.levelDef_tf.text; editorProxy.loadLevel(levelDef); destroy(); } } }//package editor.view
Section 177
//LevelSaveMediator (editor.view.LevelSaveMediator) package editor.view { import flash.events.*; import org.puremvc.as3.interfaces.*; import editor.model.*; import editor.view.components.*; import org.puremvc.as3.patterns.mediator.*; public class LevelSaveMediator extends Mediator implements IMediator { private var _view:LevelSaveView; public static const NAME:String = "LevelSaveMediator"; public function LevelSaveMediator(viewComponent:LevelSaveView):void{ super(NAME, viewComponent); init(); } private function init():void{ _view = (getViewComponent() as LevelSaveView); var editorProxy:EditorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); _view.levelDef_tf.text = editorProxy.getLevelDef(); _view.ok_bt.addEventListener(MouseEvent.CLICK, okClickHandler); } override public function handleNotification(note:INotification):void{ } override public function listNotificationInterests():Array{ return ([]); } private function destroy():void{ _view.parent.removeChild(_view); facade.removeMediator(NAME); } private function okClickHandler(e:MouseEvent):void{ destroy(); } } }//package editor.view
Section 178
//LevelTestMediator (editor.view.LevelTestMediator) package editor.view { import flash.events.*; import org.puremvc.as3.interfaces.*; import editor.model.*; import flash.display.*; import game.model.*; import editor.view.components.*; import org.puremvc.as3.patterns.mediator.*; public class LevelTestMediator extends Mediator implements IMediator { private var _view:LevelTestView; private var levelProxy:LevelProxy; private var cutIcons:Array; public static const NAME:String = "LevelTestMediator"; public function LevelTestMediator(viewComponent:LevelTestView):void{ super(NAME, viewComponent); init(); } override public function listNotificationInterests():Array{ return ([EditorProxy.ELEVEL_COMPLETE]); } public function getLevelContainer():Sprite{ return (_view.levelContainer); } private function backClickHandler(e:MouseEvent):void{ var notesProxy:NotesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); notesProxy.push(EditorProxy.ELEVEL_ABORT); } override public function handleNotification(note:INotification):void{ switch (note.getName()){ case EditorProxy.ELEVEL_COMPLETE: levelComplete(); break; }; } private function restartClickHandler(e:MouseEvent):void{ var notesProxy:NotesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); notesProxy.push(EditorProxy.ELEVEL_ABORT); notesProxy.push(EditorProxy.ELEVEL_START); } private function init():void{ _view = (getViewComponent() as LevelTestView); levelProxy = (facade.retrieveProxy(LevelProxy.NAME) as LevelProxy); _view.back_bt.addEventListener(MouseEvent.CLICK, backClickHandler); _view.restart_bt.addEventListener(MouseEvent.CLICK, restartClickHandler); } public function destroy():void{ _view.parent.removeChild(_view); facade.removeMediator(NAME); } private function levelComplete():void{ } } }//package editor.view
Section 179
//ObjectsMediator (editor.view.ObjectsMediator) package editor.view { import org.puremvc.as3.interfaces.*; import editor.model.*; import editor.model.objects.*; import editor.view.components.*; import org.puremvc.as3.patterns.mediator.*; import editor.view.components.obj.*; public class ObjectsMediator extends Mediator implements IMediator { private var _view:ObjectsView; private var objViews:Array; public static const NAME:String = "ObjectsMediator"; public function ObjectsMediator(viewComponent:ObjectsView):void{ super(NAME, viewComponent); init(); } override public function listNotificationInterests():Array{ return ([EditorProxy.OBJECT_ADD, EditorProxy.OBJECTS_SELECT, EditorProxy.OBJECT_UPDATE, EditorProxy.OBJECT_REMOVE]); } private function objectAdd(obj:BaseObjectDef):void{ var objView:ObjView; if ((obj is PlayerDef)){ objView = new SimpleView(obj); } else { if ((obj is CircleDef)){ objView = new CircleView((obj as CircleDef)); } else { if ((obj is RectDef)){ objView = new RectView((obj as RectDef)); } else { if ((obj is DistJointDef)){ objView = new DistJointView((obj as DistJointDef)); } else { if ((obj is MotorDef)){ objView = new MotorView((obj as MotorDef)); } else { if ((obj is RevJointDef)){ objView = new SimpleView((obj as RevJointDef)); } else { return; }; }; }; }; }; }; if ((obj is PlayerDef)){ _view.player.addChild(objView); } else { if ((((obj is CircleDef)) || ((obj is RectDef)))){ _view.bodies.addChild(objView); } else { if ((((obj is DistJointDef)) || ((obj is RevJointDef)))){ _view.joints.addChild(objView); }; }; }; objViews.push(objView); } private function objectRemove(obj:BaseObjectDef):void{ var objView:ObjView; var i:uint; while (i < objViews.length) { objView = objViews[i]; if (objView.obj == obj){ objView.destroy(); }; i++; }; } override public function handleNotification(note:INotification):void{ switch (note.getName()){ case EditorProxy.OBJECT_ADD: objectAdd((note.getBody() as BaseObjectDef)); break; case EditorProxy.OBJECTS_SELECT: objectsSelect((note.getBody() as Array)); break; case EditorProxy.OBJECT_UPDATE: objectUpdate((note.getBody() as BaseObjectDef)); break; case EditorProxy.OBJECT_REMOVE: objectRemove((note.getBody() as BaseObjectDef)); break; }; } private function objectUpdate(obj:BaseObjectDef):void{ var objView:ObjView; var i:uint; while (i < objViews.length) { objView = objViews[i]; if (objView.obj == obj){ objView.update(); }; i++; }; } private function init():void{ _view = (getViewComponent() as ObjectsView); objViews = []; } public function destroy():void{ facade.removeMediator(NAME); } private function objectsSelect(objs:Array):void{ var objView:ObjView; var j:uint; var obj:BaseObjectDef; var i:uint; while (i < objViews.length) { objView = objViews[i]; objView.deselect(); j = 0; while (j < objs.length) { obj = objs[j]; if (objView.obj == obj){ objView.select(); }; j++; }; i++; }; } } }//package editor.view
Section 180
//PropsMediator (editor.view.PropsMediator) package editor.view { import org.puremvc.as3.interfaces.*; import editor.model.*; import editor.model.objects.*; import editor.view.components.*; import org.puremvc.as3.patterns.mediator.*; import editor.view.components.props.*; public class PropsMediator extends Mediator implements IMediator { private var _view:PropsView; private var objPropsView:ObjPropsView; public static const NAME:String = "ObjPropsMediator"; public function PropsMediator(viewComponent:PropsView):void{ super(mediatorName, viewComponent); init(); } override public function listNotificationInterests():Array{ return ([EditorProxy.OBJECTS_SELECT, EditorProxy.OBJECT_UPDATE, EditorProxy.OBJECT_REMOVE]); } private function objectRemove():void{ var editorProxy:EditorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); var objs:Array = editorProxy.getSelectedObjects(); objectsSelect(objs); } private function objectUpdate(obj:BaseObjectDef):void{ if (objPropsView){ if (objPropsView.obj == obj){ objPropsView.update(); }; }; } private function init():void{ _view = (getViewComponent() as PropsView); } private function objectsSelect(objs:Array):void{ var obj:BaseObjectDef; if (objPropsView){ objPropsView.destroy(); objPropsView = null; }; if (objs.length > 0){ if (objs.length == 1){ obj = objs[0]; if ((obj is PlayerDef)){ return; }; if ((obj is CircleDef)){ objPropsView = new CirclePropsView((obj as CircleDef)); } else { if ((obj is RectDef)){ objPropsView = new RectPropsView((obj as RectDef)); } else { return; }; }; } else { objPropsView = new SeveralObjsPropsView(objs[0]); }; _view.container.addChild(objPropsView); }; } override public function handleNotification(note:INotification):void{ switch (note.getName()){ case EditorProxy.OBJECTS_SELECT: objectsSelect((note.getBody() as Array)); break; case EditorProxy.OBJECT_UPDATE: objectUpdate((note.getBody() as BaseObjectDef)); break; case EditorProxy.OBJECT_REMOVE: objectRemove(); break; }; } } }//package editor.view
Section 181
//ShapesMediator (editor.view.ShapesMediator) package editor.view { import flash.events.*; import org.puremvc.as3.interfaces.*; import editor.model.*; import game.model.*; import core.shapes.*; import editor.model.objects.*; import editor.view.components.*; import org.puremvc.as3.patterns.mediator.*; import editor.view.components.shapes.*; public class ShapesMediator extends Mediator implements IMediator { private var editorProxy:EditorProxy; private var _view:ShapesView; private var items:Array; private var notesProxy:NotesProxy; public static const NAME:String = "ShapesMediator"; public function ShapesMediator(viewComponent:ShapesView):void{ super(NAME, viewComponent); init(); } public function destroy():void{ facade.removeMediator(NAME); } private function createItems():void{ var item:ShapeHolderItem; items = []; var i:int; while (i < 5) { item = new ShapeHolderItem(i); _view.itemsContainer.addChild(item); item.x = (i * 60); items.push(item); i++; }; } private function objectUpdate(obj:BaseObjectDef):void{ var i:int; var item:ShapeHolderItem; var shape:BaseShape; if (_view.inner.visible){ i = 0; while (i < items.length) { item = items[i]; if (item.isObjectInside(obj)){ if ((obj is CircleDef)){ shape = new CircleShape((obj as CircleDef).r); } else { if ((obj is RectDef)){ shape = new RectShape((obj as RectDef).width, (obj as RectDef).height); }; }; if (shape){ notesProxy.push(EditorProxy.OBJECT_REMOVE, obj); notesProxy.push(EditorProxy.SHAPE_ADD, [shape, i]); }; break; }; i++; }; }; } private function init():void{ _view = (getViewComponent() as ShapesView); notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); editorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); _view.inner.visible = false; createItems(); _view.show_bt.addEventListener(MouseEvent.CLICK, showClickHandler); _view.hide_bt.addEventListener(MouseEvent.CLICK, hideClickHandler); } override public function handleNotification(note:INotification):void{ switch (note.getName()){ case EditorProxy.OBJECT_UPDATE: objectUpdate((note.getBody() as BaseObjectDef)); break; case EditorProxy.SHAPE_ADD: shapeAdd((note.getBody() as Array)); break; }; } private function shapeAdd(params:Array):void{ var shape:BaseShape = params[0]; var index:int = params[1]; var item:ShapeHolderItem = items[index]; item.addShape(shape); } override public function listNotificationInterests():Array{ return ([EditorProxy.OBJECT_UPDATE, EditorProxy.SHAPE_ADD]); } private function hideClickHandler(e:MouseEvent):void{ _view.inner.visible = false; _view.show_bt.visible = true; } private function showClickHandler(e:MouseEvent):void{ _view.inner.visible = true; _view.show_bt.visible = false; } } }//package editor.view
Section 182
//ToolsMediator (editor.view.ToolsMediator) package editor.view { import flash.events.*; import org.puremvc.as3.interfaces.*; import editor.model.*; import flash.display.*; import game.model.*; import editor.view.components.*; import editor.view.components.tools.*; import org.puremvc.as3.patterns.mediator.*; public class ToolsMediator extends Mediator implements IMediator { private var editorProxy:EditorProxy; private var _view:ToolsView; private var toolTypes:Array; private var canvasScale:Number; private var selectedTool:ToolView; private var notesProxy:NotesProxy; private var toolViews:Array; public static const NAME:String = "ToolsMediator"; public function ToolsMediator(viewComponent:ToolsView):void{ super(NAME, viewComponent); init(); } override public function handleNotification(note:INotification):void{ switch (note.getName()){ case EditorProxy.TOOL_SELECT: toolSelect((note.getBody() as Tool)); break; case EditorProxy.OBJECTS_SELECT: objectsSelect((note.getBody() as Array)); break; case EditorProxy.OBJECT_REMOVE: objectsRemove((note.getBody() as Array)); break; }; } private function getToolView(tool:Tool):ToolView{ var toolView:ToolView; var i:uint; while (i < toolViews.length) { toolView = toolViews[i]; if (toolView.tool == tool){ return (toolView); }; i++; }; return (null); } private function init():void{ _view = (getViewComponent() as ToolsView); notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); } private function getToolByType(type:String):Tool{ var tool:Tool; var tools:Array = editorProxy.getTools(); var i:uint; while (i < tools.length) { tool = tools[i]; if (tool.type == type){ return (tool); }; i++; }; return (null); } override public function listNotificationInterests():Array{ return ([EditorProxy.TOOL_SELECT, EditorProxy.OBJECTS_SELECT, EditorProxy.OBJECT_REMOVE]); } override public function onRegister():void{ editorProxy = (facade.retrieveProxy(EditorProxy.NAME) as EditorProxy); initTools(); canvasScale = 1; _view.window.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); toolTypes = [Tool.TYPE_SELECTION, Tool.TYPE_CIRCLE, Tool.TYPE_RECT, Tool.TYPE_DIST_JOINT, Tool.TYPE_REV_JOINT, Tool.TYPE_MOTOR]; notesProxy.push(EditorProxy.TOOL_SELECT, editorProxy.getTools()[0]); } private function initTools():void{ var tool:Tool; var toolView:ToolView; var tools:Array = editorProxy.getTools(); toolViews = []; var i:uint; for (;i < tools.length;i++) { tool = tools[i]; switch (tool.type){ case Tool.TYPE_SELECTION: toolView = new SelectionTool(_view.selectionTool, tool); break; case Tool.TYPE_CIRCLE: toolView = new CircleTool(_view.circleTool, tool); break; case Tool.TYPE_RECT: toolView = new RectTool(_view.rectTool, tool); break; case Tool.TYPE_DIST_JOINT: toolView = new DistJointTool(_view.distJointTool, tool); break; case Tool.TYPE_REV_JOINT: toolView = new SimpleTool(_view.revJointTool, tool); break; case Tool.TYPE_MOTOR: toolView = new SimpleTool(_view.motorTool, tool); break; default: continue; }; toolViews.push(toolView); toolView.addEventListener(ToolView.SELECT, toolSelectHandler); }; } private function keyDownHandler(e:KeyboardEvent):void{ var tool:Tool; var editorMed:EditorMediator = (facade.retrieveMediator(EditorMediator.NAME) as EditorMediator); var editorView:EditorView = (editorMed.getViewComponent() as EditorView); var canvas:Sprite = editorView.canvas; if ((((e.keyCode >= 49)) && ((e.keyCode <= 55)))){ tool = getToolByType(toolTypes[(e.keyCode - 49)]); if (editorProxy.selectedTool != tool){ notesProxy.push(EditorProxy.TOOL_SELECT, tool); }; }; } private function toolSelect(tool:Tool):void{ if (selectedTool){ selectedTool.deselect(); }; selectedTool = getToolView(tool); selectedTool.select(); editorProxy.selectedTool = selectedTool.tool; } private function objectsSelect(objs:Array):void{ if (objs.length == 0){ _view.window.visible = true; } else { _view.window.visible = false; }; } private function objectsRemove(objs:Array):void{ _view.window.visible = true; } public function destroy():void{ _view.window.stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); facade.removeMediator(NAME); } private function toolSelectHandler(e:Event):void{ var toolView:ToolView = (e.target as ToolView); notesProxy.push(EditorProxy.TOOL_SELECT, toolView.tool); } } }//package editor.view
Section 183
//GameAbortCommand (game.controller.GameAbortCommand) package game.controller { import org.puremvc.as3.interfaces.*; import game.view.components.*; import game.model.*; import org.puremvc.as3.patterns.command.*; import game.view.*; public class GameAbortCommand extends SimpleCommand implements ICommand { public function GameAbortCommand(){ super(); } override public function execute(note:INotification):void{ var gameProxy:GameProxy = (facade.retrieveProxy(GameProxy.NAME) as GameProxy); gameProxy.gameAbort(); var levelSelectMed:LevelSelectMediator = (facade.retrieveMediator(LevelSelectMediator.NAME) as LevelSelectMediator); if (levelSelectMed){ levelSelectMed.destroy(); }; var gameCompleteMed:GameCompleteMediator = (facade.retrieveMediator(GameCompleteMediator.NAME) as GameCompleteMediator); if (gameCompleteMed){ gameCompleteMed.destroy(); }; var appMed:AppMediator = (facade.retrieveMediator(AppMediator.NAME) as AppMediator); var mainMenuView:MainMenuView = new MainMenuView(); appMed.getViewContainer().addChild(mainMenuView); var mainMenuMed:MainMenuMediator = new MainMenuMediator(mainMenuView); facade.registerMediator(mainMenuMed); } } }//package game.controller
Section 184
//GameCompleteCommand (game.controller.GameCompleteCommand) package game.controller { import org.puremvc.as3.interfaces.*; import game.view.components.*; import org.puremvc.as3.patterns.command.*; import game.view.*; public class GameCompleteCommand extends SimpleCommand implements ICommand { public function GameCompleteCommand(){ super(); } override public function execute(note:INotification):void{ var appMed:AppMediator = (facade.retrieveMediator(AppMediator.NAME) as AppMediator); var gameCompleteView:GameCompleteView = new GameCompleteView(); appMed.getViewContainer().addChild(gameCompleteView); var gameCompleteMed:GameCompleteMediator = new GameCompleteMediator(gameCompleteView); facade.registerMediator(gameCompleteMed); } } }//package game.controller
Section 185
//GameStartCommand (game.controller.GameStartCommand) package game.controller { import org.puremvc.as3.interfaces.*; import game.view.components.*; import game.model.*; import org.puremvc.as3.patterns.command.*; import game.view.*; public class GameStartCommand extends SimpleCommand implements ICommand { public function GameStartCommand(){ super(); } override public function execute(note:INotification):void{ var mainMenuMed:MainMenuMediator = (facade.retrieveMediator(MainMenuMediator.NAME) as MainMenuMediator); mainMenuMed.destroy(); var gameProxy:GameProxy = new GameProxy(); facade.registerProxy(gameProxy); gameProxy.gameStart(); var appMed:AppMediator = (facade.retrieveMediator(AppMediator.NAME) as AppMediator); var levelSelectView:LevelSelectView = new LevelSelectView(); appMed.getViewContainer().addChild(levelSelectView); var levelSelectMed:LevelSelectMediator = new LevelSelectMediator(levelSelectView); facade.registerMediator(levelSelectMed); } } }//package game.controller
Section 186
//InitializeCommand (game.controller.InitializeCommand) package game.controller { import org.puremvc.as3.interfaces.*; import game.view.components.*; import game.model.*; import org.puremvc.as3.patterns.command.*; import game.view.*; public class InitializeCommand extends SimpleCommand implements ICommand { public function InitializeCommand(){ super(); } override public function execute(note:INotification):void{ var appView:AppView = new AppView(); ApplicationFacade.getInstance().viewContainer.addChild(appView); var appMed:AppMediator = new AppMediator(appView); facade.registerMediator(appMed); var mainMenuView:MainMenuView = new MainMenuView(); appMed.getViewContainer().addChild(mainMenuView); var mainMenuMed:MainMenuMediator = new MainMenuMediator(mainMenuView); facade.registerMediator(mainMenuMed); var appProxy:AppProxy = (facade.retrieveProxy(AppProxy.NAME) as AppProxy); appProxy.initializeComplete(); var logoView:LogoView = new LogoView(); appMed.getSplashContainer().addChild(logoView); } } }//package game.controller
Section 187
//LevelAbortCommand (game.controller.LevelAbortCommand) package game.controller { import org.puremvc.as3.interfaces.*; import game.view.components.*; import game.model.*; import org.puremvc.as3.patterns.command.*; import game.view.*; public class LevelAbortCommand extends SimpleCommand implements ICommand { public function LevelAbortCommand(){ super(); } override public function execute(note:INotification):void{ var levelMed:LevelMediator = (facade.retrieveMediator(LevelMediator.NAME) as LevelMediator); levelMed.destroy(); var levelCompleteMed:LevelCompleteMediator = (facade.retrieveMediator(LevelCompleteMediator.NAME) as LevelCompleteMediator); if (levelCompleteMed){ levelCompleteMed.destroy(); }; var gameProxy:GameProxy = (facade.retrieveProxy(GameProxy.NAME) as GameProxy); gameProxy.levelAbort(); var appMed:AppMediator = (facade.retrieveMediator(AppMediator.NAME) as AppMediator); var levelSelectView:LevelSelectView = new LevelSelectView(); appMed.getViewContainer().addChild(levelSelectView); var levelSelectMed:LevelSelectMediator = new LevelSelectMediator(levelSelectView); facade.registerMediator(levelSelectMed); } } }//package game.controller
Section 188
//LevelCompleteCommand (game.controller.LevelCompleteCommand) package game.controller { import org.puremvc.as3.interfaces.*; import game.view.components.*; import org.puremvc.as3.patterns.command.*; import game.view.*; public class LevelCompleteCommand extends SimpleCommand implements ICommand { public function LevelCompleteCommand(){ super(); } override public function execute(note:INotification):void{ var appMed:AppMediator = (facade.retrieveMediator(AppMediator.NAME) as AppMediator); var levelCompleteView:LevelCompleteView = new LevelCompleteView(); appMed.getViewContainer().addChild(levelCompleteView); var levelCompleteMed:LevelCompleteMediator = new LevelCompleteMediator(levelCompleteView); facade.registerMediator(levelCompleteMed); } } }//package game.controller
Section 189
//LevelStartCommand (game.controller.LevelStartCommand) package game.controller { import org.puremvc.as3.interfaces.*; import game.view.components.*; import game.model.*; import org.puremvc.as3.patterns.command.*; import game.view.*; public class LevelStartCommand extends SimpleCommand implements ICommand { public function LevelStartCommand(){ super(); } override public function execute(note:INotification):void{ var levelSelectMed:LevelSelectMediator = (facade.retrieveMediator(LevelSelectMediator.NAME) as LevelSelectMediator); levelSelectMed.destroy(); var appMed:AppMediator = (facade.retrieveMediator(AppMediator.NAME) as AppMediator); var levelView:LevelView = new LevelView(); appMed.getViewContainer().addChild(levelView); var levelMed:LevelMediator = new LevelMediator(levelView); facade.registerMediator(levelMed); var gameProxy:GameProxy = (facade.retrieveProxy(GameProxy.NAME) as GameProxy); gameProxy.levelStart((note.getBody() as int)); levelMed.processLevelStart(); } } }//package game.controller
Section 190
//StartupCommand (game.controller.StartupCommand) package game.controller { import org.puremvc.as3.interfaces.*; import flash.display.*; import game.model.*; import org.puremvc.as3.patterns.command.*; public class StartupCommand extends SimpleCommand implements ICommand { public function StartupCommand(){ super(); } override public function execute(note:INotification):void{ var container:Sprite = note.getBody().container; var appProxy:AppProxy = new AppProxy(); facade.registerProxy(appProxy); appProxy.startApp(); } } }//package game.controller
Section 191
//AppProxy (game.model.AppProxy) package game.model { import flash.events.*; import game.view.components.*; import editor.model.*; import core.*; import flash.display.*; import game.controller.*; import org.puremvc.as3.patterns.proxy.*; import flash.system.*; import editor.controller.*; import game.view.*; import flash.net.*; import caurina.transitions.properties.*; import SWFStats.*; public class AppProxy extends Proxy { public var agi; private var devKey:String;// = "81e402f6d18cfd00bc230089f5128a2a" private var gameKey:String;// = "wake-the-royalty" private var notesProxy:NotesProxy; public static const GAME_URL:String = ("http://olologames.com/playgame.php?id=" + GAME_ID); public static const GAME_ABORT:String = "GameAbort"; public static const MORE_GAMES_URL:String = "http://armorgames.com"; public static const GAME_ID:int = 92; public static const NAME:String = "AppProxy"; public static const EDITOR_CLOSE:String = "EditorClose"; public static const INITIALIZE:String = "Initialize"; public static const ARMORBLOG_URL:String = "http://armorblog.com"; public static const HIGHSCORES_URL:String = ("http://olologames.com/highscores.php?id=" + GAME_ID); public static const WALKTHROUGH_URL:String = "http://armorgames.com/guide/wake-the-royalty-walk-through"; public static const FACEBOOK_URL:String = "http://www.facebook.com/pages/Armor-Games/19522089061"; public static const SITE_URL:String = "http://armorgames.com"; public static const TWITTER_URL:String = "http://twitter.com/armorgames"; public static const GAME_COMPLETE:String = "GameComplete"; public static const INSERTSCORE_URL:String = "http://olologames.com/insertscore.php"; public static const EDITOR_START:String = "EditorStart"; public static const MUSICBY_URL:String = "http://imperfectdisciple.newgrounds.com/"; public static const GAME_START:String = "GameStart"; public static const ORIGINAL_GAME_URL:String = "http://armorgames.com/play/4839/wake-up-the-box"; public static var GAME_VERSION:String = "0.96"; public function AppProxy():void{ super(NAME); init(); } private function initArmorScores():void{ var agi_url:String = "http://agi.armorgames.com/assets/agi/AGI.swf"; Security.allowDomain(agi_url); Security.allowInsecureDomain(agi_url); var urlRequest:URLRequest = new URLRequest(agi_url); var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete); loader.load(urlRequest); } public function initializeComplete():void{ Fader.getInstance(); initArmorScores(); } private function loadComplete(e:Event):void{ var appMed:AppMediator = (facade.retrieveMediator(AppMediator.NAME) as AppMediator); agi = e.currentTarget.content; var appView:AppView = (appMed.getViewComponent() as AppView); appView.scores.addChild(agi); agi.init(devKey, gameKey); } private function init():void{ facade.registerCommand(INITIALIZE, InitializeCommand); facade.registerCommand(GAME_START, GameStartCommand); facade.registerCommand(GAME_ABORT, GameAbortCommand); facade.registerCommand(GAME_COMPLETE, GameCompleteCommand); facade.registerCommand(EDITOR_START, EditorStartCommand); facade.registerCommand(EDITOR_CLOSE, EditorCloseCommand); notesProxy = new NotesProxy(); facade.registerProxy(notesProxy); trace("log view?"); Tracker.LogView(); } private function editorAssetsInitHandler(e:Event):void{ var embedAssets:GameAssets = GameAssets.getInstance(); embedAssets.addEventListener(Event.INIT, assetsInitHandler); embedAssets.init(); } private function assetsInitHandler(e:Event=null):void{ if (Preloader.DOMAIN_KONG){ GAME_VERSION = (GAME_VERSION + " kong"); }; SaveData.getInstance().initialize(); SoundShortcuts.init(); notesProxy.push(INITIALIZE); CoreEngine.getInstance().initialize(); } private function coreAssetsInitHandler(e:Event):void{ var editorAssets:EditorAssets = EditorAssets.getInstance(); editorAssets.addEventListener(Event.INIT, editorAssetsInitHandler); editorAssets.init(); } public function startApp():void{ var coreAssets:CoreAssets = CoreAssets.getInstance(); coreAssets.addEventListener(Event.INIT, coreAssetsInitHandler); coreAssets.init(); } } }//package game.model
Section 192
//GameAssets (game.model.GameAssets) package game.model { import flash.events.*; import flash.display.*; import flash.system.*; public class GameAssets extends EventDispatcher { private var Assets:Class; private var appDomain:ApplicationDomain; private static var instance:GameAssets; public function GameAssets():void{ Assets = GameAssets_Assets; super(); } public function init():void{ var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.INIT, assetsInitHandler); loader.loadBytes(new Assets()); } private function assetsInitHandler(e:Event):void{ appDomain = e.target.content.loaderInfo.applicationDomain; dispatchEvent(new Event(Event.INIT)); } public function getAssetClass(name:String):Class{ if (!appDomain.hasDefinition(name)){ trace((("*Error*: There is no definition of class '" + name) + "'")); return (null); }; return ((appDomain.getDefinition(name) as Class)); } public static function getInstance():GameAssets{ if (!instance){ instance = new (GameAssets); }; return (instance); } } }//package game.model
Section 193
//GameAssets_Assets (game.model.GameAssets_Assets) package game.model { import mx.core.*; public class GameAssets_Assets extends ByteArrayAsset { } }//package game.model
Section 194
//GameLevel (game.model.GameLevel) package game.model { import core.*; public class GameLevel extends CoreLevel { public var assetName:String; public function GameLevel(id:int, assetName:String){ this.assetName = assetName; super(id); } } }//package game.model
Section 195
//GameProxy (game.model.GameProxy) package game.model { import game.view.components.*; import core.*; import game.controller.*; import org.puremvc.as3.patterns.proxy.*; import game.view.*; import SWFStats.*; public class GameProxy extends Proxy { private var engine:CoreEngine; public var currentLevel:GameLevel; public var playername:String; private var notesProxy:NotesProxy; public var levels:Array; public static const LEVEL_COMPLETE:String = "LevelComplete"; public static const LEVEL_ABORT:String = "LevelAbort"; public static const LEVEL_START:String = "LevelStart"; public static const NAME:String = "GameProxy"; public function GameProxy():void{ super(NAME); init(); } private function yeahGameComplete():void{ notesProxy.push(AppProxy.GAME_COMPLETE); } public function destroy():void{ engine.destroy(); facade.removeProxy(NAME); } public function levelStart(id:int):void{ var levelMed:LevelMediator = (facade.retrieveMediator(LevelMediator.NAME) as LevelMediator); var levelView:LevelView = (levelMed.getViewComponent() as LevelView); var nextLevel:GameLevel = levels[id]; if (currentLevel){ engine.isLevelRestart = ((currentLevel.id == nextLevel.id)) ? true : false; }; currentLevel = nextLevel; engine.levelStart(currentLevel, levelView.coreContainer); var LevelSpriteClass:Class = CoreAssets.getInstance().getAssetClass(currentLevel.assetName); LevelSpriteParser.getInstance().parse(new (LevelSpriteClass)); } private function init():void{ if (!facade.hasCommand(LEVEL_START)){ facade.registerCommand(LEVEL_START, LevelStartCommand); }; if (!facade.hasCommand(LEVEL_ABORT)){ facade.registerCommand(LEVEL_ABORT, LevelAbortCommand); }; if (!facade.hasCommand(LEVEL_COMPLETE)){ facade.registerCommand(LEVEL_COMPLETE, LevelCompleteCommand); }; notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); engine = CoreEngine.getInstance(); playername = "Mr. Box"; Tracker.LogPlay(); } public function gameAbort():void{ engine.removeEventListener(CoreEngine.LEVEL_COMPLETE, levelCompleteHandler); destroy(); } private function levelCompleteHandler(e:CoreEvent):void{ currentLevel.complete(engine.elapsedTime); var nextLevel:CoreLevel = levels[(currentLevel.id + 1)]; if (nextLevel){ nextLevel.isOpen = true; }; var lastLevel:CoreLevel = levels[(levels.length - 1)]; if (currentLevel.id == lastLevel.id){ Fader.getInstance().fade(yeahGameComplete); } else { notesProxy.push(LEVEL_COMPLETE); }; if (Preloader.DOMAIN_KONG){ Preloader.kongregate.scores.submit(getTotalScore()); }; } public function gameStart():void{ var i:int; var level:GameLevel; var levelObj:Object; var names:Array = ["Level25", "Level2", "Level13", "Level28", "Level29", "Level3", "Level8", "Level26", "Level16", "Level1", "Level10", "Level21", "Level23", "Level24", "Level19", "Level4", "Level27", "Level14", "Level17", "Level12", "Level22", "Level15", "Level18", "Level7", "Level20"]; levels = []; i = 0; while (i < names.length) { level = new GameLevel(i, names[i]); levels.push(level); i++; }; var completedLevels:Array = SaveData.getInstance().completedLevels; i = 0; while (i < completedLevels.length) { levelObj = completedLevels[i]; level = levels[i]; if (level){ level.isOpen = levelObj.isOpen; level.isCompleted = levelObj.isCompleted; level.score = levelObj.score; }; i++; }; engine.addEventListener(CoreEngine.LEVEL_COMPLETE, levelCompleteHandler); } public function levelAbort():void{ engine.levelAbort(); } public function getTotalScore():int{ var level:CoreLevel; var totalScore:int; var i:int; while (i < levels.length) { level = levels[i]; totalScore = (totalScore + level.score); i++; }; return (totalScore); } } }//package game.model
Section 196
//LevelSpriteParser (game.model.LevelSpriteParser) package game.model { import core.*; import flash.display.*; import core.shapes.*; import core.objects.*; import flash.geom.*; import core.view.*; import core.tools.*; public class LevelSpriteParser { private var engine:CoreEngine; private static var instance:LevelSpriteParser; public function LevelSpriteParser():void{ super(); init(); } private function init():void{ engine = CoreEngine.getInstance(); } private function parseObjects(levelSprite:Sprite):void{ var objectSprite:Sprite; var obj:BodyObject; var rectShape:RectShape; var circleShape:CircleShape; var box:Box; var boxWife:BoxWife; var boxSon:BoxSon; var hinge:Hinge; var motor:Motor; var joint:DistanceJoint; var assets:CoreAssets = CoreAssets.getInstance(); var StaticRectClass:Class = assets.getAssetClass(BodyObject.STATIC_RECT_CLASS_NAME); var DynamicRectClass:Class = assets.getAssetClass(BodyObject.DYNAMIC_RECT_CLASS_NAME); var StaticCircleClass:Class = assets.getAssetClass(BodyObject.STATIC_CIRCLE_CLASS_NAME); var DynamicCircleClass:Class = assets.getAssetClass(BodyObject.DYNAMIC_CIRCLE_CLASS_NAME); var StickyRectClass:Class = assets.getAssetClass(BodyObject.STICKY_RECT_CLASS_NAME); var StickyCircleClass:Class = assets.getAssetClass(BodyObject.STICKY_CIRCLE_CLASS_NAME); var BoxClass:Class = assets.getAssetClass(Box.SKIN_CLASS_NAME); var BoxWifeClass:Class = assets.getAssetClass(BoxWife.SKIN_CLASS_NAME); var BoxSonClass:Class = assets.getAssetClass(BoxSon.SKIN_CLASS_NAME); var HingeClass:Class = assets.getAssetClass(Hinge.SKIN_CLASS_NAME); var MotorClass:Class = assets.getAssetClass(Motor.SKIN_CLASS_NAME); var DistanceJointClass:Class = assets.getAssetClass(DistanceJoint.SKIN_CLASS_NAME); var objectSprites:Sprite = (levelSprite.getChildByName("objects") as Sprite); engine.objects = []; var i:uint; for (;i < objectSprites.numChildren;i++) { objectSprite = (objectSprites.getChildAt(i) as Sprite); if ((objectSprite is StaticRectClass)){ obj = new BodyObject(objectSprite.x, objectSprite.y, true); rectShape = new RectShape(objectSprite.width, objectSprite.height); obj.addRectShape(rectShape, new Point(objectSprite.x, objectSprite.y)); engine.objects.push(obj); } else { if ((objectSprite is DynamicRectClass)){ obj = new BodyObject(objectSprite.x, objectSprite.y, false); rectShape = new RectShape(objectSprite.width, objectSprite.height); obj.addRectShape(rectShape, new Point(objectSprite.x, objectSprite.y)); engine.objects.push(obj); } else { if ((objectSprite is StaticCircleClass)){ obj = new BodyObject(objectSprite.x, objectSprite.y, true); circleShape = new CircleShape((objectSprite.width / 2)); obj.addCircleShape(circleShape, new Point(objectSprite.x, objectSprite.y)); engine.objects.push(obj); } else { if ((objectSprite is DynamicCircleClass)){ obj = new BodyObject(objectSprite.x, objectSprite.y, false); circleShape = new CircleShape((objectSprite.width / 2)); obj.addCircleShape(circleShape, new Point(objectSprite.x, objectSprite.y)); engine.objects.push(obj); } else { if ((objectSprite is StickyRectClass)){ obj = new StickyBodyObject(objectSprite.x, objectSprite.y); rectShape = new RectShape(objectSprite.width, objectSprite.height); obj.addRectShape(rectShape, new Point(objectSprite.x, objectSprite.y)); engine.objects.push(obj); } else { if ((objectSprite is StickyCircleClass)){ obj = new StickyBodyObject(objectSprite.x, objectSprite.y); circleShape = new CircleShape((objectSprite.width / 2)); obj.addCircleShape(circleShape, new Point(objectSprite.x, objectSprite.y)); engine.objects.push(obj); } else { if ((objectSprite is BoxClass)){ box = new Box(objectSprite.x, objectSprite.y); engine.objects.push(box); } else { if ((objectSprite is BoxWifeClass)){ boxWife = new BoxWife(objectSprite.x, objectSprite.y); engine.objects.push(boxWife); } else { if ((objectSprite is BoxSonClass)){ boxSon = new BoxSon(objectSprite.x, objectSprite.y); engine.objects.push(boxSon); } else { if ((objectSprite is HingeClass)){ hinge = new Hinge(objectSprite.x, objectSprite.y); engine.objects.push(hinge); } else { if ((objectSprite is MotorClass)){ motor = createMotor(objectSprite); engine.objects.push(motor); } else { if ((objectSprite is DistanceJointClass)){ joint = createDistanceJoint(objectSprite); if (joint){ engine.objects.push(joint); }; } else { continue; }; }; }; }; }; }; }; }; }; }; }; }; }; } private function parseShapes(levelSprite:Sprite):void{ var i:int; var shapeSprite:Sprite; var rectShape:RectShape; var circleShape:CircleShape; engine.addShapeTool = new AddShapeTool(); var ShapeRectClass:Class = engine.assets.getAssetClass(RectShape.SKIN_CLASS_NAME); var ShapeCircleClass:Class = engine.assets.getAssetClass(CircleShape.SKIN_CLASS_NAME); var shapesSprite:Sprite = (levelSprite.getChildByName("shapes") as Sprite); var shapes:Array = []; if (shapesSprite){ i = 0; while (i < shapesSprite.numChildren) { shapeSprite = (shapesSprite.getChildAt(i) as Sprite); if ((shapeSprite is ShapeRectClass)){ rectShape = new RectShape(shapeSprite.width, shapeSprite.height); shapes.push(rectShape); } else { if ((shapeSprite is ShapeCircleClass)){ circleShape = new CircleShape((shapeSprite.width / 2)); shapes.push(circleShape); }; }; i++; }; }; engine.addShapeTool.initShapes(shapes); engine.shapesPreview = new ShapesPreview(); engine.addShapeTool.start(); } private function createDistanceJoint(objectSprite:Sprite):DistanceJoint{ var params:Array; var x2:Number; var y2:Number; var isMx:String; var isMy:String; var distJoint:DistanceJoint; if (objectSprite.name != ""){ params = objectSprite.name.split("_"); x2 = params[1]; y2 = params[2]; isMx = params[3]; isMy = params[4]; if (isMx == "m"){ x2 = (x2 * -1); }; if (isMy == "m"){ y2 = (y2 * -1); }; distJoint = new DistanceJoint(objectSprite.x, objectSprite.y, x2, y2); return (distJoint); }; return (null); } private function createMotor(objectSprite:Sprite):Motor{ var params:Array; var direction:String; var torque:Number = 0; if (objectSprite.name != ""){ params = objectSprite.name.split("_"); direction = params[0]; torque = params[1]; if (direction == "m"){ torque = (torque * -1); }; torque = (torque / 10); }; var motor:Motor = new Motor(objectSprite.x, objectSprite.y, torque); return (motor); } public function parse(levelSprite:Sprite):void{ parseObjects(levelSprite); parseShapes(levelSprite); parseHints(levelSprite); } private function parseHints(levelSprite:Sprite):void{ engine.hintsManager.parseHints(levelSprite); } public static function getInstance():LevelSpriteParser{ if (instance == null){ instance = new (LevelSpriteParser); }; return (instance); } } }//package game.model
Section 197
//NotesProxy (game.model.NotesProxy) package game.model { import org.puremvc.as3.interfaces.*; import org.puremvc.as3.patterns.proxy.*; public class NotesProxy extends Proxy implements IProxy { private var notes:Array; public static const NAME:String = "NotesProxy"; public function NotesProxy():void{ super(NAME); init(); } private function init():void{ notes = []; } private function sendNote():void{ var note:Object = notes[0]; trace("note!", note.name); sendNotification(note.name, note.body); sendNoteComplete(); } public function push(name:String, body:Object=null):void{ var note:Object = {name:name, body:body}; notes.push(note); if (notes.length == 1){ sendNote(); }; } private function sendNoteComplete():void{ notes.splice(0, 1); if (notes.length > 0){ sendNote(); }; } } }//package game.model
Section 198
//SaveData (game.model.SaveData) package game.model { import core.*; import flash.net.*; public class SaveData { private var sharedObject:SharedObject; public var isNewGame:Boolean; public var soundEnabled:Boolean; private var levelsNum:int; public var completedLevels:Array; public var musicEnabled:Boolean; private static var instance:SaveData; public function SaveData(){ super(); } public function clearProgress():void{ completedLevels = null; sharedObject.data.completedLevels = null; isNewGame = true; sharedObject.data.isNewGame = isNewGame; sharedObject.flush(); initLevels(); } private function initLevels():void{ var i:int; var levelObj:Object; if (sharedObject.data.completedLevels == null){ completedLevels = new Array(levelsNum); i = 0; while (i < levelsNum) { levelObj = {isCompleted:false, isOpen:false, score:0}; if (i == 0){ levelObj.isOpen = true; }; completedLevels[i] = levelObj; sharedObject.data.completedLevels = completedLevels; i++; }; sharedObject.flush(); } else { completedLevels = new Array(levelsNum); i = 0; while (i <= 25) { levelObj = sharedObject.data.completedLevels[i]; if (levelObj){ completedLevels[i] = {isCompleted:levelObj.isCompleted, isOpen:levelObj.isOpen, score:levelObj.score}; }; i++; }; }; if (sharedObject.data.isNewGame != null){ isNewGame = sharedObject.data.isNewGame; }; } public function levelComplete(level:CoreLevel):void{ var levelObj:Object = {isCompleted:true, isOpen:true, score:level.score}; completedLevels[level.id] = levelObj; sharedObject.data.completedLevels[level.id] = completedLevels[level.id]; if (level.id < (levelsNum - 1)){ completedLevels[(level.id + 1)].isOpen = true; sharedObject.data.completedLevels[(level.id + 1)].isOpen = true; }; isNewGame = false; sharedObject.data.isNewGame = isNewGame; sharedObject.flush(); } public function initialize():void{ levelsNum = 20; sharedObject = SharedObject.getLocal("gameData"); isNewGame = true; musicEnabled = true; soundEnabled = true; initLevels(); } public static function getInstance():SaveData{ if (instance == null){ instance = new (SaveData); }; return (instance); } } }//package game.model
Section 199
//SendScore (game.model.SendScore) package game.model { import flash.events.*; import flash.display.*; import flash.net.*; import flash.text.*; public class SendScore { private var error_tf:TextField; private var viewScores_bt:SimpleButton; private var loader:URLLoader; private var errorHolder:Sprite; private var sendHolder:Sprite; private var gameProxy:GameProxy; private var send_bt:SimpleButton; private var username_tf:TextField; private var skin:Sprite; public function SendScore():void{ super(); init(); } private function ioErrorHandler(e:IOErrorEvent):void{ sendHolder.visible = false; errorHolder.visible = true; trace(e.text); error_tf.text = "ioError"; } private function securityErrorHandler(e:SecurityErrorEvent):void{ sendHolder.visible = false; errorHolder.visible = true; trace(e.text); error_tf.text = "security error"; } private function sendClickHandler(e:MouseEvent):void{ var score:Number; if (((!((username_tf.text == "YOUR NAME"))) && ((username_tf.text.length > 0)))){ gameProxy.playername = username_tf.text; score = gameProxy.getTotalScore(); sendArmorScores(score); sendHolder.visible = false; }; } private function init():void{ var facade:ApplicationFacade = ApplicationFacade.getInstance(); gameProxy = (facade.retrieveProxy(GameProxy.NAME) as GameProxy); } private function completeHandler(e:Event):void{ sendHolder.visible = false; viewScores_bt.visible = true; } public function sendArmorScores(score:Number):void{ var facade:ApplicationFacade = ApplicationFacade.getInstance(); var appProxy:AppProxy = (facade.retrieveProxy(AppProxy.NAME) as AppProxy); appProxy.agi.showScoreboardSubmit(score); } private function usernameClickHandler(e:MouseEvent):void{ username_tf.text = ""; username_tf.removeEventListener(MouseEvent.CLICK, usernameClickHandler); } private function viewScoresClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest(AppProxy.HIGHSCORES_URL)); } } }//package game.model
Section 200
//LevelItem (game.view.components.levelSelect.LevelItem) package game.view.components.levelSelect { import flash.events.*; import game.view.components.*; import core.*; import flash.display.*; import game.model.*; import flash.text.*; public class LevelItem extends Sprite { public var level:CoreLevel; private var back:MovieClip; private var num_tf:TextField; private var window:Sprite; private var score_tf:TextField; public function LevelItem(level:CoreLevel):void{ super(); this.level = level; init(); } private function clickHandler(e:MouseEvent):void{ Fader.getInstance().fade(startLevel); } private function startLevel():void{ var facade:ApplicationFacade = ApplicationFacade.getInstance(); var notesProxy:NotesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); notesProxy.push(GameProxy.LEVEL_START, level.id); } private function init():void{ var WindowClass:Class = GameAssets.getInstance().getAssetClass("LevelItemAsset"); window = new (WindowClass); addChild(window); back = (window.getChildByName("back") as MovieClip); score_tf = (window.getChildByName("score_tf") as TextField); num_tf = (window.getChildByName("num_tf") as TextField); num_tf.text = (level.id + 1).toString(); num_tf.mouseEnabled = false; if (level.isOpen){ if (level.isCompleted){ score_tf.text = level.score.toString(); back.gotoAndStop(2); } else { score_tf.visible = false; back.gotoAndStop(1); }; buttonMode = true; addEventListener(MouseEvent.CLICK, clickHandler); } else { score_tf.visible = false; back.gotoAndStop(3); }; scaleX = (scaleY = 0.9); } } }//package game.view.components.levelSelect
Section 201
//AppView (game.view.components.AppView) package game.view.components { import flash.display.*; import game.model.*; public class AppView extends Sprite { public var container:Sprite; public var music:MovieClip; public var logo_bt:SimpleButton; public var scores:Sprite; public var sound:MovieClip; private var window:Sprite; public var popupContainer:Sprite; public var splashContainer:Sprite; public function AppView(){ super(); init(); } private function init():void{ var windowClass:Class = GameAssets.getInstance().getAssetClass("AppWindow"); window = new (windowClass); addChild(window); container = (window.getChildByName("container") as Sprite); popupContainer = (window.getChildByName("popupContainer") as Sprite); splashContainer = (window.getChildByName("splashContainer") as Sprite); sound = (window.getChildByName("sound") as MovieClip); music = (window.getChildByName("music") as MovieClip); logo_bt = (window.getChildByName("logo_bt") as SimpleButton); scores = new MovieClip(); window.addChild(scores); } } }//package game.view.components
Section 202
//CreditsView (game.view.components.CreditsView) package game.view.components { import flash.display.*; import game.model.*; public class CreditsView extends Sprite { public var egoshin_bt:SimpleButton; public var deforestb_bt:SimpleButton; private var window:Sprite; public var ok_bt:SimpleButton; public var inner:Sprite; public var sponsor_bt:SimpleButton; public var box2d_bt:SimpleButton; public var karataev_bt:SimpleButton; public function CreditsView():void{ super(); init(); } private function init():void{ var WindowClass:Class = GameAssets.getInstance().getAssetClass("CreditsWindow"); window = new (WindowClass); addChild(window); inner = (window.getChildByName("inner") as Sprite); ok_bt = (inner.getChildByName("ok_bt") as SimpleButton); karataev_bt = (inner.getChildByName("karataev_bt") as SimpleButton); egoshin_bt = (inner.getChildByName("egoshin_bt") as SimpleButton); sponsor_bt = (inner.getChildByName("sponsor_bt") as SimpleButton); box2d_bt = (inner.getChildByName("box2d_bt") as SimpleButton); deforestb_bt = (inner.getChildByName("deforestb_bt") as SimpleButton); } } }//package game.view.components
Section 203
//Fader (game.view.components.Fader) package game.view.components { import flash.display.*; import game.model.*; import game.view.*; import caurina.transitions.*; public class Fader { private var window:Sprite; private var callbackFunc:Function; private static var instance:Fader; public function Fader():void{ super(); init(); } private function init():void{ var WindowClass:Class = GameAssets.getInstance().getAssetClass("FaderWindow"); window = new (WindowClass); var facade:ApplicationFacade = ApplicationFacade.getInstance(); var appMed:AppMediator = (facade.retrieveMediator(AppMediator.NAME) as AppMediator); appMed.getPopupContainer().addChild(window); window.visible = false; } private function fadeInComplete():void{ Tweener.addTween(window, {alpha:0, time:0.3, transition:"linear", onComplete:fadeOutComplete}); callbackFunc(); } private function fadeOutComplete():void{ window.visible = false; } public function fade(callbackFunc:Function):void{ this.callbackFunc = callbackFunc; window.visible = true; window.alpha = 0; Tweener.addTween(window, {alpha:1, time:0.3, transition:"linear", onComplete:fadeInComplete}); } public static function getInstance():Fader{ if (instance == null){ instance = new (Fader); }; return (instance); } } }//package game.view.components
Section 204
//GameCompleteView (game.view.components.GameCompleteView) package game.view.components { import flash.display.*; import game.model.*; import flash.text.*; public class GameCompleteView extends Sprite { public var totalScore_tf:TextField; public var back:Sprite; public var sendScore_bt:SimpleButton; private var window:Sprite; public var exit_bt:SimpleButton; public var inner:Sprite; public function GameCompleteView():void{ super(); init(); } private function init():void{ var WindowClass:Class = GameAssets.getInstance().getAssetClass("GameCompleteWindow"); window = new (WindowClass); addChild(window); back = (window.getChildByName("back") as Sprite); inner = (window.getChildByName("inner") as Sprite); totalScore_tf = (inner.getChildByName("score_tf") as TextField); exit_bt = (inner.getChildByName("exit_bt") as SimpleButton); sendScore_bt = (inner.getChildByName("submitScore_bt") as SimpleButton); } } }//package game.view.components
Section 205
//LevelCompleteView (game.view.components.LevelCompleteView) package game.view.components { import flash.display.*; import game.model.*; public class LevelCompleteView extends Sprite { public var nextLevel_bt:SimpleButton; public var restart_bt:SimpleButton; public var moreGames_bt:SimpleButton; public var back:Sprite; public var levels_bt:SimpleButton; private var window:Sprite; public var inner:Sprite; public function LevelCompleteView():void{ super(); init(); } private function init():void{ var WindowClass:Class = GameAssets.getInstance().getAssetClass("LevelCompleteWindow"); window = new (WindowClass); addChild(window); back = (window.getChildByName("back") as Sprite); inner = (window.getChildByName("inner") as Sprite); restart_bt = (inner.getChildByName("restart_bt") as SimpleButton); levels_bt = (inner.getChildByName("levels_bt") as SimpleButton); nextLevel_bt = (inner.getChildByName("nextLevel_bt") as SimpleButton); moreGames_bt = (inner.getChildByName("moreGames_bt") as SimpleButton); } } }//package game.view.components
Section 206
//LevelSelectView (game.view.components.LevelSelectView) package game.view.components { import flash.display.*; import game.model.*; import flash.text.*; public class LevelSelectView extends Sprite { private var window:Sprite; public var itemsContainer:Sprite; public var totalScore_tf:TextField; public var back_bt:SimpleButton; public var totalScoreHolder:Sprite; public function LevelSelectView():void{ super(); init(); } private function init():void{ var WindowClass:Class = GameAssets.getInstance().getAssetClass("LevelSelectWindow"); window = new (WindowClass); addChild(window); totalScoreHolder = (window.getChildByName("totalScoreHolder") as Sprite); totalScore_tf = (totalScoreHolder.getChildByName("totalScore_tf") as TextField); back_bt = (window.getChildByName("back_bt") as SimpleButton); itemsContainer = new Sprite(); window.addChild(itemsContainer); itemsContainer.x = 84; itemsContainer.y = 45; } } }//package game.view.components
Section 207
//LevelView (game.view.components.LevelView) package game.view.components { import flash.display.*; import game.model.*; import flash.text.*; public class LevelView extends Sprite { public var levels_bt:SimpleButton; public var coreContainer:Sprite; public var level_tf:TextField; private var window:Sprite; public var restart_bt:SimpleButton; public var exit_bt:SimpleButton; public var walkthrough_bt:SimpleButton; public function LevelView():void{ super(); init(); } private function init():void{ var WindowClass:Class = GameAssets.getInstance().getAssetClass("LevelWindow"); window = new (WindowClass); addChild(window); coreContainer = (window.getChildByName("coreContainer") as Sprite); exit_bt = (window.getChildByName("exit_bt") as SimpleButton); restart_bt = (window.getChildByName("restart_bt") as SimpleButton); levels_bt = (window.getChildByName("levels_bt") as SimpleButton); walkthrough_bt = (window.getChildByName("walkthrough_bt") as SimpleButton); level_tf = (window.getChildByName("level_tf") as TextField); level_tf.mouseEnabled = false; } } }//package game.view.components
Section 208
//LogoView (game.view.components.LogoView) package game.view.components { import flash.events.*; import flash.display.*; import game.model.*; import game.view.*; import flash.net.*; public class LogoView extends Sprite { private var window:Sprite; private var ag:MovieClip; public function LogoView():void{ super(); init(); } private function clickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest(AppProxy.SITE_URL)); } private function init():void{ var WindowClass:Class = GameAssets.getInstance().getAssetClass("LogoWindow"); window = new (WindowClass); addChild(window); ag = (window.getChildByName("ag") as MovieClip); ag.gotoAndPlay(2); addEventListener(Event.ENTER_FRAME, efHandler); buttonMode = true; ag.addEventListener(MouseEvent.CLICK, clickHandler); } private function efHandler(e:Event):void{ var facade:ApplicationFacade; var appMed:AppMediator; if (ag.currentFrame == ag.totalFrames){ facade = ApplicationFacade.getInstance(); appMed = (facade.retrieveMediator(AppMediator.NAME) as AppMediator); appMed.logoComplete(); ag.stop(); removeEventListener(Event.ENTER_FRAME, efHandler); destroy(); }; } private function destroy():void{ parent.removeChild(this); } private function hideComplete():void{ destroy(); } } }//package game.view.components
Section 209
//MainMenuView (game.view.components.MainMenuView) package game.view.components { import flash.display.*; import game.model.*; import flash.text.*; public class MainMenuView extends Sprite { public var newGameConfirmNo_bt:SimpleButton; public var karataev_bt:SimpleButton; public var newGameConfirmInner:Sprite; public var musicby_bt:SimpleButton; public var highscores_bt:SimpleButton; public var anim:MovieClip; public var armorblog_bt:SimpleButton; public var inner:Sprite; public var clearProgress_bt:SimpleButton; public var continueGame_bt:SimpleButton; public var twitter_bt:SimpleButton; public var editor_bt:SimpleButton; public var wutb_bt:SimpleButton; public var facebook_bt:SimpleButton; public var newGameConfirm:Sprite; private var window:Sprite; public var newGameConfirmYes_bt:SimpleButton; public var version_tf:TextField; public var startGame_bt:SimpleButton; public function MainMenuView():void{ super(); init(); } private function init():void{ var WindowClass:Class = GameAssets.getInstance().getAssetClass("MainMenuWindow"); window = new (WindowClass); addChild(window); inner = (window.getChildByName("inner") as Sprite); startGame_bt = (inner.getChildByName("startGame_bt") as SimpleButton); clearProgress_bt = (window.getChildByName("clearProgress_bt") as SimpleButton); continueGame_bt = (inner.getChildByName("continue_bt") as SimpleButton); highscores_bt = (inner.getChildByName("highscores_bt") as SimpleButton); twitter_bt = (window.getChildByName("twitter_bt") as SimpleButton); version_tf = (window.getChildByName("version_tf") as TextField); musicby_bt = (window.getChildByName("musicby_bt") as SimpleButton); karataev_bt = (window.getChildByName("karataev_bt") as SimpleButton); newGameConfirm = (window.getChildByName("newGameConfirm") as Sprite); newGameConfirmInner = (newGameConfirm.getChildByName("inner") as Sprite); newGameConfirmYes_bt = (newGameConfirmInner.getChildByName("yes_bt") as SimpleButton); newGameConfirmNo_bt = (newGameConfirmInner.getChildByName("no_bt") as SimpleButton); editor_bt = (window.getChildByName("editor_bt") as SimpleButton); anim = (window.getChildByName("anim") as MovieClip); wutb_bt = (window.getChildByName("wutb_bt") as SimpleButton); armorblog_bt = (window.getChildByName("armorblog_bt") as SimpleButton); facebook_bt = (window.getChildByName("facebook_bt") as SimpleButton); } } }//package game.view.components
Section 210
//AppMediator (game.view.AppMediator) package game.view { import flash.events.*; import org.puremvc.as3.interfaces.*; import game.view.components.*; import flash.display.*; import game.model.*; import flash.media.*; import org.puremvc.as3.patterns.mediator.*; import flash.net.*; import caurina.transitions.*; public class AppMediator extends Mediator implements IMediator { private var sndMainMusic:Sound; private var _view:AppView; private var saveData:SaveData; private var musicChannel:SoundChannel; private var musicVolume:Number; private var levelCompleteChannel:SoundChannel; private var sndLevelComplete:Sound; public static const NAME:String = "AppMediator"; public function AppMediator(viewComponent:AppView):void{ super(NAME, viewComponent); init(); } public function logoComplete():void{ if (saveData.musicEnabled){ musicChannel = sndMainMusic.play(0, 10000, new SoundTransform(musicVolume)); }; } private function init():void{ _view = (getViewComponent() as AppView); _view.tabChildren = false; saveData = SaveData.getInstance(); var SndMusicClass:Class = GameAssets.getInstance().getAssetClass("SndMusic"); sndMainMusic = new (SndMusicClass); var SndLevelCompleteClass:Class = GameAssets.getInstance().getAssetClass("SndLevelComplete"); sndLevelComplete = new (SndLevelCompleteClass); musicVolume = 0.7; _view.sound.addEventListener(MouseEvent.CLICK, soundClickHandler); _view.music.addEventListener(MouseEvent.CLICK, musicClickHandler); _view.logo_bt.addEventListener(MouseEvent.CLICK, logoClickHandler); _view.sound.buttonMode = true; _view.music.buttonMode = true; _view.sound.gotoAndStop(1); _view.music.gotoAndStop(1); } private function soundClickHandler(e:MouseEvent):void{ if (saveData.soundEnabled){ saveData.soundEnabled = false; _view.sound.gotoAndStop(2); } else { saveData.soundEnabled = true; _view.sound.gotoAndStop(1); }; } private function levelAbort():void{ if (levelCompleteChannel){ Tweener.addTween(levelCompleteChannel, {_sound_volume:0, time:0.5}); }; Tweener.addTween(musicChannel, {_sound_volume:musicVolume, time:0.5}); } private function levelComplete():void{ levelCompleteChannel = sndLevelComplete.play(0, 1, new SoundTransform(musicVolume)); Tweener.addTween(musicChannel, {_sound_volume:0, time:0.5}); } override public function listNotificationInterests():Array{ return ([GameProxy.LEVEL_COMPLETE, GameProxy.LEVEL_START, GameProxy.LEVEL_ABORT]); } public function getSplashContainer():Sprite{ return (_view.splashContainer); } private function musicClickHandler(e:MouseEvent):void{ if (saveData.musicEnabled){ saveData.musicEnabled = false; _view.music.gotoAndStop(2); musicVolume = 0; Tweener.addTween(musicChannel, {_sound_volume:0, time:0.5}); } else { saveData.musicEnabled = true; _view.music.gotoAndStop(1); musicVolume = 0.7; Tweener.addTween(musicChannel, {_sound_volume:musicVolume, time:0.5}); }; } public function getPopupContainer():Sprite{ return (_view.popupContainer); } public function getViewContainer():Sprite{ return (_view.container); } override public function handleNotification(note:INotification):void{ switch (note.getName()){ case GameProxy.LEVEL_COMPLETE: levelComplete(); break; case GameProxy.LEVEL_START: levelStart(); break; case GameProxy.LEVEL_ABORT: levelAbort(); break; }; } private function logoClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest(AppProxy.MORE_GAMES_URL), "_blank"); } private function levelStart():void{ if (levelCompleteChannel){ Tweener.addTween(levelCompleteChannel, {_sound_volume:0, time:0.5}); }; Tweener.addTween(musicChannel, {_sound_volume:musicVolume, time:0.5}); } } }//package game.view
Section 211
//CreditsMediator (game.view.CreditsMediator) package game.view { import flash.events.*; import org.puremvc.as3.interfaces.*; import game.view.components.*; import org.puremvc.as3.patterns.mediator.*; import flash.net.*; public class CreditsMediator extends Mediator implements IMediator { private var _view:CreditsView; public static const NAME:String = "CreditsMediator"; public function CreditsMediator(viewComponent:CreditsView):void{ super(NAME, viewComponent); init(); } override public function listNotificationInterests():Array{ return ([]); } override public function handleNotification(notification:INotification):void{ } private function karataevClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest("mailto:eugene.karataev@gmail.com"), "_blank"); } private function deforestbClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest("http://deforestb.newgrounds.com/"), "_blank"); } private function egoshinClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest("mailto:egoshin83@rambler.ru"), "_blank"); } private function init():void{ _view = (getViewComponent() as CreditsView); _view.karataev_bt.addEventListener(MouseEvent.CLICK, karataevClickHandler); _view.egoshin_bt.addEventListener(MouseEvent.CLICK, egoshinClickHandler); _view.sponsor_bt.addEventListener(MouseEvent.CLICK, sponsorClickHandler); _view.box2d_bt.addEventListener(MouseEvent.CLICK, box2dClickHandler); _view.ok_bt.addEventListener(MouseEvent.CLICK, okClickHandler); _view.deforestb_bt.addEventListener(MouseEvent.CLICK, deforestbClickHandler); } private function destroy():void{ _view.parent.removeChild(_view); facade.removeMediator(NAME); } private function sponsorClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest("http://olologames.com"), "_blank"); } private function okClickHandler(e:MouseEvent):void{ destroy(); } private function box2dClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest("http://box2d.org"), "_blank"); } } }//package game.view
Section 212
//GameCompleteMediator (game.view.GameCompleteMediator) package game.view { import flash.events.*; import org.puremvc.as3.interfaces.*; import game.view.components.*; import game.model.*; import org.puremvc.as3.patterns.mediator.*; public class GameCompleteMediator extends Mediator implements IMediator { private var _view:GameCompleteView; private var sendScore:SendScore; private var notesProxy:NotesProxy; private var gameProxy:GameProxy; public static const NAME:String = "GameCompleteMediator"; public function GameCompleteMediator(viewComponent:GameCompleteView):void{ super(NAME, viewComponent); init(); } private function exitClickHandler(e:MouseEvent):void{ SaveData.getInstance().clearProgress(); Fader.getInstance().fade(gameAbort); } public function destroy():void{ _view.parent.removeChild(_view); facade.removeMediator(NAME); } override public function handleNotification(note:INotification):void{ } override public function listNotificationInterests():Array{ return ([]); } private function sendScoreClickHandler(e:MouseEvent):void{ sendScore.sendArmorScores(gameProxy.getTotalScore()); _view.sendScore_bt.visible = false; SaveData.getInstance().clearProgress(); } private function init():void{ _view = (getViewComponent() as GameCompleteView); notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); gameProxy = (facade.retrieveProxy(GameProxy.NAME) as GameProxy); _view.exit_bt.addEventListener(MouseEvent.CLICK, exitClickHandler); _view.totalScore_tf.text = gameProxy.getTotalScore().toString(); _view.sendScore_bt.addEventListener(MouseEvent.CLICK, sendScoreClickHandler); sendScore = new SendScore(); } private function gameAbort():void{ notesProxy.push(GameProxy.LEVEL_ABORT); notesProxy.push(AppProxy.GAME_ABORT); } } }//package game.view
Section 213
//LevelCompleteMediator (game.view.LevelCompleteMediator) package game.view { import flash.events.*; import org.puremvc.as3.interfaces.*; import game.view.components.*; import core.*; import game.model.*; import org.puremvc.as3.patterns.mediator.*; import flash.net.*; import caurina.transitions.*; public class LevelCompleteMediator extends Mediator implements IMediator { private var _view:LevelCompleteView; private var notesProxy:NotesProxy; private var gameProxy:GameProxy; public static const NAME:String = "LevelCompleteMediator"; public function LevelCompleteMediator(viewComponent:LevelCompleteView):void{ super(NAME, viewComponent); init(); } private function nextLevel():void{ notesProxy.push(GameProxy.LEVEL_ABORT); var nextLevel:CoreLevel = gameProxy.levels[(gameProxy.currentLevel.id + 1)]; if (nextLevel){ notesProxy.push(GameProxy.LEVEL_START, nextLevel.id); } else { trace("GAME COMPLETE!"); }; } public function destroy():void{ _view.parent.removeChild(_view); facade.removeMediator(NAME); } private function nextLevelClickHandler(e:MouseEvent):void{ SaveData.getInstance().levelComplete(gameProxy.currentLevel); Fader.getInstance().fade(nextLevel); } override public function listNotificationInterests():Array{ return ([]); } override public function handleNotification(note:INotification):void{ } private function moreGamesClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest(AppProxy.MORE_GAMES_URL), "_blank"); } private function init():void{ _view = (getViewComponent() as LevelCompleteView); notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); gameProxy = (facade.retrieveProxy(GameProxy.NAME) as GameProxy); _view.restart_bt.addEventListener(MouseEvent.CLICK, restartClickHandler); _view.levels_bt.addEventListener(MouseEvent.CLICK, levelsClickHandler); _view.nextLevel_bt.addEventListener(MouseEvent.CLICK, nextLevelClickHandler); _view.moreGames_bt.addEventListener(MouseEvent.CLICK, moreGamesClickHandler); _view.back.alpha = 0; Tweener.addTween(_view.back, {alpha:1, time:1, transition:"linear"}); _view.moreGames_bt.visible = false; var innerY:Number = _view.inner.y; _view.inner.y = -(_view.inner.height); Tweener.addTween(_view.inner, {y:innerY, time:1, delay:0.5, transition:"easeoutback"}); } private function restartClickHandler(e:MouseEvent):void{ SaveData.getInstance().levelComplete(gameProxy.currentLevel); Fader.getInstance().fade(restartLevel); } private function abortLevel():void{ notesProxy.push(GameProxy.LEVEL_ABORT); } private function restartLevel():void{ notesProxy.push(GameProxy.LEVEL_ABORT); notesProxy.push(GameProxy.LEVEL_START, gameProxy.currentLevel.id); } private function levelsClickHandler(e:MouseEvent):void{ SaveData.getInstance().levelComplete(gameProxy.currentLevel); Fader.getInstance().fade(abortLevel); } } }//package game.view
Section 214
//LevelMediator (game.view.LevelMediator) package game.view { import flash.events.*; import org.puremvc.as3.interfaces.*; import game.view.components.*; import game.model.*; import org.puremvc.as3.patterns.mediator.*; import flash.net.*; import caurina.transitions.*; import flash.ui.*; public class LevelMediator extends Mediator implements IMediator { private var _view:LevelView; private var notesProxy:NotesProxy; public static const NAME:String = "LevelMediator"; public function LevelMediator(viewComponent:LevelView):void{ super(NAME, viewComponent); init(); } private function exitClickHandler(e:MouseEvent):void{ Fader.getInstance().fade(abortGame); } public function destroy():void{ _view.exit_bt.removeEventListener(MouseEvent.CLICK, exitClickHandler); _view.stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); _view.parent.removeChild(_view); facade.removeMediator(NAME); } private function abortGame():void{ notesProxy.push(GameProxy.LEVEL_ABORT); notesProxy.push(AppProxy.GAME_ABORT); } private function walkthroughClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest(AppProxy.WALKTHROUGH_URL)); } override public function listNotificationInterests():Array{ return ([GameProxy.LEVEL_COMPLETE, AppProxy.GAME_COMPLETE]); } private function keyDownHandler(e:KeyboardEvent):void{ var gameProxy:GameProxy; if ((((e.keyCode == Keyboard.SPACE)) || ((e.keyCode == 82)))){ gameProxy = (facade.retrieveProxy(GameProxy.NAME) as GameProxy); _view.stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); Fader.getInstance().fade(restartLevel); }; } private function gameComplete():void{ _view.stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); } override public function handleNotification(note:INotification):void{ switch (note.getName()){ case GameProxy.LEVEL_COMPLETE: levelComplete(); break; case AppProxy.GAME_COMPLETE: gameComplete(); break; }; } public function processLevelStart():void{ var gameProxy:GameProxy = (facade.retrieveProxy(GameProxy.NAME) as GameProxy); _view.level_tf.text = (gameProxy.currentLevel.id + 1).toString(); } private function init():void{ _view = (getViewComponent() as LevelView); notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); _view.exit_bt.addEventListener(MouseEvent.CLICK, exitClickHandler); _view.restart_bt.addEventListener(MouseEvent.CLICK, restartClickHandler); _view.levels_bt.addEventListener(MouseEvent.CLICK, levelsClickHandler); _view.walkthrough_bt.addEventListener(MouseEvent.CLICK, walkthroughClickHandler); _view.exit_bt.visible = false; _view.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); } private function restartClickHandler(e:MouseEvent):void{ Fader.getInstance().fade(restartLevel); } private function restartLevel():void{ var gameProxy:GameProxy = (facade.retrieveProxy(GameProxy.NAME) as GameProxy); notesProxy.push(GameProxy.LEVEL_ABORT); notesProxy.push(GameProxy.LEVEL_START, gameProxy.currentLevel.id); } private function levelsClickHandler(e:MouseEvent):void{ Fader.getInstance().fade(abortLevel); } private function abortLevel():void{ notesProxy.push(GameProxy.LEVEL_ABORT); } private function levelComplete():void{ Tweener.addTween(_view.levels_bt, {alpha:0, time:0.5, transition:"linear"}); Tweener.addTween(_view.restart_bt, {alpha:0, time:0.5, transition:"linear"}); Tweener.addTween(_view.walkthrough_bt, {alpha:0, time:0.5, transition:"linear"}); _view.stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); } private function yeahGameComplete():void{ notesProxy.push(AppProxy.GAME_COMPLETE); } } }//package game.view
Section 215
//LevelSelectMediator (game.view.LevelSelectMediator) package game.view { import flash.events.*; import org.puremvc.as3.interfaces.*; import game.view.components.*; import core.*; import game.model.*; import org.puremvc.as3.patterns.mediator.*; import game.view.components.levelSelect.*; public class LevelSelectMediator extends Mediator implements IMediator { private var _view:LevelSelectView; private var gameProxy:GameProxy; public static const NAME:String = "LevelSelectMediator"; public function LevelSelectMediator(viewComponent:LevelSelectView):void{ super(NAME, viewComponent); init(); } override public function listNotificationInterests():Array{ return ([]); } private function abortGame():void{ var notesProxy:NotesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); notesProxy.push(AppProxy.GAME_ABORT); } private function backClickHandler(e:MouseEvent):void{ Fader.getInstance().fade(abortGame); } private function createItems():void{ var level:CoreLevel; var item:LevelItem; var i:int; while (i < gameProxy.levels.length) { level = gameProxy.levels[i]; item = new LevelItem(level); item.x = ((i % 5) * 100); item.y = (Math.floor((i / 5)) * 80); _view.itemsContainer.addChild(item); i++; }; } private function init():void{ _view = (getViewComponent() as LevelSelectView); gameProxy = (facade.retrieveProxy(GameProxy.NAME) as GameProxy); createItems(); _view.totalScoreHolder.visible = false; _view.totalScore_tf.text = gameProxy.getTotalScore().toString(); _view.back_bt.addEventListener(MouseEvent.CLICK, backClickHandler); } override public function handleNotification(note:INotification):void{ } public function destroy():void{ _view.parent.removeChild(_view); facade.removeMediator(NAME); } } }//package game.view
Section 216
//MainMenuMediator (game.view.MainMenuMediator) package game.view { import flash.events.*; import org.puremvc.as3.interfaces.*; import game.view.components.*; import game.model.*; import org.puremvc.as3.patterns.mediator.*; import flash.net.*; public class MainMenuMediator extends Mediator implements IMediator { private var _view:MainMenuView; private var notesProxy:NotesProxy; public static const NAME:String = "MainMenuMediator"; public function MainMenuMediator(viewComponent:MainMenuView):void{ super(NAME, viewComponent); init(); } override public function handleNotification(note:INotification):void{ } private function highscoresClickHandler(e:MouseEvent):void{ var appProxy:AppProxy = (facade.retrieveProxy(AppProxy.NAME) as AppProxy); appProxy.agi.initAGUI({onClose:closeHandler}); appProxy.agi.showScoreboardList(); } private function wutbClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest(AppProxy.ORIGINAL_GAME_URL), "_blank"); } private function facebookClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest(AppProxy.FACEBOOK_URL), "_blank"); } private function init():void{ _view = (getViewComponent() as MainMenuView); notesProxy = (facade.retrieveProxy(NotesProxy.NAME) as NotesProxy); _view.startGame_bt.addEventListener(MouseEvent.CLICK, startGameClickHandler); _view.clearProgress_bt.addEventListener(MouseEvent.CLICK, clearProgressClickHandler); _view.highscores_bt.addEventListener(MouseEvent.CLICK, highscoresClickHandler); _view.twitter_bt.addEventListener(MouseEvent.CLICK, twitterClickHandler); _view.editor_bt.addEventListener(MouseEvent.CLICK, editorClickHandler); _view.wutb_bt.addEventListener(MouseEvent.CLICK, wutbClickHandler); _view.armorblog_bt.addEventListener(MouseEvent.CLICK, armorblogClickHandler); _view.facebook_bt.addEventListener(MouseEvent.CLICK, facebookClickHandler); _view.musicby_bt.addEventListener(MouseEvent.CLICK, musicbyClickHandler); _view.karataev_bt.addEventListener(MouseEvent.CLICK, karataevClickHandler); var saveData:SaveData = SaveData.getInstance(); if (saveData.isNewGame){ _view.continueGame_bt.alpha = 0.5; _view.continueGame_bt.mouseEnabled = false; } else { _view.continueGame_bt.addEventListener(MouseEvent.CLICK, continueGameClickHandler); }; _view.clearProgress_bt.visible = false; _view.newGameConfirm.visible = false; _view.newGameConfirmYes_bt.addEventListener(MouseEvent.CLICK, newGameYesClickHandler); _view.newGameConfirmNo_bt.addEventListener(MouseEvent.CLICK, newGameNoClickHandler); _view.version_tf.text = AppProxy.GAME_VERSION; _view.editor_bt.visible = false; _view.version_tf.visible = false; _view.inner.visible = false; _view.anim.addEventListener(Event.ENTER_FRAME, animStartEfHandler); } private function newGameNoClickHandler(e:MouseEvent):void{ _view.newGameConfirm.visible = false; } private function closeMainMenu():void{ _view.inner.visible = false; _view.anim.visible = true; _view.anim.play(); _view.anim.addEventListener(Event.ENTER_FRAME, animEndEfHandler); } private function animStartEfHandler(e:Event):void{ if (_view.anim.currentFrame == 38){ _view.anim.stop(); _view.anim.removeEventListener(Event.ENTER_FRAME, animStartEfHandler); _view.inner.visible = true; }; } private function creditsClickHandler(e:MouseEvent):void{ var appMed:AppMediator = (facade.retrieveMediator(AppMediator.NAME) as AppMediator); var creditsView:CreditsView = new CreditsView(); appMed.getViewContainer().addChild(creditsView); var creditsMed:CreditsMediator = new CreditsMediator(creditsView); facade.registerMediator(creditsMed); } private function walkthroughClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest(AppProxy.WALKTHROUGH_URL)); } override public function listNotificationInterests():Array{ return ([]); } private function armorblogClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest(AppProxy.ARMORBLOG_URL), "_blank"); } private function karataevClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest("mailto:eugene.karataev@gmail.com"), "_blank"); } private function newGameYesClickHandler(e:MouseEvent):void{ SaveData.getInstance().clearProgress(); Fader.getInstance().fade(startNewGame); } private function clearProgressClickHandler(e:MouseEvent):void{ SaveData.getInstance().clearProgress(); } private function originalGameClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest(AppProxy.ORIGINAL_GAME_URL), "_blank"); } private function moreGamesClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest(AppProxy.MORE_GAMES_URL), "_blank"); } private function editorClickHandler(e:MouseEvent):void{ notesProxy.push(AppProxy.EDITOR_START); } private function startNewGame():void{ notesProxy.push(AppProxy.GAME_START); } private function closeHandler():void{ } private function twitterClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest(AppProxy.TWITTER_URL), "_blank"); } private function startGameClickHandler(e:MouseEvent):void{ var saveData:SaveData = SaveData.getInstance(); if (!saveData.isNewGame){ _view.newGameConfirm.visible = true; } else { closeMainMenu(); }; } private function continueGame():void{ notesProxy.push(AppProxy.GAME_START); } public function destroy():void{ _view.parent.removeChild(_view); facade.removeMediator(NAME); } private function continueGameClickHandler(e:MouseEvent):void{ closeMainMenu(); } private function musicbyClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest(AppProxy.MUSICBY_URL), "_blank"); } private function animEndEfHandler(e:Event):void{ if (_view.anim.currentFrame == _view.anim.totalFrames){ _view.anim.stop(); _view.anim.removeEventListener(Event.ENTER_FRAME, animEndEfHandler); Fader.getInstance().fade(startNewGame); }; } } }//package game.view
Section 217
//PreloaderKnight (game.PreloaderKnight) package game { import flash.events.*; import flash.display.*; public class PreloaderKnight { private var KnightAwakeClass:Class; private var skinSleep:MovieClip; private var skinAwake:MovieClip; private var isAwakened:Boolean; private var edge:Number; public function PreloaderKnight(edge:Number, skinSleep:MovieClip):void{ KnightAwakeClass = PreloaderKnight_KnightAwakeClass; super(); this.edge = edge; this.skinSleep = skinSleep; init(); } public function update(percent:Number):void{ if (!isAwakened){ if (edge > percent){ isAwakened = true; skinSleep.visible = false; skinSleep.stop(); skinAwake = new KnightAwakeClass(); skinSleep.parent.addChild(skinAwake); skinAwake.x = skinSleep.x; skinAwake.y = skinSleep.y; skinAwake.addEventListener(Event.ENTER_FRAME, efHandler); }; }; } private function init():void{ isAwakened = false; } private function efHandler(e:Event):void{ if (skinAwake.currentFrame == skinAwake.totalFrames){ skinAwake.stop(); skinAwake.removeEventListener(Event.ENTER_FRAME, efHandler); }; } } }//package game
Section 218
//PreloaderKnight_KnightAwakeClass (game.PreloaderKnight_KnightAwakeClass) package game { import mx.core.*; import flash.display.*; public class PreloaderKnight_KnightAwakeClass extends MovieClipAsset { public var armorHolder:DisplayObject; public var knight1:DisplayObject; public var knight2:DisplayObject; public var knight3:DisplayObject; public var back:DisplayObject; public var adsContainer:DisplayObject; public var armor_bt:DisplayObject; public var bar:DisplayObject; public var anim:DisplayObject; public var play_bt:DisplayObject; } }//package game
Section 219
//ByteArrayAsset (mx.core.ByteArrayAsset) package mx.core { import flash.utils.*; public class ByteArrayAsset extends ByteArray implements IFlexAsset { mx_internal static const VERSION:String = "3.0.0.0"; public function ByteArrayAsset(){ super(); } } }//package mx.core
Section 220
//EdgeMetrics (mx.core.EdgeMetrics) package mx.core { public class EdgeMetrics { public var top:Number; public var left:Number; public var bottom:Number; public var right:Number; mx_internal static const VERSION:String = "3.0.0.0"; public static const EMPTY:EdgeMetrics = new EdgeMetrics(0, 0, 0, 0); ; public function EdgeMetrics(left:Number=0, top:Number=0, right:Number=0, bottom:Number=0){ super(); this.left = left; this.top = top; this.right = right; this.bottom = bottom; } public function clone():EdgeMetrics{ return (new EdgeMetrics(left, top, right, bottom)); } } }//package mx.core
Section 221
//FlexMovieClip (mx.core.FlexMovieClip) package mx.core { import flash.display.*; import mx.utils.*; public class FlexMovieClip extends MovieClip { mx_internal static const VERSION:String = "3.0.0.0"; public function FlexMovieClip(){ super(); name = NameUtil.createUniqueName(this); //unresolved jump var _slot1 = e; } override public function toString():String{ return (NameUtil.displayObjectToString(this)); } } }//package mx.core
Section 222
//FlexSprite (mx.core.FlexSprite) package mx.core { import flash.display.*; import mx.utils.*; public class FlexSprite extends Sprite { mx_internal static const VERSION:String = "3.0.0.0"; public function FlexSprite(){ super(); name = NameUtil.createUniqueName(this); //unresolved jump var _slot1 = e; } override public function toString():String{ return (NameUtil.displayObjectToString(this)); } } }//package mx.core
Section 223
//IBorder (mx.core.IBorder) package mx.core { public interface IBorder { function get borderMetrics():EdgeMetrics; } }//package mx.core
Section 224
//IFlexAsset (mx.core.IFlexAsset) package mx.core { public interface IFlexAsset { } }//package mx.core
Section 225
//IFlexDisplayObject (mx.core.IFlexDisplayObject) package mx.core { import flash.events.*; import flash.display.*; import flash.geom.*; import flash.accessibility.*; public interface IFlexDisplayObject extends IBitmapDrawable, IEventDispatcher { function get visible():Boolean; function get rotation():Number; function localToGlobal(void:Point):Point; function get name():String; function set width(flash.display:Number):void; function get measuredHeight():Number; function get blendMode():String; function get scale9Grid():Rectangle; function set name(flash.display:String):void; function set scaleX(flash.display:Number):void; function set scaleY(flash.display:Number):void; function get measuredWidth():Number; function get accessibilityProperties():AccessibilityProperties; function set scrollRect(flash.display:Rectangle):void; function get cacheAsBitmap():Boolean; function globalToLocal(void:Point):Point; function get height():Number; function set blendMode(flash.display:String):void; function get parent():DisplayObjectContainer; function getBounds(String:DisplayObject):Rectangle; function get opaqueBackground():Object; function set scale9Grid(flash.display:Rectangle):void; function setActualSize(_arg1:Number, _arg2:Number):void; function set alpha(flash.display:Number):void; function set accessibilityProperties(flash.display:AccessibilityProperties):void; function get width():Number; function hitTestPoint(_arg1:Number, _arg2:Number, _arg3:Boolean=false):Boolean; function set cacheAsBitmap(flash.display:Boolean):void; function get scaleX():Number; function get scaleY():Number; function get scrollRect():Rectangle; function get mouseX():Number; function get mouseY():Number; function set height(flash.display:Number):void; function set mask(flash.display:DisplayObject):void; function getRect(String:DisplayObject):Rectangle; function get alpha():Number; function set transform(flash.display:Transform):void; function move(_arg1:Number, _arg2:Number):void; function get loaderInfo():LoaderInfo; function get root():DisplayObject; function hitTestObject(mx.core:IFlexDisplayObject/mx.core:IFlexDisplayObject:stage/get:DisplayObject):Boolean; function set opaqueBackground(flash.display:Object):void; function set visible(flash.display:Boolean):void; function get mask():DisplayObject; function set x(flash.display:Number):void; function set y(flash.display:Number):void; function get transform():Transform; function set filters(flash.display:Array):void; function get x():Number; function get y():Number; function get filters():Array; function set rotation(flash.display:Number):void; function get stage():Stage; } }//package mx.core
Section 226
//IRepeaterClient (mx.core.IRepeaterClient) package mx.core { public interface IRepeaterClient { function get instanceIndices():Array; function set instanceIndices(E:\dev\3.0.x\frameworks\projects\framework\src;mx\core;IRepeaterClient.as:Array):void; function get isDocument():Boolean; function set repeaters(E:\dev\3.0.x\frameworks\projects\framework\src;mx\core;IRepeaterClient.as:Array):void; function initializeRepeaterArrays(E:\dev\3.0.x\frameworks\projects\framework\src;mx\core;IRepeaterClient.as:IRepeaterClient):void; function get repeaters():Array; function set repeaterIndices(E:\dev\3.0.x\frameworks\projects\framework\src;mx\core;IRepeaterClient.as:Array):void; function get repeaterIndices():Array; } }//package mx.core
Section 227
//MovieClipAsset (mx.core.MovieClipAsset) package mx.core { public class MovieClipAsset extends FlexMovieClip implements IFlexAsset, IFlexDisplayObject, IBorder { private var _measuredHeight:Number; private var _measuredWidth:Number; mx_internal static const VERSION:String = "3.0.0.0"; public function MovieClipAsset(){ super(); _measuredWidth = width; _measuredHeight = height; } public function get measuredWidth():Number{ return (_measuredWidth); } public function get measuredHeight():Number{ return (_measuredHeight); } public function setActualSize(newWidth:Number, newHeight:Number):void{ width = newWidth; height = newHeight; } public function move(x:Number, y:Number):void{ this.x = x; this.y = y; } public function get borderMetrics():EdgeMetrics{ if (scale9Grid == null){ return (EdgeMetrics.EMPTY); }; return (new EdgeMetrics(scale9Grid.left, scale9Grid.top, Math.ceil((measuredWidth - scale9Grid.right)), Math.ceil((measuredHeight - scale9Grid.bottom)))); } } }//package mx.core
Section 228
//mx_internal (mx.core.mx_internal) package mx.core { public namespace mx_internal = "http://www.adobe.com/2006/flex/mx/internal"; }//package mx.core
Section 229
//SpriteAsset (mx.core.SpriteAsset) package mx.core { public class SpriteAsset extends FlexSprite implements IFlexAsset, IFlexDisplayObject, IBorder { private var _measuredHeight:Number; private var _measuredWidth:Number; mx_internal static const VERSION:String = "3.0.0.0"; public function SpriteAsset(){ super(); _measuredWidth = width; _measuredHeight = height; } public function get measuredWidth():Number{ return (_measuredWidth); } public function get measuredHeight():Number{ return (_measuredHeight); } public function setActualSize(newWidth:Number, newHeight:Number):void{ width = newWidth; height = newHeight; } public function move(x:Number, y:Number):void{ this.x = x; this.y = y; } public function get borderMetrics():EdgeMetrics{ if (scale9Grid == null){ return (EdgeMetrics.EMPTY); }; return (new EdgeMetrics(scale9Grid.left, scale9Grid.top, Math.ceil((measuredWidth - scale9Grid.right)), Math.ceil((measuredHeight - scale9Grid.bottom)))); } } }//package mx.core
Section 230
//NameUtil (mx.utils.NameUtil) package mx.utils { import mx.core.*; import flash.display.*; import flash.utils.*; public class NameUtil { mx_internal static const VERSION:String = "3.0.0.0"; private static var counter:int = 0; public function NameUtil(){ super(); } public static function displayObjectToString(displayObject:DisplayObject):String{ var result:String; var s:String; var indices:Array; var o:DisplayObject = displayObject; while (o != null) { if (((((o.parent) && (o.stage))) && ((o.parent == o.stage)))){ break; }; s = o.name; if ((o is IRepeaterClient)){ indices = IRepeaterClient(o).instanceIndices; if (indices){ s = (s + (("[" + indices.join("][")) + "]")); }; }; result = ((result == null)) ? s : ((s + ".") + result); o = o.parent; }; return (result); } public static function createUniqueName(object:Object):String{ if (!object){ return (null); }; var name:String = getQualifiedClassName(object); var index:int = name.indexOf("::"); if (index != -1){ name = name.substr((index + 2)); }; var charCode:int = name.charCodeAt((name.length - 1)); if ((((charCode >= 48)) && ((charCode <= 57)))){ name = (name + "_"); }; return ((name + counter++)); } } }//package mx.utils
Section 231
//Controller (org.puremvc.as3.core.controller.Controller) package org.puremvc.as3.core.controller { import org.puremvc.as3.interfaces.*; import org.puremvc.as3.core.view.*; import org.puremvc.as3.patterns.observer.*; public class Controller implements IController { protected const SINGLETON_MSG:String = "Controller Singleton already constructed!"; protected var commandMap:Array; protected var view:IView; protected static var instance:IController; public function Controller(){ super(); if (instance != null){ throw (Error(SINGLETON_MSG)); }; instance = this; commandMap = new Array(); initializeController(); } public function removeCommand(notificationName:String):void{ commandMap[notificationName] = null; } public function registerCommand(notificationName:String, commandClassRef:Class):void{ if (commandMap[notificationName] == null){ view.registerObserver(notificationName, new Observer(executeCommand, this)); }; commandMap[notificationName] = commandClassRef; } protected function initializeController():void{ view = View.getInstance(); } public function hasCommand(notificationName:String):Boolean{ return (!((commandMap[notificationName] == null))); } public function executeCommand(note:INotification):void{ var commandClassRef:Class = commandMap[note.getName()]; if (commandClassRef == null){ return; }; var commandInstance:ICommand = new (commandClassRef); commandInstance.execute(note); } public static function getInstance():IController{ if (instance == null){ instance = new (Controller); }; return (instance); } } }//package org.puremvc.as3.core.controller
Section 232
//Model (org.puremvc.as3.core.model.Model) package org.puremvc.as3.core.model { import org.puremvc.as3.interfaces.*; public class Model implements IModel { protected const SINGLETON_MSG:String = "Model Singleton already constructed!"; protected var proxyMap:Array; protected static var instance:IModel; public function Model(){ super(); if (instance != null){ throw (Error(SINGLETON_MSG)); }; instance = this; proxyMap = new Array(); initializeModel(); } protected function initializeModel():void{ } public function removeProxy(proxyName:String):IProxy{ var proxy:IProxy = (proxyMap[proxyName] as IProxy); proxyMap[proxyName] = null; return (proxy); } public function hasProxy(proxyName:String):Boolean{ return (!((proxyMap[proxyName] == null))); } public function retrieveProxy(proxyName:String):IProxy{ return (proxyMap[proxyName]); } public function registerProxy(proxy:IProxy):void{ proxyMap[proxy.getProxyName()] = proxy; } public static function getInstance():IModel{ if (instance == null){ instance = new (Model); }; return (instance); } } }//package org.puremvc.as3.core.model
Section 233
//View (org.puremvc.as3.core.view.View) package org.puremvc.as3.core.view { import org.puremvc.as3.interfaces.*; import org.puremvc.as3.patterns.observer.*; public class View implements IView { protected const SINGLETON_MSG:String = "View Singleton already constructed!"; protected var observerMap:Array; protected var mediatorMap:Array; protected static var instance:IView; public function View(){ super(); if (instance != null){ throw (Error(SINGLETON_MSG)); }; instance = this; mediatorMap = new Array(); observerMap = new Array(); initializeView(); } public function retrieveMediator(mediatorName:String):IMediator{ return (mediatorMap[mediatorName]); } public function hasMediator(mediatorName:String):Boolean{ return (!((mediatorMap[mediatorName] == null))); } public function notifyObservers(notification:INotification):void{ var observers:Array; var i:Number; var observer:IObserver; if (observerMap[notification.getName()] != null){ observers = (observerMap[notification.getName()] as Array); i = 0; while (i < observers.length) { observer = (observers[i] as IObserver); observer.notifyObserver(notification); i++; }; }; } protected function initializeView():void{ } public function registerMediator(mediator:IMediator):void{ var observer:Observer; var i:Number; mediatorMap[mediator.getMediatorName()] = mediator; var interests:Array = mediator.listNotificationInterests(); if (interests.length > 0){ observer = new Observer(mediator.handleNotification, mediator); i = 0; while (i < interests.length) { registerObserver(interests[i], observer); i++; }; }; mediator.onRegister(); } public function removeMediator(mediatorName:String):IMediator{ var notificationName:String; var mediator:IMediator; var observers:Array; var removalTargets:Array; var i:int; var target:int; for (notificationName in observerMap) { observers = observerMap[notificationName]; removalTargets = new Array(); i = 0; while (i < observers.length) { if (Observer(observers[i]).compareNotifyContext(retrieveMediator(mediatorName)) == true){ removalTargets.push(i); }; i++; }; while (removalTargets.length > 0) { target = removalTargets.pop(); observers.splice(target, 1); }; if (observers.length == 0){ delete observerMap[notificationName]; }; }; mediator = (mediatorMap[mediatorName] as IMediator); delete mediatorMap[mediatorName]; if (mediator){ mediator.onRemove(); }; return (mediator); } public function registerObserver(notificationName:String, observer:IObserver):void{ if (observerMap[notificationName] != null){ observerMap[notificationName].push(observer); } else { observerMap[notificationName] = [observer]; }; } public static function getInstance():IView{ if (instance == null){ instance = new (View); }; return (instance); } } }//package org.puremvc.as3.core.view
Section 234
//ICommand (org.puremvc.as3.interfaces.ICommand) package org.puremvc.as3.interfaces { public interface ICommand { function execute(:INotification):void; } }//package org.puremvc.as3.interfaces
Section 235
//IController (org.puremvc.as3.interfaces.IController) package org.puremvc.as3.interfaces { public interface IController { function registerCommand(_arg1:String, _arg2:Class):void; function hasCommand(org.puremvc.as3.interfaces:IController/org.puremvc.as3.interfaces:IController:registerCommand:String):Boolean; function executeCommand(:INotification):void; function removeCommand(:String):void; } }//package org.puremvc.as3.interfaces
Section 236
//IFacade (org.puremvc.as3.interfaces.IFacade) package org.puremvc.as3.interfaces { public interface IFacade extends INotifier { function removeCommand(:String):void; function registerCommand(_arg1:String, _arg2:Class):void; function removeProxy(E:\Flash\Classes\PureMVC_AS3_2_0_RC3;org\puremvc\as3\interfaces;IFacade.as:String):IProxy; function registerProxy(:IProxy):void; function hasMediator(org.puremvc.as3.interfaces:IFacade/org.puremvc.as3.interfaces:IFacade:registerProxy:String):Boolean; function retrieveMediator(org.puremvc.as3.interfaces:String):IMediator; function hasCommand(org.puremvc.as3.interfaces:IFacade/org.puremvc.as3.interfaces:IFacade:registerProxy:String):Boolean; function retrieveProxy(E:\Flash\Classes\PureMVC_AS3_2_0_RC3;org\puremvc\as3\interfaces;IFacade.as:String):IProxy; function hasProxy(org.puremvc.as3.interfaces:IFacade/org.puremvc.as3.interfaces:IFacade:registerProxy:String):Boolean; function registerMediator(:IMediator):void; function removeMediator(org.puremvc.as3.interfaces:String):IMediator; } }//package org.puremvc.as3.interfaces
Section 237
//IMediator (org.puremvc.as3.interfaces.IMediator) package org.puremvc.as3.interfaces { public interface IMediator { function listNotificationInterests():Array; function onRegister():void; function handleNotification(org.puremvc.as3.interfaces:IMediator/org.puremvc.as3.interfaces:IMediator:getMediatorName:INotification):void; function getMediatorName():String; function setViewComponent(org.puremvc.as3.interfaces:IMediator/org.puremvc.as3.interfaces:IMediator:getMediatorName:Object):void; function getViewComponent():Object; function onRemove():void; } }//package org.puremvc.as3.interfaces
Section 238
//IModel (org.puremvc.as3.interfaces.IModel) package org.puremvc.as3.interfaces { public interface IModel { function removeProxy(E:\Flash\Classes\PureMVC_AS3_2_0_RC3;org\puremvc\as3\interfaces;IModel.as:String):IProxy; function retrieveProxy(E:\Flash\Classes\PureMVC_AS3_2_0_RC3;org\puremvc\as3\interfaces;IModel.as:String):IProxy; function registerProxy(:IProxy):void; function hasProxy(org.puremvc.as3.interfaces:IModel/org.puremvc.as3.interfaces:IModel:registerProxy:String):Boolean; } }//package org.puremvc.as3.interfaces
Section 239
//INotification (org.puremvc.as3.interfaces.INotification) package org.puremvc.as3.interfaces { public interface INotification { function getType():String; function getName():String; function toString():String; function setBody(E:\Flash\Classes\PureMVC_AS3_2_0_RC3;org\puremvc\as3\interfaces;INotification.as:Object):void; function getBody():Object; function setType(E:\Flash\Classes\PureMVC_AS3_2_0_RC3;org\puremvc\as3\interfaces;INotification.as:String):void; } }//package org.puremvc.as3.interfaces
Section 240
//INotifier (org.puremvc.as3.interfaces.INotifier) package org.puremvc.as3.interfaces { public interface INotifier { function sendNotification(_arg1:String, _arg2:Object=null, _arg3:String=null):void; } }//package org.puremvc.as3.interfaces
Section 241
//IObserver (org.puremvc.as3.interfaces.IObserver) package org.puremvc.as3.interfaces { public interface IObserver { function compareNotifyContext(void:Object):Boolean; function setNotifyContext(:Object):void; function setNotifyMethod(:Function):void; function notifyObserver(:INotification):void; } }//package org.puremvc.as3.interfaces
Section 242
//IProxy (org.puremvc.as3.interfaces.IProxy) package org.puremvc.as3.interfaces { public interface IProxy { function getData():Object; function getProxyName():String; function setData(E:\Flash\Classes\PureMVC_AS3_2_0_RC3;org\puremvc\as3\interfaces;IProxy.as:Object):void; } }//package org.puremvc.as3.interfaces
Section 243
//IView (org.puremvc.as3.interfaces.IView) package org.puremvc.as3.interfaces { public interface IView { function notifyObservers(:INotification):void; function registerMediator(:IMediator):void; function removeMediator(org.puremvc.as3.interfaces:IView/org.puremvc.as3.interfaces:IView:registerObserver:String):IMediator; function registerObserver(_arg1:String, _arg2:IObserver):void; function hasMediator(void:String):Boolean; function retrieveMediator(org.puremvc.as3.interfaces:IView/org.puremvc.as3.interfaces:IView:registerObserver:String):IMediator; } }//package org.puremvc.as3.interfaces
Section 244
//SimpleCommand (org.puremvc.as3.patterns.command.SimpleCommand) package org.puremvc.as3.patterns.command { import org.puremvc.as3.interfaces.*; import org.puremvc.as3.patterns.observer.*; public class SimpleCommand extends Notifier implements ICommand, INotifier { public function SimpleCommand(){ super(); } public function execute(notification:INotification):void{ } } }//package org.puremvc.as3.patterns.command
Section 245
//Facade (org.puremvc.as3.patterns.facade.Facade) package org.puremvc.as3.patterns.facade { import org.puremvc.as3.interfaces.*; import org.puremvc.as3.core.view.*; import org.puremvc.as3.core.controller.*; import org.puremvc.as3.core.model.*; import org.puremvc.as3.patterns.observer.*; public class Facade implements IFacade { protected const SINGLETON_MSG:String = "Facade Singleton already constructed!"; protected var controller:IController; protected var view:IView; protected var model:IModel; protected static var instance:IFacade; public function Facade(){ super(); if (instance != null){ throw (Error(SINGLETON_MSG)); }; instance = this; initializeFacade(); } public function removeProxy(proxyName:String):IProxy{ var proxy:IProxy; if (model != null){ proxy = model.removeProxy(proxyName); }; return (proxy); } public function registerProxy(proxy:IProxy):void{ model.registerProxy(proxy); } protected function initializeController():void{ if (controller != null){ return; }; controller = Controller.getInstance(); } protected function initializeFacade():void{ initializeModel(); initializeController(); initializeView(); } public function retrieveProxy(proxyName:String):IProxy{ return (model.retrieveProxy(proxyName)); } public function sendNotification(notificationName:String, body:Object=null, type:String=null):void{ notifyObservers(new Notification(notificationName, body, type)); } public function notifyObservers(notification:INotification):void{ if (view != null){ view.notifyObservers(notification); }; } protected function initializeView():void{ if (view != null){ return; }; view = View.getInstance(); } public function retrieveMediator(mediatorName:String):IMediator{ return ((view.retrieveMediator(mediatorName) as IMediator)); } public function removeMediator(mediatorName:String):IMediator{ var mediator:IMediator; if (view != null){ mediator = view.removeMediator(mediatorName); }; return (mediator); } public function hasCommand(notificationName:String):Boolean{ return (controller.hasCommand(notificationName)); } public function removeCommand(notificationName:String):void{ controller.removeCommand(notificationName); } public function registerCommand(notificationName:String, commandClassRef:Class):void{ controller.registerCommand(notificationName, commandClassRef); } public function hasMediator(mediatorName:String):Boolean{ return (view.hasMediator(mediatorName)); } public function registerMediator(mediator:IMediator):void{ if (view != null){ view.registerMediator(mediator); }; } protected function initializeModel():void{ if (model != null){ return; }; model = Model.getInstance(); } public function hasProxy(proxyName:String):Boolean{ return (model.hasProxy(proxyName)); } public static function getInstance():IFacade{ if (instance == null){ instance = new (Facade); }; return (instance); } } }//package org.puremvc.as3.patterns.facade
Section 246
//Mediator (org.puremvc.as3.patterns.mediator.Mediator) package org.puremvc.as3.patterns.mediator { import org.puremvc.as3.interfaces.*; import org.puremvc.as3.patterns.observer.*; public class Mediator extends Notifier implements IMediator, INotifier { protected var viewComponent:Object; protected var mediatorName:String; public static const NAME:String = "Mediator"; public function Mediator(mediatorName:String=null, viewComponent:Object=null){ super(); this.mediatorName = ((mediatorName)!=null) ? mediatorName : NAME; this.viewComponent = viewComponent; } public function listNotificationInterests():Array{ return ([]); } public function onRegister():void{ } public function onRemove():void{ } public function getViewComponent():Object{ return (viewComponent); } public function handleNotification(notification:INotification):void{ } public function getMediatorName():String{ return (mediatorName); } public function setViewComponent(viewComponent:Object):void{ this.viewComponent = viewComponent; } } }//package org.puremvc.as3.patterns.mediator
Section 247
//Notification (org.puremvc.as3.patterns.observer.Notification) package org.puremvc.as3.patterns.observer { import org.puremvc.as3.interfaces.*; public class Notification implements INotification { private var body:Object; private var name:String; private var type:String; public function Notification(name:String, body:Object=null, type:String=null){ super(); this.name = name; this.body = body; this.type = type; } public function setBody(body:Object):void{ this.body = body; } public function getName():String{ return (name); } public function toString():String{ var msg:String = ("Notification Name: " + getName()); msg = (msg + ("\nBody:" + ((body)==null) ? "null" : body.toString())); msg = (msg + ("\nType:" + ((type)==null) ? "null" : type)); return (msg); } public function getType():String{ return (type); } public function setType(type:String):void{ this.type = type; } public function getBody():Object{ return (body); } } }//package org.puremvc.as3.patterns.observer
Section 248
//Notifier (org.puremvc.as3.patterns.observer.Notifier) package org.puremvc.as3.patterns.observer { import org.puremvc.as3.interfaces.*; import org.puremvc.as3.patterns.facade.*; public class Notifier implements INotifier { protected var facade:IFacade; public function Notifier(){ facade = Facade.getInstance(); super(); } public function sendNotification(notificationName:String, body:Object=null, type:String=null):void{ facade.sendNotification(notificationName, body, type); } } }//package org.puremvc.as3.patterns.observer
Section 249
//Observer (org.puremvc.as3.patterns.observer.Observer) package org.puremvc.as3.patterns.observer { import org.puremvc.as3.interfaces.*; public class Observer implements IObserver { private var notify:Function; private var context:Object; public function Observer(notifyMethod:Function, notifyContext:Object){ super(); setNotifyMethod(notifyMethod); setNotifyContext(notifyContext); } private function getNotifyMethod():Function{ return (notify); } public function compareNotifyContext(object:Object):Boolean{ return ((object === this.context)); } public function setNotifyContext(notifyContext:Object):void{ context = notifyContext; } private function getNotifyContext():Object{ return (context); } public function setNotifyMethod(notifyMethod:Function):void{ notify = notifyMethod; } public function notifyObserver(notification:INotification):void{ this.getNotifyMethod().apply(this.getNotifyContext(), [notification]); } } }//package org.puremvc.as3.patterns.observer
Section 250
//Proxy (org.puremvc.as3.patterns.proxy.Proxy) package org.puremvc.as3.patterns.proxy { import org.puremvc.as3.interfaces.*; import org.puremvc.as3.patterns.observer.*; public class Proxy extends Notifier implements IProxy, INotifier { protected var proxyName:String; protected var data:Object; public static var NAME:String = "Proxy"; public function Proxy(proxyName:String=null, data:Object=null){ super(); this.proxyName = ((proxyName)!=null) ? proxyName : NAME; if (data != null){ setData(data); }; } public function getData():Object{ return (data); } public function getProxyName():String{ return (proxyName); } public function setData(data:Object):void{ this.data = data; } } }//package org.puremvc.as3.patterns.proxy
Section 251
//Config (SWFStats.Config) package SWFStats { import flash.utils.*; public class Config { public static const LevelLabels:Dictionary = new Dictionary(); public static const GUID:String = "635c4a6e-53a7-4dec-94f4-7b690cf7893c"; public static const LevelCounterMetrics:Dictionary = new Dictionary(); public static const ScoreTables:Dictionary = new Dictionary(); public static const LevelRangedMetrics:Dictionary = new Dictionary(); public static const CustomMetrics:Dictionary = new Dictionary(); public static const SWFID:int = 174; public function Config(){ super(); } } }//package SWFStats
Section 252
//Tracker (SWFStats.Tracker) package SWFStats { import flash.events.*; import flash.utils.*; import flash.net.*; import flash.system.*; import flash.external.*; public class Tracker { public static const Random:Number = Math.random(); private static const Ping:Timer = new Timer(30000); public static var Initialised:Boolean = false; public static var SourceUrl:String; public static var DebugMode:Boolean = true; public function Tracker(){ super(); } public static function LogView():void{ if (SourceUrl == null){ return; }; if (DebugMode){ trace("SWFStats.Tracker.LogView"); }; var sendaction:URLLoader = new URLLoader(); sendaction.addEventListener(IOErrorEvent.IO_ERROR, ErrorHandler); sendaction.load(new URLRequest(((((((("http://tracker.swfstats.com/Games/View.html?guid=" + Config.GUID) + "&swfid=") + Config.SWFID) + "&url=") + SourceUrl) + "&") + Random))); Ping.addEventListener(TimerEvent.TIMER, PingServer); Ping.start(); } public static function ErrorHandler(e:IOErrorEvent):void{ if (DebugMode){ trace("** ERROR COMPLETING URL REQUEST TO SWFSTATS **"); }; SourceUrl = null; } private static function PingServer(e:Event):void{ if (SourceUrl == null){ return; }; if (DebugMode){ trace("SWFStats.Tracker.PingServer"); }; var sendaction:URLLoader = new URLLoader(); sendaction.addEventListener(IOErrorEvent.IO_ERROR, ErrorHandler); sendaction.load(new URLRequest(((((((("http://tracker.swfstats.com/Games/Ping.html?guid=" + Config.GUID) + "&swfid=") + Config.SWFID) + "&url=") + SourceUrl) + "&") + Random))); } public static function Initialise(defaulturl:String, turnoffdebugmode:Boolean=false):void{ var defaulturl = defaulturl; var turnoffdebugmode = turnoffdebugmode; DebugMode = (turnoffdebugmode) ? false : (Security.sandboxType == "localTrusted"); if (DebugMode){ trace("SWFStats.Tracker.Initialise"); }; if ((((Config.SWFID == 0)) || ((Config.GUID == "")))){ if (DebugMode){ trace("** ERROR YOU MUST COPY YOUR DATA INTO CONFIG.AS **"); trace(" You have not copied your settings into SWFStats\\Config.as."); trace(" Solution:"); trace(" 1) Go to http://my.swfstats.com/"); trace(" 2) Select your game and go into the 'API Code' section"); trace(" 3) Copy your data into SWFStats\\Config.as"); }; return; }; Initialised = true; if (((!((defaulturl.indexOf("http://") == 0))) && (!((Security.sandboxType == "localTrusted"))))){ return; }; SourceUrl = GetUrl(defaulturl); Security.loadPolicyFile("http://tracker.swfstats.com/crossdomain.xml"); Security.loadPolicyFile("http://utils.swfstats.com/crossdomain.xml"); //unresolved jump var _slot1 = s; SourceUrl = null; return; if (DebugMode){ trace("** ERROR COULD NOT LOAD SWFSTATS POLICY FILE **"); }; } public static function LogPlay():void{ if (SourceUrl == null){ return; }; if (DebugMode){ trace("SWFStats.Tracker.LogPlay"); }; var sendaction:URLLoader = new URLLoader(); sendaction.addEventListener(IOErrorEvent.IO_ERROR, ErrorHandler); sendaction.load(new URLRequest(((((((("http://tracker.swfstats.com/Games/Play.html?guid=" + Config.GUID) + "&swfid=") + Config.SWFID) + "&url=") + SourceUrl) + "&") + Random))); } private static function GetUrl(defaulturl:String):String{ var url:String; var defaulturl = defaulturl; url = String(ExternalInterface.call("window.location.href.toString")); //unresolved jump var _slot1 = s; url = ((defaulturl)!=null) ? defaulturl : ""; return (((url)!="null") ? url : ""); } } }//package SWFStats
Section 253
//ApplicationFacade (ApplicationFacade) package { import org.puremvc.as3.interfaces.*; import flash.display.*; import org.puremvc.as3.patterns.facade.*; import org.puremvc.as3.patterns.observer.*; import game.controller.*; public class ApplicationFacade extends Facade implements IFacade { public var viewContainer:Sprite; public static const STARTUP:String = "Startup"; public function ApplicationFacade(){ super(); } override protected function initializeController():void{ super.initializeController(); registerCommand(STARTUP, StartupCommand); } public function startup(startupObj:Object):void{ var container:Sprite = startupObj.container; viewContainer = new Sprite(); container.addChild(viewContainer); notifyObservers(new Notification(STARTUP, startupObj)); } public static function getInstance():ApplicationFacade{ if (instance == null){ instance = new (ApplicationFacade); }; return ((instance as ApplicationFacade)); } } }//package
Section 254
//Preloader (Preloader) package { import flash.events.*; import flash.display.*; import caurina.transitions.*; import flash.text.*; import SWFStats.*; import game.*; import flash.utils.*; import flash.ui.*; import flash.net.*; public class Preloader extends MovieClip { private var PreloaderClass:Class; private var knights:Array; private var armorHolder:Sprite; private var isLoaded:Boolean; private var anim:MovieClip; private var armor_bt:SimpleButton; private var bar:Sprite; private var _containerSprite:Sprite; private var _percentLoaded:Number; private var _infoField:TextField; private var back:Sprite; private var adsContainer:MovieClip; private var play_bt:SimpleButton; public static var DOMAIN_LOCAL:Boolean = false; public static var DOMAIN_ARMORGAMES:Boolean = false; public static var DOMAIN_OLOLOGAMES:Boolean = false; public static var DOMAIN_KONG:Boolean = false; public static var kongregate; public function Preloader(){ PreloaderClass = Preloader_PreloaderClass; super(); _containerSprite = (new PreloaderClass() as Sprite); addChild(_containerSprite); adsContainer = (_containerSprite.getChildByName("adsContainer") as MovieClip); back = (_containerSprite.getChildByName("back") as Sprite); anim = (_containerSprite.getChildByName("anim") as MovieClip); armorHolder = (anim.getChildByName("armorHolder") as Sprite); armor_bt = (armorHolder.getChildByName("armor_bt") as SimpleButton); play_bt = (anim.getChildByName("play_bt") as SimpleButton); bar = (anim.getChildByName("bar") as Sprite); var knight1:MovieClip = (anim.getChildByName("knight1") as MovieClip); var knight2:MovieClip = (anim.getChildByName("knight2") as MovieClip); var knight3:MovieClip = (anim.getChildByName("knight3") as MovieClip); knights = [new PreloaderKnight(0.86, knight1), new PreloaderKnight(0.44, knight2), new PreloaderKnight(0.03, knight3)]; var myContextMenu:ContextMenu = new ContextMenu(); myContextMenu.hideBuiltInItems(); contextMenu = myContextMenu; checkDomain(); Tracker.Initialise(loaderInfo.loaderURL); anim.stop(); play_bt.visible = false; isLoaded = false; loaderInfo.addEventListener(ProgressEvent.PROGRESS, onRootLoaderProgress); loaderInfo.addEventListener(Event.COMPLETE, onRootLoaderComplete); play_bt.addEventListener(MouseEvent.CLICK, playClickHandler); armor_bt.addEventListener(MouseEvent.CLICK, armorClickHandler); anim.addEventListener(Event.ENTER_FRAME, animEfHandler); if (DOMAIN_KONG){ initKongAPI(); }; } private function armorClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest("http://armorgames.com"), "_blank"); } private function adsCompleteHandler():void{ trace("ADS COMPLETE"); onRootLoaderComplete(null); } private function initKongAPI():void{ var paramObj:Object = LoaderInfo(root.loaderInfo).parameters; var api_url:String = ((paramObj.api_path) || ("http://www.kongregate.com/flash/API_AS3_Local.swf")); trace(("API path: " + api_url)); var request:URLRequest = new URLRequest(api_url); var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, kongAPILoadComplete); loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, kongAPIErrorHandler); loader.load(request); this.addChild(loader); } private function animEfHandler(e:Event):void{ var knight:PreloaderKnight; if (anim.currentFrame == anim.totalFrames){ anim.stop(); anim.removeEventListener(Event.ENTER_FRAME, animEfHandler); play_bt.visible = true; }; var i:int; while (i < knights.length) { knight = knights[i]; knight.update(bar.scaleX); i++; }; } private function tweenComplete():void{ trace("TWEEN COMPLETE!", isLoaded); if (isLoaded){ anim.gotoAndPlay(50); }; } private function onRootLoaderProgress(event:ProgressEvent):void{ var bytesLoaded:Number = event.target.bytesLoaded; var bytesTotal:Number = event.target.bytesTotal; _percentLoaded = (bytesLoaded / bytesTotal); var barWidth:Number = 478; var newScaleX:Number = (1 - _percentLoaded); var time:Number = ((bar.scaleX - newScaleX) * 3); if (time > 0){ Tweener.removeAllTweens(); trace("tween", _percentLoaded, time); Tweener.addTween(bar, {time:time, scaleX:newScaleX, transition:"linear", onComplete:tweenComplete}); }; } private function kongAPILoadComplete(event:Event):void{ kongregate = event.target.content; kongregate.services.connect(); trace(("\n" + kongregate.services)); trace(("\n" + kongregate.user)); trace(("\n" + kongregate.scores)); trace(("\n" + kongregate.stats)); } private function checkDomain():void{ var url:String = stage.loaderInfo.url; var urlStart:Number = (url.indexOf("://") + 3); var urlEnd:Number = url.indexOf("/", urlStart); var domain:String = url.substring(urlStart, urlEnd); var LastDot:Number = (domain.lastIndexOf(".") - 1); var domEnd:Number = (domain.lastIndexOf(".", LastDot) + 1); domain = domain.substring(domEnd, domain.length); if ((((domain == "")) || ((domain == "localhost")))){ DOMAIN_LOCAL = true; }; if ((((domain == "isfland.com")) || ((domain == "olologames.com")))){ DOMAIN_OLOLOGAMES = true; }; if (domain == "armorgames.com"){ DOMAIN_ARMORGAMES = true; }; DOMAIN_KONG = ((domain == "kongregate.com")) ? true : false; } private function backClickHandler(e:MouseEvent):void{ navigateToURL(new URLRequest("http://olologames.com")); } private function onRootLoaderComplete(event:Event):void{ isLoaded = true; trace("LOADED!!!"); loaderInfo.removeEventListener(ProgressEvent.PROGRESS, onRootLoaderProgress); loaderInfo.removeEventListener(Event.COMPLETE, onRootLoaderComplete); } private function playClickHandler(e:MouseEvent):void{ var app:Object; removeChild(_containerSprite); loaderInfo.removeEventListener(ProgressEvent.PROGRESS, onRootLoaderProgress); loaderInfo.removeEventListener(Event.COMPLETE, onRootLoaderComplete); nextFrame(); var mainClass:Class = Class(getDefinitionByName("WakeTheRoyalty")); if (mainClass){ app = new (mainClass); addChild((app as DisplayObject)); }; } private function kongAPIErrorHandler(e:IOErrorEvent):void{ trace("ZZ", e.text); } } }//package
Section 255
//Preloader_PreloaderClass (Preloader_PreloaderClass) package { import mx.core.*; import flash.display.*; public class Preloader_PreloaderClass extends SpriteAsset { public var armorHolder:DisplayObject; public var knight1:DisplayObject; public var knight2:DisplayObject; public var knight3:DisplayObject; public var back:DisplayObject; public var adsContainer:DisplayObject; public var armor_bt:DisplayObject; public var bar:DisplayObject; public var anim:DisplayObject; public var play_bt:DisplayObject; } }//package
Section 256
//WakeTheRoyalty (WakeTheRoyalty) package { import flash.events.*; import flash.display.*; public class WakeTheRoyalty extends Sprite { public function WakeTheRoyalty(){ super(); addEventListener(Event.ADDED_TO_STAGE, addedHandler); } private function addedHandler(e:Event):void{ ApplicationFacade.getInstance().startup({container:this}); } } }//package

Library Items

Symbol 1 GraphicUsed by:2
Symbol 2 MovieClipUses:1Used by:3
Symbol 3 MovieClipUses:2Used by:36
Symbol 4 GraphicUsed by:5
Symbol 5 MovieClipUses:4Used by:34
Symbol 6 GraphicUsed by:7
Symbol 7 ButtonUses:6Used by:16 32 37
Symbol 8 GraphicUsed by:9
Symbol 9 ButtonUses:8Used by:16 32 37
Symbol 10 ShapeTweeningUsed by:13
Symbol 11 ShapeTweeningUsed by:13
Symbol 12 GraphicUsed by:13
Symbol 13 MovieClipUses:10 11 12Used by:16
Symbol 14 GraphicUsed by:15
Symbol 15 MovieClipUses:14Used by:16
Symbol 16 MovieClipUses:7 9 13 15Used by:34
Symbol 17 GraphicUsed by:34
Symbol 18 GraphicUsed by:22
Symbol 19 GraphicUsed by:22
Symbol 20 GraphicUsed by:22
Symbol 21 GraphicUsed by:22
Symbol 22 ButtonUses:18 19 20 21Used by:34
Symbol 23 GraphicUsed by:28
Symbol 24 GraphicUsed by:28
Symbol 25 GraphicUsed by:28
Symbol 26 GraphicUsed by:28
Symbol 27 GraphicUsed by:28
Symbol 28 ButtonUses:23 24 25 26 27Used by:29
Symbol 29 MovieClipUses:28Used by:34
Symbol 30 GraphicUsed by:31
Symbol 31 ButtonUses:30Used by:32 37
Symbol 32 MovieClipUses:7 9 31Used by:34
Symbol 33 GraphicUsed by:34
Symbol 34 MovieClipUses:5 16 17 22 29 32 33Used by:36
Symbol 35 MovieClipUsed by:36
Symbol 36 MovieClip {Preloader_PreloaderClass} [PreloaderWindow]Uses:3 34 35
Symbol 37 MovieClip {game.PreloaderKnight_KnightAwakeClass} [KnightAwakeAsset]Uses:7 9 31
Symbol 38 BinaryData {editor.model.EditorAssets_Assets} [editor.model.EditorAssets_Assets]
Symbol 39 BinaryData {core.CoreAssets_Assets} [core.CoreAssets_Assets]
Symbol 40 BinaryData {game.model.GameAssets_Assets} [game.model.GameAssets_Assets]

Instance Names

"armor_bt"Symbol 29 MovieClip Frame 1Symbol 28 Button
"bar"Symbol 34 MovieClip Frame 1Symbol 5 MovieClip
"knight3"Symbol 34 MovieClip Frame 1Symbol 16 MovieClip
"knight1"Symbol 34 MovieClip Frame 1Symbol 16 MovieClip
"knight2"Symbol 34 MovieClip Frame 1Symbol 16 MovieClip
"play_bt"Symbol 34 MovieClip Frame 1Symbol 22 Button
"armorHolder"Symbol 34 MovieClip Frame 1Symbol 29 MovieClip
"back"Symbol 36 MovieClip {Preloader_PreloaderClass} [PreloaderWindow] Frame 1Symbol 3 MovieClip
"anim"Symbol 36 MovieClip {Preloader_PreloaderClass} [PreloaderWindow] Frame 1Symbol 34 MovieClip
"adsContainer"Symbol 36 MovieClip {Preloader_PreloaderClass} [PreloaderWindow] Frame 1Symbol 35 MovieClip

Special Tags

FileAttributes (69)Timeline Frame 1Access network only, Metadata present, AS3.
SWFMetaData (77)Timeline Frame 1457 bytes "<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'><rdf:Description rdf:about='' xmlns ..."
ScriptLimits (65)Timeline Frame 1MaxRecursionDepth: 1000, ScriptTimeout: 60 seconds
ExportAssets (56)Timeline Frame 1Symbol 36 as "PreloaderWindow"
ExportAssets (56)Timeline Frame 1Symbol 37 as "KnightAwakeAsset"
ExportAssets (56)Timeline Frame 2Symbol 38 as "editor.model.EditorAssets_Assets"
ExportAssets (56)Timeline Frame 2Symbol 39 as "core.CoreAssets_Assets"
ExportAssets (56)Timeline Frame 2Symbol 40 as "game.model.GameAssets_Assets"
EnableDebugger2 (64)Timeline Frame 131 bytes "u.$1$IJ$ZqB7/H2rxse84DtcZGv2I1."
DebugMX1 (63)Timeline Frame 1
SerialNumber (41)Timeline Frame 1

Labels

"Preloader"Frame 1
"WakeTheRoyalty"Frame 2




http://swfchan.com/19/93153/info.shtml
Created: 27/3 -2019 02:03:55 Last modified: 27/3 -2019 02:03:55 Server time: 22/12 -2024 08:37:00