SceneObject.cc 133 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _SCENE_OBJECT_H_
  23. #include "2d/sceneobject/SceneObject.h"
  24. #endif
  25. #ifndef _DGL_H_
  26. #include "graphics/dgl.h"
  27. #endif
  28. #ifndef _COLOR_H_
  29. #include "graphics/color.h"
  30. #endif
  31. #ifndef _BITSTREAM_H_
  32. #include "io/bitStream.h"
  33. #endif
  34. #ifndef _MMATHFN_H_
  35. #include "math/mMathFn.h"
  36. #endif
  37. #ifndef _CONSOLETYPES_H_
  38. #include "console/consoleTypes.h"
  39. #endif
  40. #ifndef _SIMBASE_H_
  41. #include "sim/simBase.h"
  42. #endif
  43. #ifndef _BEHAVIORTEMPLATE_H_
  44. #include "component/behaviors/behaviorTemplate.h"
  45. #endif
  46. #ifndef _SCENE_OBJECT_MOVE_TO_EVENT_H_
  47. #include "2d/sceneobject/SceneObjectMoveToEvent.h"
  48. #endif
  49. #ifndef _SCENE_OBJECT_ROTATE_TO_EVENT_H_
  50. #include "2d/sceneobject/SceneObjectRotateToEvent.h"
  51. #endif
  52. #ifndef _RENDER_PROXY_H_
  53. #include "2d/core/RenderProxy.h"
  54. #endif
  55. #ifndef _STRINGUNIT_H_
  56. #include "string/stringUnit.h"
  57. #endif
  58. // Script bindings.
  59. #include "SceneObject_ScriptBinding.h"
  60. // Debug Profiling.
  61. #include "debug/profiler.h"
  62. //-----------------------------------------------------------------------------
  63. IMPLEMENT_CONOBJECT(SceneObject);
  64. //-----------------------------------------------------------------------------
  65. // Scene-Object counter.
  66. static U32 sGlobalSceneObjectCount = 0;
  67. static U32 sSceneObjectMasterSerialId = 0;
  68. // Collision shape property names.
  69. static bool collisionShapePropertiesInitialized = false;
  70. static StringTableEntry shapeCustomNodeName;
  71. static StringTableEntry shapeDensityName;
  72. static StringTableEntry shapeFrictionName;
  73. static StringTableEntry shapeRestitutionName;
  74. static StringTableEntry shapeSensorName;
  75. static StringTableEntry circleTypeName;
  76. static StringTableEntry circleRadiusName;
  77. static StringTableEntry circleOffsetName;
  78. static StringTableEntry polygonTypeName;
  79. static StringTableEntry polygonPointName;
  80. static StringTableEntry chainTypeName;
  81. static StringTableEntry chainPointName;
  82. static StringTableEntry chainAdjacentStartName;
  83. static StringTableEntry chainAdjacentEndName;
  84. static StringTableEntry edgeTypeName;
  85. static StringTableEntry edgeStartName;
  86. static StringTableEntry edgeEndName;
  87. static StringTableEntry edgeAdjacentStartName;
  88. static StringTableEntry edgeAdjacentEndName;
  89. //------------------------------------------------------------------------------
  90. // Important: If these defaults are changed then modify the associated "write" field protected methods to ensure
  91. // that the associated field is persisted if not the default.
  92. SceneObject::SceneObject() :
  93. /// Scene.
  94. mpScene(NULL),
  95. mpTargetScene(NULL),
  96. /// Lifetime.
  97. mLifetime(0.0f),
  98. mLifetimeActive(false),
  99. /// Layers.
  100. mSceneLayer(0),
  101. mSceneLayerMask(BIT(mSceneLayer)),
  102. mSceneLayerDepth(0.0f),
  103. /// Scene groups.
  104. mSceneGroup(0),
  105. mSceneGroupMask(BIT(mSceneGroup)),
  106. /// Area.
  107. mWorldProxyId(-1),
  108. /// Position / Angle.
  109. mPreTickPosition( 0.0f, 0.0f ),
  110. mPreTickAngle( 0.0f ),
  111. mRenderPosition( 0.0f, 0.0f ),
  112. mRenderAngle( 0.0f ),
  113. mSpatialDirty( true ),
  114. /// Body.
  115. mpBody(NULL),
  116. mWorldQueryKey(0),
  117. /// Collision control.
  118. mCollisionLayerMask(MASK_ALL),
  119. mCollisionGroupMask(MASK_ALL),
  120. mCollisionSuppress(false),
  121. mGatherContacts(false),
  122. mpCurrentContacts(NULL),
  123. /// Render visibility.
  124. mVisible(true),
  125. /// Render blending.
  126. mBlendMode(true),
  127. mSrcBlendFactor(GL_SRC_ALPHA),
  128. mDstBlendFactor(GL_ONE_MINUS_SRC_ALPHA),
  129. mBlendColor(ColorF(1.0f,1.0f,1.0f,1.0f)),
  130. mAlphaTest(-1.0f),
  131. /// Render sorting.
  132. mSortPoint(0.0f,0.0f),
  133. /// Input events.
  134. mUseInputEvents(false),
  135. /// Script callbacks.
  136. mUpdateCallback(false),
  137. mCollisionCallback(false),
  138. mSleepingCallback(false),
  139. /// Debug mode.
  140. mDebugMask(0X00000000),
  141. /// Camera mounting.
  142. mpAttachedCamera(NULL),
  143. /// GUI attachment.
  144. mAttachedGuiSizeControl(false),
  145. mpAttachedGui(NULL),
  146. mpAttachedGuiSceneWindow(NULL),
  147. /// Pathing.
  148. mAttachedToPath(NULL),
  149. /// Safe deletion.
  150. mBeingSafeDeleted(false),
  151. mSafeDeleteReady(true),
  152. /// Miscellaneous.
  153. mBatchIsolated(false),
  154. mSerialiseKey(0),
  155. mEditorTickAllowed(true),
  156. mPickingAllowed(true),
  157. mAlwaysInScope(false),
  158. mMoveToEventId(0),
  159. mRotateToEventId(0),
  160. mSerialId(0),
  161. mRenderGroup( StringTable->EmptyString )
  162. {
  163. // Initialize collision shape field names.
  164. if ( !collisionShapePropertiesInitialized )
  165. {
  166. shapeCustomNodeName = StringTable->insert( "CollisionShapes" );
  167. shapeDensityName = StringTable->insert( "Density" );
  168. shapeFrictionName = StringTable->insert( "Friction" );
  169. shapeRestitutionName = StringTable->insert( "Restitution" );
  170. shapeSensorName = StringTable->insert( "Sensor" );
  171. circleTypeName = StringTable->insert( "Circle" );
  172. circleRadiusName = StringTable->insert( "Radius" );
  173. circleOffsetName = StringTable->insert( "Offset" );
  174. polygonTypeName = StringTable->insert( "Polygon" );
  175. polygonPointName = StringTable->insert( "Point" );
  176. chainTypeName = StringTable->insert( "Chain" );
  177. chainPointName = polygonPointName;
  178. chainAdjacentStartName = StringTable->insert( "AdjacentStartPoint" );
  179. chainAdjacentEndName = StringTable->insert( "AdjacentEndPoint" );
  180. edgeTypeName = StringTable->insert( "Edge" );
  181. edgeStartName = StringTable->insert( "Point0" );
  182. edgeEndName = StringTable->insert( "Point1" );
  183. edgeAdjacentStartName = chainAdjacentStartName;
  184. edgeAdjacentEndName = chainAdjacentEndName;
  185. // Flag as initialized.
  186. collisionShapePropertiesInitialized = true;
  187. }
  188. // Set Vector Associations.
  189. VECTOR_SET_ASSOCIATION( mDestroyNotifyList );
  190. VECTOR_SET_ASSOCIATION( mCollisionFixtureDefs );
  191. VECTOR_SET_ASSOCIATION( mCollisionFixtures );
  192. // Assign scene-object index.
  193. mSerialId = ++sSceneObjectMasterSerialId;
  194. sGlobalSceneObjectCount++;
  195. // Initialize the body definition.
  196. // Important: If these defaults are changed then modify the associated "write" field protected methods to ensure
  197. // that the associated field is persisted if not the default.
  198. mBodyDefinition.userData = static_cast<PhysicsProxy*>(this);
  199. mBodyDefinition.position.Set(0.0f, 0.0f);
  200. mBodyDefinition.angle = 0.0f;
  201. mBodyDefinition.linearVelocity.Set(0.0f, 0.0f);
  202. mBodyDefinition.angularVelocity = 0.0f;
  203. mBodyDefinition.linearDamping = 0.0f;
  204. mBodyDefinition.angularDamping = 0.0f;
  205. mBodyDefinition.allowSleep = true;
  206. mBodyDefinition.awake = true;
  207. mBodyDefinition.fixedRotation = false;
  208. mBodyDefinition.bullet = false;
  209. mBodyDefinition.type = b2_dynamicBody;
  210. mBodyDefinition.active = true;
  211. mBodyDefinition.gravityScale = 1.0f;
  212. // Initialize the default fixture definition.
  213. // Important: If these defaults are changed then modify the associated "write" field protected methods to ensure
  214. // that the associated field is persisted if not the default.
  215. mDefaultFixture.userData = static_cast<PhysicsProxy*>(this);
  216. mDefaultFixture.density = 1.0f;
  217. mDefaultFixture.friction = 0.2f;
  218. mDefaultFixture.restitution = 0.0f;
  219. mDefaultFixture.isSensor = false;
  220. mDefaultFixture.shape = NULL;
  221. // Set last awake state.
  222. mLastAwakeState = !mBodyDefinition.allowSleep || mBodyDefinition.awake;
  223. // Turn-off auto-sizing.
  224. mAutoSizing = false;
  225. // Set size.
  226. setSize( Vector2::getOne() );
  227. }
  228. //-----------------------------------------------------------------------------
  229. SceneObject::~SceneObject()
  230. {
  231. // Are we in a Scene?
  232. if ( mpScene )
  233. {
  234. // Yes, so remove from Scene.
  235. mpScene->removeFromScene( this );
  236. }
  237. // Decrease scene-object count.
  238. --sGlobalSceneObjectCount;
  239. }
  240. //-----------------------------------------------------------------------------
  241. void SceneObject::initPersistFields()
  242. {
  243. // Call parent.
  244. Parent::initPersistFields();
  245. /// Lifetime.
  246. addProtectedField("Lifetime", TypeF32, Offset(mLifetime, SceneObject), &setLifetime, &defaultProtectedGetFn, &writeLifetime, "");
  247. /// Scene Layers.
  248. addProtectedField("SceneLayer", TypeS32, Offset(mSceneLayer, SceneObject), &setSceneLayer, &defaultProtectedGetFn, &writeSceneLayer, "");
  249. addProtectedField("SceneLayerDepth", TypeF32, Offset(mSceneLayerDepth, SceneObject), &setSceneLayerDepth, &defaultProtectedGetFn, &writeSceneLayerDepth, "" );
  250. // Scene Groups.
  251. addProtectedField("SceneGroup", TypeS32, Offset(mSceneGroup, SceneObject), &setSceneGroup, &defaultProtectedGetFn, &writeSceneGroup, "");
  252. /// Area.
  253. addProtectedField("Size", TypeVector2, Offset( mSize, SceneObject), &setSize, &defaultProtectedGetFn, &writeSize, "");
  254. /// Position / Angle.
  255. addProtectedField("Position", TypeVector2, NULL, &setPosition, &getPosition, &writePosition, "");
  256. addProtectedField("Angle", TypeF32, NULL, &setAngle, &getAngle, &writeAngle, "");
  257. addProtectedField("FixedAngle", TypeBool, NULL, &setFixedAngle, &getFixedAngle, &writeFixedAngle, "");
  258. /// Body.
  259. addProtectedField("BodyType", TypeEnum, NULL, &setBodyType, &getBodyType, &writeBodyType, 1, &bodyTypeTable, "" );
  260. addProtectedField("Active", TypeBool, NULL, &setActive, &getActive, &writeActive, "" );
  261. addProtectedField("Awake", TypeBool, NULL, &setAwake, &getAwake, &writeAwake, "" );
  262. addProtectedField("Bullet", TypeBool, NULL, &setBullet, &getBullet, &writeBullet, "" );
  263. addProtectedField("SleepingAllowed", TypeBool, NULL, &setSleepingAllowed, &getSleepingAllowed, &writeSleepingAllowed, "" );
  264. /// Collision control.
  265. addProtectedField("CollisionGroups", TypeS32, Offset(mCollisionGroupMask, SceneObject), &setCollisionGroups, &defaultProtectedGetFn, &writeCollisionGroups, "");
  266. addProtectedField("CollisionLayers", TypeS32, Offset(mCollisionLayerMask, SceneObject), &setCollisionLayers, &defaultProtectedGetFn, &writeCollisionLayers, "");
  267. addField("CollisionSuppress", TypeBool, Offset(mCollisionSuppress, SceneObject), &writeCollisionSuppress, "");
  268. addProtectedField("GatherContacts", TypeBool, NULL, &setGatherContacts, &defaultProtectedGetFn, &writeGatherContacts, "");
  269. addProtectedField("DefaultDensity", TypeF32, Offset( mDefaultFixture.density, SceneObject), &setDefaultDensity, &defaultProtectedGetFn, &writeDefaultDensity, "");
  270. addProtectedField("DefaultFriction", TypeF32, Offset( mDefaultFixture.friction, SceneObject), &setDefaultFriction, &defaultProtectedGetFn, &writeDefaultFriction, "");
  271. addProtectedField("DefaultRestitution", TypeF32, Offset( mDefaultFixture.restitution, SceneObject), &setDefaultRestitution, &defaultProtectedGetFn, &writeDefaultRestitution, "");
  272. /// Velocities.
  273. addProtectedField("LinearVelocity", TypeVector2, NULL, &setLinearVelocity, &getLinearVelocity, &writeLinearVelocity, "");
  274. addProtectedField("AngularVelocity", TypeF32, NULL, &setAngularVelocity, &getAngularVelocity, &writeAngularVelocity, "");
  275. addProtectedField("LinearDamping", TypeF32, NULL, &setLinearDamping, &getLinearDamping, &writeLinearDamping, "");
  276. addProtectedField("AngularDamping", TypeF32, NULL, &setAngularDamping, &getAngularDamping, &writeAngularDamping, "");
  277. /// Gravity scaling.
  278. addProtectedField("GravityScale", TypeF32, NULL, &setGravityScale, &getGravityScale, &writeGravityScale, "");
  279. /// Render visibility.
  280. addField("Visible", TypeBool, Offset(mVisible, SceneObject), &writeVisible, "");
  281. /// Render blending.
  282. addField("BlendMode", TypeBool, Offset(mBlendMode, SceneObject), &writeBlendMode, "");
  283. addField("SrcBlendFactor", TypeEnum, Offset(mSrcBlendFactor, SceneObject), &writeSrcBlendFactor, 1, &srcBlendFactorTable);
  284. addField("DstBlendFactor", TypeEnum, Offset(mDstBlendFactor, SceneObject), &writeDstBlendFactor, 1, &dstBlendFactorTable);
  285. addField("BlendColor", TypeColorF, Offset(mBlendColor, SceneObject), &writeBlendColor, "");
  286. addField("AlphaTest", TypeF32, Offset(mAlphaTest, SceneObject), &writeAlphaTest, "");
  287. /// Render sorting.
  288. addField("SortPoint", TypeVector2, Offset(mSortPoint, SceneObject), &writeSortPoint, "");
  289. addField("RenderGroup", TypeString, Offset(mRenderGroup, SceneObject), &writeRenderGroup, "");
  290. /// Input events.
  291. addField("UseInputEvents", TypeBool, Offset(mUseInputEvents, SceneObject), &writeUseInputEvents, "");
  292. // Script callbacks.
  293. addField("UpdateCallback", TypeBool, Offset(mUpdateCallback, SceneObject), &writeUpdateCallback, "");
  294. addField("CollisionCallback", TypeBool, Offset(mCollisionCallback, SceneObject), &writeCollisionCallback, "");
  295. addField("SleepingCallback", TypeBool, Offset(mSleepingCallback, SceneObject), &writeSleepingCallback, "");
  296. /// Scene.
  297. addProtectedField("scene", TypeSimObjectPtr, Offset(mpScene, SceneObject), &setScene, &defaultProtectedGetFn, &writeScene, "");
  298. }
  299. //-----------------------------------------------------------------------------
  300. bool SceneObject::onAdd()
  301. {
  302. // Call Parent.
  303. if(!Parent::onAdd())
  304. return false;
  305. // Add to any target scene.
  306. if ( mpTargetScene )
  307. {
  308. // Add to the target scene.
  309. mpTargetScene->addToScene(this);
  310. mpTargetScene = NULL;
  311. }
  312. // Perform the callback.
  313. Con::executef(this, 1, "onAdd");
  314. // Return Okay.
  315. return true;
  316. }
  317. //-----------------------------------------------------------------------------
  318. void SceneObject::onRemove()
  319. {
  320. // Perform the callback.
  321. Con::executef(this, 1, "onRemove");
  322. // Detach Any GUI Control.
  323. detachGui();
  324. // Remove from Scene.
  325. if ( getScene() )
  326. getScene()->removeFromScene( this );
  327. // Call Parent.
  328. Parent::onRemove();
  329. }
  330. //-----------------------------------------------------------------------------
  331. void SceneObject::onDestroyNotify( SceneObject* pSceneObject )
  332. {
  333. }
  334. //-----------------------------------------------------------------------------
  335. void SceneObject::OnRegisterScene( Scene* pScene )
  336. {
  337. // Sanity!
  338. AssertFatal( mpScene == NULL, "Cannot register to a scene if already registered." );
  339. AssertFatal( mpBody == NULL, "Cannot create a physics body if one already exists." );
  340. // Initialize contact gathering.
  341. initializeContactGathering();
  342. // Set scene.
  343. mpScene = pScene;
  344. // Create the physics body.
  345. mpBody = pScene->getWorld()->CreateBody( &mBodyDefinition );
  346. // Set active status.
  347. if ( !isEnabled() ) mpBody->SetActive( false );
  348. // Create fixtures.
  349. for( typeCollisionFixtureDefVector::iterator itr = mCollisionFixtureDefs.begin(); itr != mCollisionFixtureDefs.end(); itr++ )
  350. {
  351. // Fetch fixture definition.
  352. b2FixtureDef* pFixtureDef = (*itr);
  353. // Create fixture.
  354. b2Fixture* pFixture = mpBody->CreateFixture( pFixtureDef );
  355. // Push fixture.
  356. mCollisionFixtures.push_back( pFixture );
  357. // Destroy fixture shape.
  358. delete pFixtureDef->shape;
  359. // Destroy fixture definition.
  360. delete pFixtureDef;
  361. }
  362. // Clear offline fixture definitions.
  363. mCollisionFixtureDefs.clear();
  364. // Calculate current AABB.
  365. CoreMath::mCalculateAABB( getLocalSizedOOBB(), mpBody->GetTransform(), &mCurrentAABB );
  366. // Create world proxy Id.
  367. mWorldProxyId = pScene->getWorldQuery()->add( this );
  368. // Reset the spatials.
  369. resetTickSpatials();
  370. // Notify components.
  371. notifyComponentsAddToScene();
  372. }
  373. //-----------------------------------------------------------------------------
  374. void SceneObject::OnUnregisterScene( Scene* pScene )
  375. {
  376. // Sanity!
  377. AssertFatal( mpScene == pScene, "Cannot unregister from a scene that is not registered." );
  378. AssertFatal( mpBody != NULL, "Cannot unregister physics body as it does not exist." );
  379. // Notify components.
  380. notifyComponentsRemoveFromScene();
  381. // Copy fixtures to fixture definitions.
  382. for( typeCollisionFixtureVector::iterator itr = mCollisionFixtures.begin(); itr != mCollisionFixtures.end(); itr++ )
  383. {
  384. // Fetch fixture.
  385. b2Fixture* pFixture = (*itr);
  386. // Create fixture definition.
  387. b2FixtureDef* pFixtureDef = new b2FixtureDef();
  388. pFixtureDef->density = pFixture->GetDensity();
  389. pFixtureDef->friction = pFixture->GetFriction();
  390. pFixtureDef->restitution = pFixture->GetRestitution();
  391. pFixtureDef->isSensor = pFixture->IsSensor();
  392. pFixtureDef->userData = this;
  393. pFixtureDef->shape = pFixture->GetShape()->Clone( pScene->getBlockAllocator() );
  394. // Push fixture definition.
  395. mCollisionFixtureDefs.push_back( pFixtureDef );
  396. }
  397. // Clear our fixture references.
  398. // The actual fixtures will get destroyed when the body is destroyed so no need to destroy them here.
  399. mCollisionFixtures.clear();
  400. // Transfer physics body configuration back to definition.
  401. mBodyDefinition.type = getBodyType();
  402. mBodyDefinition.position = getPosition();
  403. mBodyDefinition.angle = getAngle();
  404. mBodyDefinition.linearVelocity = getLinearVelocity();
  405. mBodyDefinition.angularVelocity = getAngularVelocity();
  406. mBodyDefinition.linearDamping = getLinearDamping();
  407. mBodyDefinition.angularDamping = getAngularDamping();
  408. mBodyDefinition.gravityScale = getGravityScale();
  409. mBodyDefinition.allowSleep = getSleepingAllowed();
  410. mBodyDefinition.awake = getAwake();
  411. mBodyDefinition.fixedRotation = getFixedAngle();
  412. mBodyDefinition.bullet = getBullet();
  413. mBodyDefinition.active = getActive();
  414. // Destroy current contacts.
  415. delete mpCurrentContacts;
  416. mpCurrentContacts = NULL;
  417. // Destroy the physics body.
  418. mpScene->getWorld()->DestroyBody( mpBody );
  419. mpBody = NULL;
  420. // Destroy world proxy Id.
  421. if ( mWorldProxyId != -1 )
  422. {
  423. mpScene->getWorldQuery()->remove( this );
  424. mWorldProxyId = -1;
  425. }
  426. // Reset scene.
  427. mpScene = NULL;
  428. }
  429. //-----------------------------------------------------------------------------
  430. void SceneObject::resetTickSpatials( const bool resize )
  431. {
  432. // Set coincident pre-tick, current & render.
  433. mPreTickPosition = mRenderPosition = getPosition();
  434. mPreTickAngle = mRenderAngle = getAngle();
  435. // Fetch body transform.
  436. b2Transform bodyXform = getTransform();
  437. // Calculate current AABB.
  438. CoreMath::mCalculateAABB( getLocalSizedOOBB(), bodyXform, &mCurrentAABB );
  439. // Set coincident AABBs.
  440. mPreTickAABB = mCurrentAABB;
  441. // Calculate render OOBB.
  442. CoreMath::mCalculateOOBB( getLocalSizedOOBB(), bodyXform, mRenderOOBB );
  443. // Update world proxy (if in scene).
  444. if ( mpScene )
  445. {
  446. // Fetch world query.
  447. WorldQuery* pWorldQuery = mpScene->getWorldQuery();
  448. // Are we resizing the object?
  449. if ( resize )
  450. {
  451. // Yes, so we need to recreate a proxy.
  452. pWorldQuery->remove( this );
  453. mWorldProxyId = pWorldQuery->add( this );
  454. }
  455. else
  456. {
  457. // No, so we can simply update the proxy.
  458. pWorldQuery->update( this, mCurrentAABB, b2Vec2( 0.0f, 0.0f ) );
  459. }
  460. }
  461. // Flag spatial changed.
  462. mSpatialDirty = true;
  463. }
  464. //-----------------------------------------------------------------------------
  465. void SceneObject::preIntegrate( const F32 totalTime, const F32 elapsedTime, DebugStats* pDebugStats )
  466. {
  467. // Debug Profiling.
  468. PROFILE_SCOPE(SceneObject_PreIntegrate);
  469. // Finish if nothing is dirty.
  470. if ( !mSpatialDirty )
  471. return;
  472. // Reset spatial changed.
  473. mSpatialDirty = false;
  474. mPreTickPosition = mRenderPosition = getPosition();
  475. mPreTickAngle = mRenderAngle = getAngle();
  476. mPreTickAABB = mCurrentAABB;
  477. // Calculate render OOBB.
  478. CoreMath::mCalculateOOBB( getLocalSizedOOBB(), getTransform(), mRenderOOBB );
  479. }
  480. //-----------------------------------------------------------------------------
  481. void SceneObject::integrateObject( const F32 totalTime, const F32 elapsedTime, DebugStats* pDebugStats )
  482. {
  483. // Debug Profiling.
  484. PROFILE_SCOPE(SceneObject_IntegrateObject);
  485. // Fetch position.
  486. const b2Vec2 position = getPosition();
  487. // Has the angle or position changed?
  488. if ( mPreTickAngle != getAngle() ||
  489. mPreTickPosition.x != position.x ||
  490. mPreTickPosition.y != position.y )
  491. {
  492. // Yes, so flag spatial dirty.
  493. mSpatialDirty = true;
  494. // Calculate current AABB.
  495. CoreMath::mCalculateAABB( getLocalSizedOOBB(), getTransform(), &mCurrentAABB );
  496. // Calculate tick AABB.
  497. b2AABB tickAABB;
  498. tickAABB.Combine( mPreTickAABB, mCurrentAABB );
  499. // Calculate tick displacement.
  500. b2Vec2 tickDisplacement = position - mPreTickPosition;
  501. // Update world proxy.
  502. mpScene->getWorldQuery()->update( this, tickAABB, tickDisplacement );
  503. }
  504. // Update Lifetime.
  505. if ( mLifetimeActive && !getScene()->getIsEditorScene() )
  506. {
  507. updateLifetime( elapsedTime );
  508. }
  509. // Update Any Attached GUI.
  510. if ( mpAttachedGui && mpAttachedGuiSceneWindow )
  511. {
  512. updateAttachedGui();
  513. }
  514. // Are we attached to a camera?
  515. if ( mpAttachedCamera )
  516. {
  517. // Yes, so calculate camera mount.
  518. mpAttachedCamera->calculateCameraMount( elapsedTime );
  519. }
  520. }
  521. //-----------------------------------------------------------------------------
  522. void SceneObject::postIntegrate(const F32 totalTime, const F32 elapsedTime, DebugStats *pDebugStats)
  523. {
  524. // Debug Profiling.
  525. PROFILE_SCOPE(SceneObject_PostIntegrate);
  526. // Finish if no scene.
  527. if( !getScene() )
  528. return;
  529. // Notify components.
  530. notifyComponentsUpdate();
  531. // Script "onUpdate".
  532. if ( mUpdateCallback )
  533. {
  534. PROFILE_SCOPE(SceneObject_onUpdateCallback);
  535. Con::executef(this, 1, "onUpdate");
  536. }
  537. // Are we using the sleeping callback?
  538. if ( mSleepingCallback )
  539. {
  540. PROFILE_SCOPE(SceneObject_onWakeSleepCallback);
  541. // Yes, so fetch the current awake state.
  542. const bool currentAwakeState = getAwake();
  543. // Did we change awake state?
  544. if ( currentAwakeState != mLastAwakeState )
  545. {
  546. // Yes, so update last awake state.
  547. mLastAwakeState = currentAwakeState;
  548. // Perform the appropriate callback.
  549. if ( currentAwakeState )
  550. Con::executef(this, 1, "onWake");
  551. else
  552. Con::executef(this, 1, "onSleep");
  553. }
  554. }
  555. }
  556. //-----------------------------------------------------------------------------
  557. void SceneObject::interpolateObject( const F32 timeDelta )
  558. {
  559. // Debug Profiling.
  560. PROFILE_SCOPE(SceneObject_InterpolateObject);
  561. if ( mSpatialDirty )
  562. {
  563. // Debug Profiling.
  564. PROFILE_SCOPE(SceneObject_InterpolatePositionAngle);
  565. if ( timeDelta < 1.0f )
  566. {
  567. // Calculate render position.
  568. const b2Vec2 position = getPosition();
  569. b2Vec2 positionDelta = position - mPreTickPosition;
  570. positionDelta *= timeDelta;
  571. mRenderPosition = position - positionDelta;
  572. // Calculate render angle.
  573. const F32 angle = getAngle();
  574. F32 relativeAngle = angle - mPreTickAngle;
  575. if ( relativeAngle > b2_pi )
  576. relativeAngle -= b2_pi2;
  577. else if ( relativeAngle < -b2_pi )
  578. relativeAngle += b2_pi2;
  579. mRenderAngle = angle - (relativeAngle * timeDelta);
  580. }
  581. else
  582. {
  583. mRenderPosition = mPreTickPosition;
  584. mRenderAngle = mPreTickAngle;
  585. }
  586. // Calculate render transform.
  587. b2Transform renderXF( mRenderPosition, b2Rot(mRenderAngle) );
  588. // Calculate render OOBB.
  589. CoreMath::mCalculateOOBB( getLocalSizedOOBB(), renderXF, mRenderOOBB );
  590. }
  591. // Update Any Attached GUI.
  592. if ( mpAttachedGui && mpAttachedGuiSceneWindow )
  593. {
  594. updateAttachedGui();
  595. }
  596. // Are we attached to a camera?
  597. if ( mpAttachedCamera )
  598. {
  599. // Yes, so interpolate camera mount.
  600. mpAttachedCamera->interpolateCameraMount( timeDelta );
  601. }
  602. };
  603. //-----------------------------------------------------------------------------
  604. void SceneObject::sceneRenderFallback( const SceneRenderState* pSceneRenderState, const SceneRenderRequest* pSceneRenderRequest, BatchRender* pBatchRenderer )
  605. {
  606. // Debug Profiling.
  607. PROFILE_SCOPE(SceneObject_SceneRenderFallback);
  608. // Fetch the 'cannot render' proxy.
  609. RenderProxy* pNoImageRenderProxy = Sim::findObject<RenderProxy>( CANNOT_RENDER_PROXY_NAME );
  610. // Finish if no render proxy available or it can't render.
  611. if ( pNoImageRenderProxy == NULL || !pNoImageRenderProxy->validRender() )
  612. return;
  613. // Fetch render AABB.
  614. const b2Vec2* pRenderOOBB = getRenderOOBB();
  615. // Render using render proxy.
  616. pNoImageRenderProxy->render(
  617. false, false,
  618. pRenderOOBB[0], pRenderOOBB[1], pRenderOOBB[2], pRenderOOBB[3],
  619. pBatchRenderer );
  620. }
  621. //-----------------------------------------------------------------------------
  622. void SceneObject::sceneRenderOverlay( const SceneRenderState* sceneRenderState )
  623. {
  624. // Debug Profiling.
  625. PROFILE_SCOPE(SceneObject_SceneRenderOverlay);
  626. // Get Scene.
  627. Scene* pScene = getScene();
  628. // Cannot do anything without scene!
  629. if ( !pScene )
  630. return;
  631. // Don't draw debug if not enabled.
  632. if ( !isEnabled() )
  633. return;
  634. // Get merged Local/Scene Debug Mask.
  635. U32 debugMask = getDebugMask() | pScene->getDebugMask();
  636. // Finish here if we're not rendering any debug info or only have scene-rendered debug options.
  637. if ( !debugMask || (debugMask & ~(Scene::SCENE_DEBUG_METRICS | Scene::SCENE_DEBUG_JOINTS)) == 0 )
  638. return;
  639. // Clear blending.
  640. glDisable( GL_BLEND );
  641. glDisable( GL_TEXTURE_2D );
  642. // AABB debug draw.
  643. if ( debugMask & Scene::SCENE_DEBUG_AABB )
  644. {
  645. pScene->mDebugDraw.DrawAABB( mCurrentAABB );
  646. }
  647. // OOBB debug draw.
  648. if ( debugMask & Scene::SCENE_DEBUG_OOBB )
  649. {
  650. pScene->mDebugDraw.DrawOOBB( mRenderOOBB );
  651. }
  652. // Asleep debug draw.
  653. if ( !getAwake() && debugMask & Scene::SCENE_DEBUG_SLEEP )
  654. {
  655. pScene->mDebugDraw.DrawAsleep( mRenderOOBB );
  656. }
  657. // Collision Shapes.
  658. if ( debugMask & Scene::SCENE_DEBUG_COLLISION_SHAPES )
  659. {
  660. pScene->mDebugDraw.DrawCollisionShapes( getRenderTransform(), getBody() );
  661. }
  662. // Position and local center of mass.
  663. if ( debugMask & Scene::SCENE_DEBUG_POSITION_AND_COM )
  664. {
  665. const b2Vec2 renderPosition = getRenderPosition();
  666. pScene->mDebugDraw.DrawPoint( renderPosition + getLocalCenter(), 6, b2Color( 0.0f, 1.0f, 0.4f ) );
  667. pScene->mDebugDraw.DrawPoint( renderPosition, 4, b2Color( 0.0f, 0.4f, 1.0f ) );
  668. }
  669. // Sort Points.
  670. if ( debugMask & Scene::SCENE_DEBUG_SORT_POINTS )
  671. {
  672. pScene->mDebugDraw.DrawSortPoint( getRenderPosition(), getSize(), mSortPoint );
  673. }
  674. }
  675. //-----------------------------------------------------------------------------
  676. U32 SceneObject::packUpdate(NetConnection * conn, U32 mask, BitStream *stream)
  677. {
  678. return 0;
  679. }
  680. //-----------------------------------------------------------------------------
  681. void SceneObject::unpackUpdate(NetConnection * conn, BitStream *stream)
  682. {
  683. }
  684. //-----------------------------------------------------------------------------
  685. void SceneObject::setEnabled( const bool enabled )
  686. {
  687. // Call parent.
  688. Parent::setEnabled( enabled );
  689. // If we have a scene, modify active.
  690. if ( mpScene )
  691. {
  692. mpBody->SetActive( enabled );
  693. }
  694. }
  695. //-----------------------------------------------------------------------------
  696. void SceneObject::setLifetime( const F32 lifetime )
  697. {
  698. // Debug Profiling.
  699. PROFILE_SCOPE(SceneObject_setLifetime);
  700. // Usage Flag.
  701. mLifetimeActive = mGreaterThanZero( lifetime );
  702. // Is life active?
  703. if ( mLifetimeActive )
  704. {
  705. // Yes, so set to incoming lifetime.
  706. mLifetime = lifetime;
  707. }
  708. else
  709. {
  710. // No, so reset it to be safe.
  711. mLifetime = 0.0f;
  712. }
  713. }
  714. //-----------------------------------------------------------------------------
  715. void SceneObject::updateLifetime( const F32 elapsedTime )
  716. {
  717. // Update Lifetime.
  718. if ( mLifetimeActive )
  719. {
  720. // Reduce Lifetime.
  721. setLifetime( getLifetime() - elapsedTime );
  722. // Are we now dead?
  723. if ( mLessThanOrEqual( getLifetime(), 0.0f) )
  724. {
  725. // Yes, so reset lifetime.
  726. setLifetime( 0.0f );
  727. // Initiate Death!
  728. safeDelete();
  729. }
  730. }
  731. }
  732. //-----------------------------------------------------------------------------
  733. void SceneObject::setSceneLayer( const U32 sceneLayer )
  734. {
  735. // Check Layer.
  736. if ( sceneLayer > (MAX_LAYERS_SUPPORTED-1) )
  737. {
  738. Con::warnf("SceneObject::setSceneLayer() - Invalid scene layer '%d' (0-31).", sceneLayer);
  739. return;
  740. }
  741. // Set Layer.
  742. mSceneLayer = sceneLayer;
  743. // Set Layer Mask.
  744. mSceneLayerMask = BIT( mSceneLayer );
  745. }
  746. //-----------------------------------------------------------------------------
  747. bool SceneObject::setSceneLayerDepthFront( void )
  748. {
  749. // Fetch the scene.
  750. Scene* pScene = getScene();
  751. // Finish if no scene or only a single object.
  752. if ( pScene == NULL || pScene->getSceneObjectCount() == 1 )
  753. return false;
  754. // Fetch scene objects.
  755. typeSceneObjectVector layerList;
  756. pScene->getSceneObjects( layerList, getSceneLayer() );
  757. // Fetch layer object count.
  758. const U32 layerObjectCount = (U32)layerList.size();
  759. // Sort the layer.
  760. dQsort(layerList.address(), layerObjectCount, sizeof(SceneObject*), sceneObjectLayerDepthSort);
  761. // Reset object index.
  762. U32 objectIndex = 0;
  763. // Find object index.
  764. for ( ; objectIndex < layerObjectCount; ++objectIndex )
  765. {
  766. // Stop if this is the current object index.
  767. if ( layerList[objectIndex] == this )
  768. break;
  769. }
  770. // Finish if already at front of layer.
  771. if ( objectIndex == layerObjectCount-1 )
  772. return false;
  773. // Fetch furthest front depth.
  774. const F32 frontDepth = layerList.last()->getSceneLayerDepth();
  775. // Adjust depth to be in front.
  776. setSceneLayerDepth( frontDepth - 1.0f );
  777. return true;
  778. }
  779. //-----------------------------------------------------------------------------
  780. bool SceneObject::setSceneLayerDepthBack( void )
  781. {
  782. // Fetch the scene.
  783. Scene* pScene = getScene();
  784. // Finish if no scene or only a single object.
  785. if ( pScene == NULL || pScene->getSceneObjectCount() == 1 )
  786. return false;
  787. // Fetch scene objects.
  788. typeSceneObjectVector layerList;
  789. pScene->getSceneObjects( layerList, getSceneLayer() );
  790. // Fetch layer object count.
  791. const U32 layerObjectCount = (U32)layerList.size();
  792. // Sort the layer.
  793. dQsort(layerList.address(), layerObjectCount, sizeof(SceneObject*), sceneObjectLayerDepthSort);
  794. // Reset object index.
  795. U32 objectIndex = 0;
  796. // Find object index.
  797. for ( ; objectIndex < layerObjectCount; ++objectIndex )
  798. {
  799. // Stop if this is the current object index.
  800. if ( layerList[objectIndex] == this )
  801. break;
  802. }
  803. // Finish if already at back of layer.
  804. if ( objectIndex == 0 )
  805. return false;
  806. // Fetch furthest back depth.
  807. const F32 backDepth = layerList.first()->getSceneLayerDepth();
  808. // Adjust depth to be in back.
  809. setSceneLayerDepth( backDepth + 1.0f );
  810. return true;
  811. }
  812. //-----------------------------------------------------------------------------
  813. bool SceneObject::setSceneLayerDepthForward( void )
  814. {
  815. // Fetch the scene.
  816. Scene* pScene = getScene();
  817. // Finish if no scene or only a single object.
  818. if ( pScene == NULL || pScene->getSceneObjectCount() == 1 )
  819. return false;
  820. // Fetch scene objects.
  821. typeSceneObjectVector layerList;
  822. pScene->getSceneObjects( layerList, getSceneLayer() );
  823. // Fetch layer object count.
  824. const U32 layerObjectCount = (U32)layerList.size();
  825. // Sort the layer.
  826. dQsort(layerList.address(), layerObjectCount, sizeof(SceneObject*), sceneObjectLayerDepthSort);
  827. // Reset object index.
  828. U32 objectIndex = 0;
  829. // Find object index.
  830. for ( ; objectIndex < layerObjectCount; ++objectIndex )
  831. {
  832. // Stop if this is the current object index.
  833. if ( layerList[objectIndex] == this )
  834. break;
  835. }
  836. // Finish if already at the front of the layer.
  837. if ( objectIndex == layerObjectCount-1 )
  838. return false;
  839. // Fetch forwards depth.
  840. const F32 forwardDepth = layerList[objectIndex+1]->getSceneLayerDepth();
  841. // Adjust depth to be forward.
  842. setSceneLayerDepth( forwardDepth - 0.5f );
  843. // Finish if we were almost at the front anyway.
  844. if ( objectIndex == layerObjectCount-2 )
  845. return true;
  846. // Adjust next objects forwards.
  847. for( U32 forwardIndex = objectIndex+2; forwardIndex < layerObjectCount; ++forwardIndex )
  848. {
  849. // Fetch scene object.
  850. SceneObject* forwardSceneObject = layerList[forwardIndex];
  851. // Adjust depth to be forwards.
  852. forwardSceneObject->setSceneLayerDepth( forwardSceneObject->getSceneLayerDepth() - 1.0f );
  853. }
  854. return true;
  855. }
  856. //-----------------------------------------------------------------------------
  857. bool SceneObject::setSceneLayerDepthBackward( void )
  858. {
  859. // Fetch the scene.
  860. Scene* pScene = getScene();
  861. // Finish if no scene or only a single object.
  862. if ( pScene == NULL || pScene->getSceneObjectCount() == 1 )
  863. return false;
  864. // Fetch scene objects.
  865. typeSceneObjectVector layerList;
  866. pScene->getSceneObjects( layerList, getSceneLayer() );
  867. // Fetch layer object count.
  868. const U32 layerObjectCount = (U32)layerList.size();
  869. // Sort the layer.
  870. dQsort(layerList.address(), layerObjectCount, sizeof(SceneObject*), sceneObjectLayerDepthSort);
  871. // Reset object index.
  872. U32 objectIndex = 0;
  873. // Find object index.
  874. for ( ; objectIndex < layerObjectCount; ++objectIndex )
  875. {
  876. // Stop if this is the current object index.
  877. if ( layerList[objectIndex] == this )
  878. break;
  879. }
  880. // Finish if already at the back of the layer.
  881. if ( objectIndex == 0 )
  882. return false;
  883. // Fetch backwards depth.
  884. const F32 backDepth = layerList[objectIndex-1]->getSceneLayerDepth();
  885. // Adjust depth to be backwards.
  886. setSceneLayerDepth( backDepth + 0.5f );
  887. // Finish if we were almost at the back anyway.
  888. if ( objectIndex == 1 )
  889. return true;
  890. // Adjust previous objects backwards.
  891. for( U32 backIndex = 0; backIndex < (objectIndex-1); ++backIndex )
  892. {
  893. // Fetch scene object.
  894. SceneObject* backSceneObject = layerList[backIndex];
  895. // Adjust depth to be backwards.
  896. backSceneObject->setSceneLayerDepth( backSceneObject->getSceneLayerDepth() + 1.0f );
  897. }
  898. return true;
  899. }
  900. //-----------------------------------------------------------------------------
  901. void SceneObject::setSceneGroup( const U32 sceneGroup )
  902. {
  903. // Check Group.
  904. if ( sceneGroup > 31 )
  905. {
  906. Con::warnf("SceneObject::setSceneGroup() - Invalid scene group '%d' (0-31).", sceneGroup);
  907. return;
  908. }
  909. // Set Group.
  910. mSceneGroup = sceneGroup;
  911. // Set Group Mask.
  912. mSceneGroupMask = BIT( mSceneGroup );
  913. }
  914. //-----------------------------------------------------------------------------
  915. void SceneObject::setArea( const Vector2& corner1, const Vector2& corner2 )
  916. {
  917. // Debug Profiling.
  918. PROFILE_SCOPE(SceneObject_SetArea);
  919. // Calculate Normalized region.
  920. const Vector2 topLeft((corner1.x <= corner2.x) ? corner1.x : corner2.x, (corner1.y <= corner2.y) ? corner1.y : corner2.y);
  921. const Vector2 bottomRight((corner1.x > corner2.x) ? corner1.x : corner2.x, (corner1.y > corner2.y) ? corner1.y : corner2.y);
  922. // Calculate New Size.
  923. const Vector2 size = bottomRight - topLeft;
  924. // Calculate New Position.
  925. const Vector2 position = topLeft + (size * 0.5f);
  926. // Reset angle.
  927. setAngle( 0.0f );
  928. // Set Position/Size.
  929. setPosition( position );
  930. setSize( size );
  931. }
  932. //-----------------------------------------------------------------------------
  933. void SceneObject::setSize( const Vector2& size )
  934. {
  935. // Debug Profiling.
  936. PROFILE_SCOPE(SceneObject_SetSize);
  937. mSize = size;
  938. // Calculate half size.
  939. const F32 halfWidth = size.x * 0.5f;
  940. const F32 halfHeight = size.y * 0.5f;
  941. // Set local size OOBB.
  942. mLocalSizeOOBB[0].Set( -halfWidth, -halfHeight );
  943. mLocalSizeOOBB[1].Set( +halfWidth, -halfHeight );
  944. mLocalSizeOOBB[2].Set( +halfWidth, +halfHeight );
  945. mLocalSizeOOBB[3].Set( -halfWidth, +halfHeight );
  946. if ( mpScene )
  947. {
  948. // Reset tick spatials.
  949. resetTickSpatials( true );
  950. }
  951. }
  952. //-----------------------------------------------------------------------------
  953. void SceneObject::setPosition( const Vector2& position )
  954. {
  955. // Debug Profiling.
  956. PROFILE_SCOPE(SceneObject_SetPosition);
  957. if ( mpScene )
  958. {
  959. mpBody->SetTransform( position, mpBody->GetAngle() );
  960. // Reset tick spatials.
  961. resetTickSpatials();
  962. }
  963. else
  964. {
  965. mBodyDefinition.position = position;
  966. }
  967. }
  968. //-----------------------------------------------------------------------------
  969. void SceneObject::setAngle( const F32 radians )
  970. {
  971. // Debug Profiling.
  972. PROFILE_SCOPE(SceneObject_SetAngle);
  973. if ( mpScene )
  974. {
  975. mpBody->SetTransform( mpBody->GetPosition(), radians );
  976. // Reset tick spatials.
  977. resetTickSpatials();
  978. }
  979. else
  980. {
  981. mBodyDefinition.angle = radians;
  982. }
  983. }
  984. //-----------------------------------------------------------------------------
  985. Vector2 SceneObject::getLocalPoint( const Vector2 &worldPoint )
  986. {
  987. if ( mpScene )
  988. {
  989. return mpBody->GetLocalPoint( worldPoint );
  990. }
  991. // Calculate body definition transform.
  992. const b2Transform transform( mBodyDefinition.position, b2Rot(mBodyDefinition.angle) );
  993. return b2MulT(transform, worldPoint);
  994. }
  995. //-----------------------------------------------------------------------------
  996. Vector2 SceneObject::getWorldPoint( const Vector2 &localPoint )
  997. {
  998. if ( mpScene )
  999. {
  1000. return mpBody->GetWorldPoint( localPoint );
  1001. }
  1002. // Calculate body definition transform.
  1003. const b2Transform transform( mBodyDefinition.position, b2Rot(mBodyDefinition.angle) );
  1004. return b2Mul(transform, localPoint);
  1005. }
  1006. //-----------------------------------------------------------------------------
  1007. Vector2 SceneObject::getLocalVector( const Vector2& worldVector )
  1008. {
  1009. if ( mpScene )
  1010. {
  1011. return mpBody->GetLocalVector( worldVector );
  1012. }
  1013. // Calculate body definition transform.
  1014. const b2Transform transform( mBodyDefinition.position, b2Rot(mBodyDefinition.angle) );
  1015. return b2MulT(transform.q, worldVector);
  1016. }
  1017. //-----------------------------------------------------------------------------
  1018. Vector2 SceneObject::getWorldVector( const Vector2& localVector )
  1019. {
  1020. if ( mpScene )
  1021. {
  1022. return mpBody->GetWorldVector( localVector );
  1023. }
  1024. // Calculate body definition transform.
  1025. const b2Transform transform( mBodyDefinition.position, b2Rot(mBodyDefinition.angle) );
  1026. return b2Mul(transform.q, localVector);
  1027. }
  1028. //-----------------------------------------------------------------------------
  1029. bool SceneObject::getIsPointInOOBB( const Vector2& worldPoint )
  1030. {
  1031. // Fetch local point.
  1032. Vector2 localPoint = getLocalPoint( worldPoint );
  1033. // Turn the local point into an absolute component distance.
  1034. localPoint.absolute();
  1035. const Vector2 halfSize = getHalfSize();
  1036. // Check distance.
  1037. return !( localPoint.x > halfSize.x || localPoint.y > halfSize.y );
  1038. }
  1039. //-----------------------------------------------------------------------------
  1040. bool SceneObject::getIsPointInCollisionShape( const U32 shapeIndex, const Vector2& worldPoint )
  1041. {
  1042. // Sanity!
  1043. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::getIsPointInCollisionShape() - Invalid shape index." );
  1044. // Sanity!
  1045. if ( !mpScene )
  1046. {
  1047. Con::warnf( "SceneObject::getIsPointInCollisionShape() - Cannot test for point, object not in scene." );
  1048. return false;
  1049. }
  1050. // Fetch fixture.
  1051. b2Fixture* pFixture = mCollisionFixtures[shapeIndex];
  1052. // Fetch local point.
  1053. const Vector2 localPoint = getLocalPoint( worldPoint );
  1054. // Test point.
  1055. return pFixture->TestPoint( localPoint );
  1056. }
  1057. //-----------------------------------------------------------------------------
  1058. void SceneObject::setBodyType( const b2BodyType type )
  1059. {
  1060. // Sanity!
  1061. AssertFatal( type == b2_staticBody || type == b2_kinematicBody || type == b2_dynamicBody, "Invalid body type." );
  1062. if ( mpScene )
  1063. {
  1064. mpBody->SetType( type );
  1065. return;
  1066. }
  1067. else
  1068. {
  1069. mBodyDefinition.type = type;
  1070. }
  1071. }
  1072. //-----------------------------------------------------------------------------
  1073. void SceneObject::applyForce( const Vector2& worldForce, const bool wake )
  1074. {
  1075. // Ignore if not in scene.
  1076. if ( !mpScene )
  1077. return;
  1078. applyForce( worldForce, getPosition() + getLocalCenter(), wake );
  1079. }
  1080. //-----------------------------------------------------------------------------
  1081. void SceneObject::applyForce( const Vector2& worldForce, const Vector2& worldPoint, const bool wake )
  1082. {
  1083. // Ignore if not in scene.
  1084. if ( !mpScene )
  1085. return;
  1086. getBody()->ApplyForce( worldForce, worldPoint, wake );
  1087. }
  1088. //-----------------------------------------------------------------------------
  1089. void SceneObject::applyTorque( const F32 torque, const bool wake )
  1090. {
  1091. // Ignore if not in scene.
  1092. if ( !mpScene )
  1093. return;
  1094. getBody()->ApplyTorque( torque, wake );
  1095. }
  1096. //-----------------------------------------------------------------------------
  1097. void SceneObject::applyLinearImpulse( const Vector2& worldImpulse, const bool wake )
  1098. {
  1099. // Ignore if not in scene.
  1100. if ( !mpScene )
  1101. return;
  1102. applyLinearImpulse( worldImpulse, getPosition() + getLocalCenter(), wake );
  1103. }
  1104. //-----------------------------------------------------------------------------
  1105. void SceneObject::applyLinearImpulse( const Vector2& worldImpulse, const Vector2& worldPoint, const bool wake )
  1106. {
  1107. // Ignore if not in scene.
  1108. if ( !mpScene )
  1109. return;
  1110. getBody()->ApplyLinearImpulse( worldImpulse, worldPoint, wake );
  1111. }
  1112. //-----------------------------------------------------------------------------
  1113. void SceneObject::applyAngularImpulse( const F32 impulse, const bool wake )
  1114. {
  1115. // Ignore if not in scene.
  1116. if ( !mpScene )
  1117. return;
  1118. getBody()->ApplyAngularImpulse( impulse, wake );
  1119. }
  1120. //-----------------------------------------------------------------------------
  1121. void SceneObject::setCollisionMasks( const U32 groupMask, const U32 layerMask )
  1122. {
  1123. // Set Group/Layer Collision Masks.
  1124. mCollisionGroupMask = groupMask;
  1125. mCollisionLayerMask = layerMask;
  1126. }
  1127. //-----------------------------------------------------------------------------
  1128. void SceneObject::setCollisionAgainst( const SceneObject* pSceneObject, const bool clearMasks )
  1129. {
  1130. // Do we need to clear existing masks?
  1131. if ( clearMasks )
  1132. {
  1133. // Yes, so just set the masks to the referenced-objects' masks.
  1134. setCollisionMasks( pSceneObject->getSceneGroupMask(), pSceneObject->getSceneLayerMask() );
  1135. }
  1136. else
  1137. {
  1138. // No, so merge with existing masks.
  1139. setCollisionMasks( getCollisionGroupMask() | pSceneObject->getSceneGroupMask(), getCollisionLayerMask() | pSceneObject->getSceneLayerMask() );
  1140. }
  1141. }
  1142. //-----------------------------------------------------------------------------
  1143. void SceneObject::setDefaultDensity( const F32 density, const bool updateShapes )
  1144. {
  1145. mDefaultFixture.density = density;
  1146. // Early-out if not updating shapes.
  1147. if ( !updateShapes )
  1148. return;
  1149. if ( mpScene )
  1150. {
  1151. // Update live fixtures.
  1152. for( U32 index = 0; index < (U32)mCollisionFixtures.size(); ++index )
  1153. {
  1154. mCollisionFixtures[index]->SetDensity( density );
  1155. }
  1156. // Update the body mass data.
  1157. mpBody->ResetMassData();
  1158. return;
  1159. }
  1160. // Update offline fixture definitions.
  1161. for( U32 index = 0; index < (U32)mCollisionFixtureDefs.size(); ++index )
  1162. {
  1163. mCollisionFixtureDefs[index]->density = density;
  1164. }
  1165. }
  1166. //-----------------------------------------------------------------------------
  1167. void SceneObject::setDefaultFriction( const F32 friction, const bool updateShapes )
  1168. {
  1169. mDefaultFixture.friction = friction;
  1170. // Early-out if not updating shapes.
  1171. if ( !updateShapes )
  1172. return;
  1173. if ( mpScene )
  1174. {
  1175. // Update live fixtures.
  1176. for( U32 index = 0; index < (U32)mCollisionFixtures.size(); ++index )
  1177. {
  1178. mCollisionFixtures[index]->SetFriction( friction );
  1179. }
  1180. return;
  1181. }
  1182. // Update offline fixture definitions.
  1183. for( U32 index = 0; index < (U32)mCollisionFixtureDefs.size(); ++index )
  1184. {
  1185. mCollisionFixtureDefs[index]->friction = friction;
  1186. }
  1187. }
  1188. //-----------------------------------------------------------------------------
  1189. void SceneObject::setDefaultRestitution( const F32 restitution, const bool updateShapes )
  1190. {
  1191. mDefaultFixture.restitution = restitution;
  1192. // Early-out if not updating shapes.
  1193. if ( !updateShapes )
  1194. return;
  1195. if ( mpScene )
  1196. {
  1197. // Update live fixtures.
  1198. for( U32 index = 0; index < (U32)mCollisionFixtures.size(); ++index )
  1199. {
  1200. mCollisionFixtures[index]->SetRestitution( restitution );
  1201. }
  1202. return;
  1203. }
  1204. // Update offline fixture definitions.
  1205. for( U32 index = 0; index < (U32)mCollisionFixtureDefs.size(); ++index )
  1206. {
  1207. mCollisionFixtureDefs[index]->restitution = restitution;
  1208. }
  1209. }
  1210. //-----------------------------------------------------------------------------
  1211. void SceneObject::initializeContactGathering( void )
  1212. {
  1213. // Are we gathering contacts?
  1214. if ( !mGatherContacts )
  1215. {
  1216. // No, so do we have any current contacts?
  1217. if ( mpCurrentContacts )
  1218. {
  1219. // Yes, so destroy them.
  1220. delete mpCurrentContacts;
  1221. mpCurrentContacts = NULL;
  1222. }
  1223. return;
  1224. }
  1225. // Clear current contacts if already present.
  1226. if ( mpCurrentContacts != NULL )
  1227. {
  1228. mpCurrentContacts->clear();
  1229. return;
  1230. }
  1231. // Generate current contacts.
  1232. mpCurrentContacts = new Scene::typeContactVector();
  1233. }
  1234. //-----------------------------------------------------------------------------
  1235. void SceneObject::onBeginCollision( const TickContact& tickContact )
  1236. {
  1237. // Finish if we're not gathering contacts.
  1238. if ( !mGatherContacts )
  1239. return;
  1240. // Sanity!
  1241. AssertFatal( mpCurrentContacts != NULL, "SceneObject::onBeginCollision() - Contacts not initialized correctly." );
  1242. AssertFatal( tickContact.mpSceneObjectA == this || tickContact.mpSceneObjectB == this, "SceneObject::onBeginCollision() - Contact does not involve this scene object." );
  1243. // Keep contact.
  1244. mpCurrentContacts->push_back( tickContact );
  1245. }
  1246. //-----------------------------------------------------------------------------
  1247. void SceneObject::onEndCollision( const TickContact& tickContact )
  1248. {
  1249. // Finish if we're not gathering contacts.
  1250. if ( !mGatherContacts )
  1251. return;
  1252. // Sanity!
  1253. AssertFatal( mpCurrentContacts != NULL, "SceneObject::onBeginCollision() - Contacts not initialized correctly." );
  1254. AssertFatal( tickContact.mpSceneObjectA == this || tickContact.mpSceneObjectB == this, "SceneObject::onEndCollision() - Contact does not involve this scene object." );
  1255. // Remove contact.
  1256. for( Scene::typeContactVector::iterator contactItr = mpCurrentContacts->begin(); contactItr != mpCurrentContacts->end(); ++contactItr )
  1257. {
  1258. // Is this is the correct contact?
  1259. if ( contactItr->mpContact == tickContact.mpContact )
  1260. {
  1261. // Yes, so remove it.
  1262. mpCurrentContacts->erase_fast( contactItr );
  1263. return;
  1264. }
  1265. }
  1266. }
  1267. //-----------------------------------------------------------------------------
  1268. bool SceneObject::moveTo( const Vector2& targetWorldPoint, const F32 speed, const bool autoStop, const bool warpToTarget )
  1269. {
  1270. // Check in a scene.
  1271. if ( !getScene() )
  1272. {
  1273. Con::warnf("SceneObject::moveTo() - Cannot move object (%d) to a point as it is not in a scene.", getId() );
  1274. return false;
  1275. }
  1276. // Check not a static body.
  1277. if ( getBodyType() == b2_staticBody )
  1278. {
  1279. Con::warnf("SceneObject::moveTo() - Cannot move object (%d) to a point as it is a static body.", getId() );
  1280. return false;
  1281. }
  1282. // Check speed.
  1283. if ( speed <= 0.0f )
  1284. {
  1285. Con::warnf("SceneObject::moveTo() - Speed '%f' is invalid.", speed );
  1286. return false;
  1287. }
  1288. // Cancel any previous event.
  1289. if ( mMoveToEventId != 0 )
  1290. {
  1291. Sim::cancelEvent( mMoveToEventId );
  1292. mMoveToEventId = 0;
  1293. }
  1294. // Calculate the linear velocity for the specified speed.
  1295. Vector2 linearVelocity = targetWorldPoint - getPosition();
  1296. const F32 distance = linearVelocity.Normalize( speed );
  1297. // Calculate the time it will take to reach the target.
  1298. const U32 time = (U32)((distance / speed) * 1000.0f);
  1299. // Set the linear velocity.
  1300. setLinearVelocity( linearVelocity );
  1301. // Create and post event.
  1302. SceneObjectMoveToEvent* pEvent = new SceneObjectMoveToEvent( targetWorldPoint, autoStop, warpToTarget );
  1303. mMoveToEventId = Sim::postEvent(this, pEvent, Sim::getCurrentTime() + time );
  1304. return true;
  1305. }
  1306. //-----------------------------------------------------------------------------
  1307. bool SceneObject::rotateTo( const F32 targetAngle, const F32 speed, const bool autoStop, const bool warpToTarget )
  1308. {
  1309. // Check in a scene.
  1310. if ( !getScene() )
  1311. {
  1312. Con::warnf("SceneObject::rotateTo() - Cannot rotate object (%d) to an angle as it is not in a scene.", getId() );
  1313. return false;
  1314. }
  1315. // Check not a static body.
  1316. if ( getBodyType() == b2_staticBody )
  1317. {
  1318. Con::warnf("SceneObject::rotateTo() - Cannot move object (%d) to an angle as it is a static body.", getId() );
  1319. return false;
  1320. }
  1321. // Check speed.
  1322. if ( speed <= 0.0f )
  1323. {
  1324. Con::warnf("SceneObject::rotateTo() - Speed '%f' is invalid.", speed );
  1325. return false;
  1326. }
  1327. // Cancel any previous event.
  1328. if ( mRotateToEventId != 0 )
  1329. {
  1330. Sim::cancelEvent( mRotateToEventId );
  1331. mRotateToEventId = 0;
  1332. }
  1333. // Calculate relative angle.
  1334. const F32 relativeAngle = targetAngle - getAngle();
  1335. // Calculate delta angle.
  1336. const F32 deltaAngle = mAtan( mSin( relativeAngle ), mCos( relativeAngle ) );
  1337. // Set angular velocity.
  1338. setAngularVelocity( deltaAngle > 0.0f ? speed : -speed );
  1339. // Calculate the time it will take to reach the angle.
  1340. const U32 time = (U32)(mFabs(deltaAngle / speed) * 1000.0f);
  1341. // Create and post event.
  1342. SceneObjectRotateToEvent* pEvent = new SceneObjectRotateToEvent( targetAngle, autoStop, warpToTarget );
  1343. mRotateToEventId = Sim::postEvent(this, pEvent, Sim::getCurrentTime() + time );
  1344. return true;
  1345. }
  1346. //-----------------------------------------------------------------------------
  1347. void SceneObject::cancelMoveTo( const bool autoStop )
  1348. {
  1349. // Only cancel an active moveTo event
  1350. if ( mMoveToEventId != 0 )
  1351. {
  1352. Sim::cancelEvent( mMoveToEventId );
  1353. mMoveToEventId = 0;
  1354. // Should we auto stop?
  1355. if ( autoStop )
  1356. {
  1357. // Yes, so remove linear velocity
  1358. setLinearVelocity( Vector2::getZero() );
  1359. }
  1360. }
  1361. }
  1362. //-----------------------------------------------------------------------------
  1363. void SceneObject::cancelRotateTo( const bool autoStop )
  1364. {
  1365. // Only cancel an active rotateTo event
  1366. if ( mRotateToEventId != 0 )
  1367. {
  1368. Sim::cancelEvent( mRotateToEventId );
  1369. mRotateToEventId = 0;
  1370. // Should we auto stop?
  1371. if ( autoStop )
  1372. {
  1373. // Yes, so remove angular velocity
  1374. setAngularVelocity( 0.0f );
  1375. }
  1376. }
  1377. }
  1378. //-----------------------------------------------------------------------------
  1379. b2Shape::Type SceneObject::getCollisionShapeType( U32 shapeIndex ) const
  1380. {
  1381. // Sanity!
  1382. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::getCollisionShapeType() - Invalid shape index." );
  1383. if ( mpScene )
  1384. {
  1385. return mCollisionFixtures[shapeIndex]->GetType();
  1386. }
  1387. return mCollisionFixtureDefs[shapeIndex]->shape->GetType();
  1388. }
  1389. //-----------------------------------------------------------------------------
  1390. S32 SceneObject::getCollisionShapeIndex( const b2Fixture* pFixture ) const
  1391. {
  1392. // Iterate collision shapes.
  1393. S32 collisionShapeIndex = 0;
  1394. for( typeCollisionFixtureVector::const_iterator collisionShapeItr = mCollisionFixtures.begin(); collisionShapeItr != mCollisionFixtures.end(); ++collisionShapeItr, ++collisionShapeIndex )
  1395. {
  1396. // Return index if this is the collision shape we are searching for.
  1397. if ( pFixture == *collisionShapeItr )
  1398. return collisionShapeIndex;
  1399. }
  1400. // Not found.
  1401. return -1;
  1402. }
  1403. //-----------------------------------------------------------------------------
  1404. void SceneObject::setCollisionShapeDefinition( const U32 shapeIndex, const b2FixtureDef& fixtureDef )
  1405. {
  1406. // We only set specific features of a fixture definition here.
  1407. setCollisionShapeDensity( shapeIndex, fixtureDef.density );
  1408. setCollisionShapeFriction( shapeIndex, fixtureDef.friction );
  1409. setCollisionShapeRestitution( shapeIndex, fixtureDef.restitution );
  1410. setCollisionShapeIsSensor( shapeIndex, fixtureDef.isSensor );
  1411. }
  1412. //-----------------------------------------------------------------------------
  1413. b2FixtureDef SceneObject::getCollisionShapeDefinition( const U32 shapeIndex ) const
  1414. {
  1415. // Sanity!
  1416. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::getCollisionShapeDefinition() - Invalid shape index." );
  1417. if ( mpScene )
  1418. {
  1419. // Fetch fixture.
  1420. const b2Fixture* pFixture = mCollisionFixtures[shapeIndex];
  1421. b2FixtureDef fixtureDef;
  1422. fixtureDef.density = pFixture->GetDensity();
  1423. fixtureDef.friction = pFixture->GetFriction();
  1424. fixtureDef.restitution = pFixture->GetRestitution();
  1425. fixtureDef.isSensor = pFixture->IsSensor();
  1426. fixtureDef.filter = pFixture->GetFilterData();
  1427. fixtureDef.shape = pFixture->GetShape();
  1428. return fixtureDef;
  1429. }
  1430. return *mCollisionFixtureDefs[shapeIndex];
  1431. }
  1432. //-----------------------------------------------------------------------------
  1433. const b2CircleShape* SceneObject::getCollisionCircleShape( const U32 shapeIndex ) const
  1434. {
  1435. // Sanity!
  1436. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::getCollisionCircleShape() - Invalid shape index." );
  1437. // Fetch shape definition.
  1438. const b2FixtureDef fixtureDef = getCollisionShapeDefinition( shapeIndex );
  1439. // Sanity!
  1440. AssertFatal( fixtureDef.shape->GetType() == b2Shape::e_circle, "SceneObject::getCollisionCircleShape() - Shape is not a circle shape." );
  1441. // Fetch circle shape.
  1442. const b2CircleShape* pShape = dynamic_cast<const b2CircleShape*>( fixtureDef.shape );
  1443. // Sanity!
  1444. AssertFatal( pShape != NULL, "SceneObject::getCollisionCircleShape() - Invalid circle shape." );
  1445. return pShape;
  1446. }
  1447. //-----------------------------------------------------------------------------
  1448. const b2PolygonShape* SceneObject::getCollisionPolygonShape( const U32 shapeIndex ) const
  1449. {
  1450. // Sanity!
  1451. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::getCollisionPolygonShape() - Invalid shape index." );
  1452. // Fetch shape definition.
  1453. const b2FixtureDef fixtureDef = getCollisionShapeDefinition( shapeIndex );
  1454. // Sanity!
  1455. AssertFatal( fixtureDef.shape->GetType() == b2Shape::e_polygon, "SceneObject::getCollisionPolygonShape() - Shape is not a polygon shape." );
  1456. // Fetch shape.
  1457. const b2PolygonShape* pShape = dynamic_cast<const b2PolygonShape*>( fixtureDef.shape );
  1458. // Sanity!
  1459. AssertFatal( pShape != NULL, "SceneObject::getCollisionPolygonShape() - Invalid polygon shape." );
  1460. return pShape;
  1461. }
  1462. //-----------------------------------------------------------------------------
  1463. const b2ChainShape* SceneObject::getCollisionChainShape( const U32 shapeIndex ) const
  1464. {
  1465. // Sanity!
  1466. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::getCollisionChainShape() - Invalid shape index." );
  1467. // Fetch shape definition.
  1468. const b2FixtureDef fixtureDef = getCollisionShapeDefinition( shapeIndex );
  1469. // Sanity!
  1470. AssertFatal( fixtureDef.shape->GetType() == b2Shape::e_chain, "SceneObject::getCollisionChainShape() - Shape is not a chain shape." );
  1471. // Fetch shape.
  1472. const b2ChainShape* pShape = dynamic_cast<const b2ChainShape*>( fixtureDef.shape );
  1473. // Sanity!
  1474. AssertFatal( pShape != NULL, "SceneObject::getCollisionChainShape() - Invalid chain shape." );
  1475. return pShape;
  1476. }
  1477. //-----------------------------------------------------------------------------
  1478. const b2EdgeShape* SceneObject::getCollisionEdgeShape( const U32 shapeIndex ) const
  1479. {
  1480. // Sanity!
  1481. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::getCollisionEdgeShape() - Invalid shape index." );
  1482. // Fetch shape definition.
  1483. const b2FixtureDef fixtureDef = getCollisionShapeDefinition( shapeIndex );
  1484. // Sanity!
  1485. AssertFatal( fixtureDef.shape->GetType() == b2Shape::e_edge, "SceneObject::getCollisionEdgeShape() - Shape is not a edge shape." );
  1486. // Fetch shape.
  1487. const b2EdgeShape* pShape = dynamic_cast<const b2EdgeShape*>( fixtureDef.shape );
  1488. // Sanity!
  1489. AssertFatal( pShape != NULL, "SceneObject::getCollisionEdgeShape() - Invalid edge shape." );
  1490. return pShape;
  1491. }
  1492. //-----------------------------------------------------------------------------
  1493. void SceneObject::setCollisionShapeDensity( const U32 shapeIndex, const F32 density )
  1494. {
  1495. // Sanity!
  1496. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::setCollisionShapeDensity() - Invalid shape index." );
  1497. if ( mpScene )
  1498. {
  1499. // Update live fixture.
  1500. mCollisionFixtures[shapeIndex]->SetDensity( density );
  1501. // Update the body mass data.
  1502. mpBody->ResetMassData();
  1503. return;
  1504. }
  1505. // Update offline fixture definition.
  1506. mCollisionFixtureDefs[shapeIndex]->density = density;
  1507. }
  1508. //-----------------------------------------------------------------------------
  1509. F32 SceneObject::getCollisionShapeDensity( const U32 shapeIndex ) const
  1510. {
  1511. // Sanity!
  1512. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::getCollisionShapeDensity() - Invalid shape index." );
  1513. if ( mpScene )
  1514. {
  1515. // Use live fixture.
  1516. return mCollisionFixtures[shapeIndex]->GetDensity();
  1517. }
  1518. // Use offline fixture definition.
  1519. return mCollisionFixtureDefs[shapeIndex]->density;
  1520. }
  1521. //-----------------------------------------------------------------------------
  1522. void SceneObject::setCollisionShapeFriction( const U32 shapeIndex, const F32 friction )
  1523. {
  1524. // Sanity!
  1525. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::setCollisionShapeFriction() - Invalid shape index." );
  1526. if ( mpScene )
  1527. {
  1528. // Fetch the fixture.
  1529. b2Fixture* pFixture = mCollisionFixtures[shapeIndex];
  1530. // Update live fixture.
  1531. pFixture->SetFriction( friction );
  1532. // Re-filter fixture.
  1533. pFixture->Refilter();
  1534. return;
  1535. }
  1536. // Update offline fixture definition.
  1537. mCollisionFixtureDefs[shapeIndex]->friction = friction;
  1538. }
  1539. //-----------------------------------------------------------------------------
  1540. F32 SceneObject::getCollisionShapeFriction( const U32 shapeIndex ) const
  1541. {
  1542. // Sanity!
  1543. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::getCollisionShapeFriction() - Invalid shape index." );
  1544. if ( mpScene )
  1545. {
  1546. // Use live fixture.
  1547. return mCollisionFixtures[shapeIndex]->GetFriction();
  1548. }
  1549. // Use offline fixture definition.
  1550. return mCollisionFixtureDefs[shapeIndex]->friction;
  1551. }
  1552. //-----------------------------------------------------------------------------
  1553. void SceneObject::setCollisionShapeRestitution( const U32 shapeIndex, const F32 restitution )
  1554. {
  1555. // Sanity!
  1556. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::setCollisionShapeRestitution() - Invalid shape index." );
  1557. if ( mpScene )
  1558. {
  1559. // Fetch the fixture.
  1560. b2Fixture* pFixture = mCollisionFixtures[shapeIndex];
  1561. // Update live fixture.
  1562. pFixture->SetRestitution( restitution );
  1563. // Re-filter fixture.
  1564. pFixture->Refilter();
  1565. return;
  1566. }
  1567. // Update offline fixture definition.
  1568. mCollisionFixtureDefs[shapeIndex]->restitution = restitution;
  1569. }
  1570. //-----------------------------------------------------------------------------
  1571. F32 SceneObject::getCollisionShapeRestitution( const U32 shapeIndex ) const
  1572. {
  1573. // Sanity!
  1574. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::getCollisionShapeRestitution() - Invalid shape index." );
  1575. if ( mpScene )
  1576. {
  1577. // Use live fixture.
  1578. return mCollisionFixtures[shapeIndex]->GetRestitution();
  1579. }
  1580. // Use offline fixture definition.
  1581. return mCollisionFixtureDefs[shapeIndex]->restitution;
  1582. }
  1583. //-----------------------------------------------------------------------------
  1584. void SceneObject::setCollisionShapeIsSensor( const U32 shapeIndex, const bool isSensor )
  1585. {
  1586. // Sanity!
  1587. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::setCollisionShapeIsSensor() - Invalid shape index." );
  1588. if ( mpScene )
  1589. {
  1590. // Fetch the fixture.
  1591. b2Fixture* pFixture = mCollisionFixtures[shapeIndex];
  1592. // Update live fixture.
  1593. pFixture->SetSensor( isSensor );
  1594. // Re-filter fixture.
  1595. pFixture->Refilter();
  1596. return;
  1597. }
  1598. // Update offline fixture definition.
  1599. mCollisionFixtureDefs[shapeIndex]->isSensor = isSensor;
  1600. }
  1601. //-----------------------------------------------------------------------------
  1602. bool SceneObject::getCollisionShapeIsSensor( const U32 shapeIndex ) const
  1603. {
  1604. // Sanity!
  1605. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::getCollisionShapeIsSensor() - Invalid shape index." );
  1606. if ( mpScene )
  1607. {
  1608. // Use live fixture.
  1609. return mCollisionFixtures[shapeIndex]->IsSensor();
  1610. }
  1611. // Use offline fixture definition.
  1612. return mCollisionFixtureDefs[shapeIndex]->isSensor;
  1613. }
  1614. //-----------------------------------------------------------------------------
  1615. void SceneObject::deleteCollisionShape( const U32 shapeIndex )
  1616. {
  1617. // Sanity!
  1618. AssertFatal( shapeIndex < getCollisionShapeCount(), "SceneObject::deleteCollisionShape() - Invalid shape index." );
  1619. if ( mpScene )
  1620. {
  1621. mpBody->DestroyFixture( mCollisionFixtures[ shapeIndex ] );
  1622. mCollisionFixtures.erase_fast( shapeIndex );
  1623. return;
  1624. }
  1625. mCollisionFixtureDefs.erase_fast( shapeIndex );
  1626. }
  1627. //-----------------------------------------------------------------------------
  1628. void SceneObject::clearCollisionShapes( void )
  1629. {
  1630. // Delete all collision shapes.
  1631. while ( getCollisionShapeCount() > 0 )
  1632. {
  1633. deleteCollisionShape( 0 );
  1634. }
  1635. }
  1636. //-----------------------------------------------------------------------------
  1637. S32 SceneObject::createCircleCollisionShape( const F32 radius )
  1638. {
  1639. // Debug Profiling.
  1640. PROFILE_SCOPE(SceneObject_CreateCircleCollisionShape);
  1641. return createCircleCollisionShape( radius, b2Vec2(0.0f, 0.0f) );
  1642. }
  1643. //-----------------------------------------------------------------------------
  1644. S32 SceneObject::createCircleCollisionShape( const F32 radius, const b2Vec2& localPosition )
  1645. {
  1646. // Sanity!
  1647. if ( radius <= 0.0f )
  1648. {
  1649. Con::errorf("SceneObject::createCircleCollisionShape() - Invalid radius of %g.", radius);
  1650. return -1;
  1651. }
  1652. // Configure fixture definition.
  1653. b2FixtureDef* pFixtureDef = new b2FixtureDef( mDefaultFixture );
  1654. b2CircleShape* pShape = new b2CircleShape();
  1655. pShape->m_p = localPosition;
  1656. pShape->m_radius = radius;
  1657. pFixtureDef->shape = pShape;
  1658. if ( mpScene )
  1659. {
  1660. // Create and push fixture.
  1661. mCollisionFixtures.push_back( mpBody->CreateFixture( pFixtureDef ) );
  1662. // Destroy shape and fixture.
  1663. delete pShape;
  1664. delete pFixtureDef;
  1665. return mCollisionFixtures.size()-1;
  1666. }
  1667. // Push fixture definition.
  1668. mCollisionFixtureDefs.push_back( pFixtureDef );
  1669. return mCollisionFixtureDefs.size()-1;
  1670. }
  1671. //-----------------------------------------------------------------------------
  1672. F32 SceneObject::getCircleCollisionShapeRadius( const U32 shapeIndex ) const
  1673. {
  1674. // Fetch shape.
  1675. const b2CircleShape* pShape = getCollisionCircleShape( shapeIndex );
  1676. return pShape->m_radius;
  1677. }
  1678. //-----------------------------------------------------------------------------
  1679. Vector2 SceneObject::getCircleCollisionShapeLocalPosition( const U32 shapeIndex ) const
  1680. {
  1681. // Fetch shape.
  1682. const b2CircleShape* pShape = getCollisionCircleShape( shapeIndex );
  1683. return pShape->m_p;
  1684. }
  1685. //-----------------------------------------------------------------------------
  1686. S32 SceneObject::createPolygonCollisionShape( const U32 pointCount, const b2Vec2* localPoints )
  1687. {
  1688. // Debug Profiling.
  1689. PROFILE_SCOPE(SceneObject_CreatePolygonCollisionShape);
  1690. // Sanity!
  1691. if ( pointCount < 3 || pointCount > b2_maxPolygonVertices )
  1692. {
  1693. Con::errorf("SceneObject::createPolygonCollisionShape() - Invalid point count of %d.", pointCount);
  1694. return -1;
  1695. }
  1696. // Configure fixture definition.
  1697. b2FixtureDef* pFixtureDef = new b2FixtureDef( mDefaultFixture );
  1698. b2PolygonShape* pShape = new b2PolygonShape();
  1699. pShape->Set( localPoints, pointCount );
  1700. pFixtureDef->shape = pShape;
  1701. if ( mpScene )
  1702. {
  1703. // Create and push fixture.
  1704. mCollisionFixtures.push_back( mpBody->CreateFixture( pFixtureDef ) );
  1705. // Destroy shape and fixture.
  1706. delete pShape;
  1707. delete pFixtureDef;
  1708. return mCollisionFixtures.size()-1;
  1709. }
  1710. // Push fixture definition.
  1711. mCollisionFixtureDefs.push_back( pFixtureDef );
  1712. return mCollisionFixtureDefs.size()-1;
  1713. }
  1714. //-----------------------------------------------------------------------------
  1715. S32 SceneObject::createPolygonBoxCollisionShape( const F32 width, const F32 height )
  1716. {
  1717. // Debug Profiling.
  1718. PROFILE_SCOPE(SceneObject_CreatePolygonBoxCollisionShapeWidthHeight);
  1719. // Sanity!
  1720. if ( width <= 0.0f )
  1721. {
  1722. Con::errorf("SceneObject::createPolygonBoxCollisionShape() - Invalid width of %g.", width);
  1723. return -1;
  1724. }
  1725. if ( height <= 0.0f )
  1726. {
  1727. Con::errorf("SceneObject::createPolygonBoxCollisionShape() - Invalid height of %g.", height);
  1728. return -1;
  1729. }
  1730. // Configure fixture definition.
  1731. b2FixtureDef* pFixtureDef = new b2FixtureDef( mDefaultFixture );
  1732. b2PolygonShape* pShape = new b2PolygonShape();
  1733. pShape->SetAsBox( width * 0.5f, height * 0.5f );
  1734. pFixtureDef->shape = pShape;
  1735. if ( mpScene )
  1736. {
  1737. // Create and push fixture.
  1738. mCollisionFixtures.push_back( mpBody->CreateFixture( pFixtureDef ) );
  1739. // Destroy shape and fixture.
  1740. delete pShape;
  1741. delete pFixtureDef;
  1742. return mCollisionFixtures.size()-1;
  1743. }
  1744. // Push fixture definition.
  1745. mCollisionFixtureDefs.push_back( pFixtureDef );
  1746. return mCollisionFixtureDefs.size()-1;
  1747. }
  1748. //-----------------------------------------------------------------------------
  1749. S32 SceneObject::createPolygonBoxCollisionShape( const F32 width, const F32 height, const b2Vec2& localCentroid )
  1750. {
  1751. // Debug Profiling.
  1752. PROFILE_SCOPE(SceneObject_CreatePolygonBoxCollisionShapeWidthHeightCentroid);
  1753. // Sanity!
  1754. if ( width <= 0.0f )
  1755. {
  1756. Con::errorf("SceneObject::createPolygonBoxCollisionShape() - Invalid width of %g.", width);
  1757. return -1;
  1758. }
  1759. if ( height <= 0.0f )
  1760. {
  1761. Con::errorf("SceneObject::createPolygonBoxCollisionShape() - Invalid height of %g.", height);
  1762. return -1;
  1763. }
  1764. // Configure fixture definition.
  1765. b2FixtureDef* pFixtureDef = new b2FixtureDef( mDefaultFixture );
  1766. b2PolygonShape* pShape = new b2PolygonShape();
  1767. pShape->SetAsBox( width * 0.5f, height * 0.5f, localCentroid, 0.0f );
  1768. pFixtureDef->shape = pShape;
  1769. if ( mpScene )
  1770. {
  1771. // Create and push fixture.
  1772. mCollisionFixtures.push_back( mpBody->CreateFixture( pFixtureDef ) );
  1773. // Destroy shape and fixture.
  1774. delete pShape;
  1775. delete pFixtureDef;
  1776. return mCollisionFixtures.size()-1;
  1777. }
  1778. // Push fixture definition.
  1779. mCollisionFixtureDefs.push_back( pFixtureDef );
  1780. return mCollisionFixtureDefs.size()-1;
  1781. }
  1782. //-----------------------------------------------------------------------------
  1783. S32 SceneObject::createPolygonBoxCollisionShape( const F32 width, const F32 height, const b2Vec2& localCentroid, const F32 rotation )
  1784. {
  1785. // Debug Profiling.
  1786. PROFILE_SCOPE(SceneObject_CreatePolygonBoxCollisionShapeWidthHeightCentroidRotation);
  1787. // Sanity!
  1788. if ( width <= 0.0f )
  1789. {
  1790. Con::errorf("SceneObject::createPolygonBoxCollisionShape() - Invalid width of %g.", width);
  1791. return -1;
  1792. }
  1793. if ( height <= 0.0f )
  1794. {
  1795. Con::errorf("SceneObject::createPolygonBoxCollisionShape() - Invalid height of %g.", height);
  1796. return -1;
  1797. }
  1798. // Configure fixture definition.
  1799. b2FixtureDef* pFixtureDef = new b2FixtureDef( mDefaultFixture );
  1800. b2PolygonShape* pShape = new b2PolygonShape();
  1801. pShape->SetAsBox( width * 0.5f, height * 0.5f, localCentroid, rotation );
  1802. pFixtureDef->shape = pShape;
  1803. if ( mpScene )
  1804. {
  1805. // Create and push fixture.
  1806. mCollisionFixtures.push_back( mpBody->CreateFixture( pFixtureDef ) );
  1807. // Destroy shape and fixture.
  1808. delete pShape;
  1809. delete pFixtureDef;
  1810. return mCollisionFixtures.size()-1;
  1811. }
  1812. // Push fixture definition.
  1813. mCollisionFixtureDefs.push_back( pFixtureDef );
  1814. return mCollisionFixtureDefs.size()-1;
  1815. }
  1816. //-----------------------------------------------------------------------------
  1817. U32 SceneObject::getPolygonCollisionShapePointCount( const U32 shapeIndex ) const
  1818. {
  1819. // Fetch shape.
  1820. const b2PolygonShape* pShape = getCollisionPolygonShape( shapeIndex );
  1821. return pShape->GetVertexCount();
  1822. }
  1823. //-----------------------------------------------------------------------------
  1824. Vector2 SceneObject::getPolygonCollisionShapeLocalPoint( const U32 shapeIndex, const U32 pointIndex ) const
  1825. {
  1826. // Fetch shape.
  1827. const b2PolygonShape* pShape = getCollisionPolygonShape( shapeIndex );
  1828. // Sanity!
  1829. AssertFatal( pointIndex < (U32)pShape->GetVertexCount(), "SceneObject::getPolygonCollisionShapeLocalPoint() - Invalid local point index." );
  1830. return pShape->GetVertex( pointIndex );
  1831. }
  1832. //-----------------------------------------------------------------------------
  1833. S32 SceneObject::createChainCollisionShape( const U32 pointCount, const b2Vec2* localPoints )
  1834. {
  1835. // Debug Profiling.
  1836. PROFILE_SCOPE(SceneObject_CreateChainCollisionShape);
  1837. // Sanity!
  1838. if ( pointCount < 2 )
  1839. {
  1840. Con::errorf("SceneObject::createChainCollisionShape() - Invalid point count of %d.", pointCount);
  1841. return -1;
  1842. }
  1843. // Configure fixture definition.
  1844. b2FixtureDef* pFixtureDef = new b2FixtureDef( mDefaultFixture );
  1845. b2ChainShape* pShape = new b2ChainShape();
  1846. pShape->CreateChain( localPoints, pointCount );
  1847. pFixtureDef->shape = pShape;
  1848. if ( mpScene )
  1849. {
  1850. // Create and push fixture.
  1851. mCollisionFixtures.push_back( mpBody->CreateFixture( pFixtureDef ) );
  1852. // Destroy shape and fixture.
  1853. delete pShape;
  1854. delete pFixtureDef;
  1855. return mCollisionFixtures.size()-1;
  1856. }
  1857. // Push fixture definition.
  1858. mCollisionFixtureDefs.push_back( pFixtureDef );
  1859. return mCollisionFixtureDefs.size()-1;
  1860. }
  1861. //-----------------------------------------------------------------------------
  1862. S32 SceneObject::createChainCollisionShape( const U32 pointCount, const b2Vec2* localPoints,
  1863. const bool hasAdjacentLocalPositionStart, const bool hasAdjacentLocalPositionEnd,
  1864. const b2Vec2& adjacentLocalPositionStart, const b2Vec2& adjacentLocalPositionEnd )
  1865. {
  1866. // Debug Profiling.
  1867. PROFILE_SCOPE(SceneObject_CreateChainCollisionShapeAdjacents);
  1868. // Sanity!
  1869. if ( pointCount < 2 )
  1870. {
  1871. Con::errorf("SceneObject::createChainCollisionShape() - Invalid point count of %d.", pointCount);
  1872. return -1;
  1873. }
  1874. // Configure fixture definition.
  1875. b2FixtureDef* pFixtureDef = new b2FixtureDef( mDefaultFixture );
  1876. b2ChainShape* pShape = new b2ChainShape();
  1877. pShape->CreateChain( localPoints, pointCount );
  1878. if ( hasAdjacentLocalPositionStart )
  1879. pShape->SetPrevVertex( adjacentLocalPositionStart );
  1880. if ( hasAdjacentLocalPositionEnd )
  1881. pShape->SetNextVertex( adjacentLocalPositionEnd );
  1882. pFixtureDef->shape = pShape;
  1883. if ( mpScene )
  1884. {
  1885. // Create and push fixture.
  1886. mCollisionFixtures.push_back( mpBody->CreateFixture( pFixtureDef ) );
  1887. // Destroy shape and fixture.
  1888. delete pShape;
  1889. delete pFixtureDef;
  1890. return mCollisionFixtures.size()-1;
  1891. }
  1892. // Push fixture definition.
  1893. mCollisionFixtureDefs.push_back( pFixtureDef );
  1894. return mCollisionFixtureDefs.size()-1;
  1895. }
  1896. //-----------------------------------------------------------------------------
  1897. U32 SceneObject::getChainCollisionShapePointCount( const U32 shapeIndex ) const
  1898. {
  1899. // Fetch shape.
  1900. const b2ChainShape* pShape = getCollisionChainShape( shapeIndex );
  1901. return pShape->m_count;
  1902. }
  1903. //-----------------------------------------------------------------------------
  1904. Vector2 SceneObject::getChainCollisionShapeLocalPoint( const U32 shapeIndex, const U32 pointIndex ) const
  1905. {
  1906. // Fetch shape.
  1907. const b2ChainShape* pShape = getCollisionChainShape( shapeIndex );
  1908. // Sanity!
  1909. AssertFatal( pointIndex < (U32)pShape->m_count, "SceneObject::getChainCollisionShapeLocalPoint() - Invalid local point index." );
  1910. return pShape->m_vertices[ pointIndex ];
  1911. }
  1912. //-----------------------------------------------------------------------------
  1913. bool SceneObject::getChainCollisionShapeHasAdjacentStart( const U32 shapeIndex ) const
  1914. {
  1915. // Fetch shape.
  1916. const b2ChainShape* pShape = getCollisionChainShape( shapeIndex );
  1917. return pShape->m_hasPrevVertex;
  1918. }
  1919. //-----------------------------------------------------------------------------
  1920. bool SceneObject::getChainCollisionShapeHasAdjacentEnd( const U32 shapeIndex ) const
  1921. {
  1922. // Fetch shape.
  1923. const b2ChainShape* pShape = getCollisionChainShape( shapeIndex );
  1924. return pShape->m_hasNextVertex;
  1925. }
  1926. //-----------------------------------------------------------------------------
  1927. Vector2 SceneObject::getChainCollisionShapeAdjacentStart( const U32 shapeIndex ) const
  1928. {
  1929. // Fetch shape.
  1930. const b2ChainShape* pShape = getCollisionChainShape( shapeIndex );
  1931. return pShape->m_prevVertex;
  1932. }
  1933. //-----------------------------------------------------------------------------
  1934. Vector2 SceneObject::getChainCollisionShapeAdjacentEnd( const U32 shapeIndex ) const
  1935. {
  1936. // Fetch shape.
  1937. const b2ChainShape* pShape = getCollisionChainShape( shapeIndex );
  1938. return pShape->m_nextVertex;
  1939. }
  1940. //-----------------------------------------------------------------------------
  1941. S32 SceneObject::createEdgeCollisionShape( const b2Vec2& localPositionStart, const b2Vec2& localPositionEnd )
  1942. {
  1943. // Debug Profiling.
  1944. PROFILE_SCOPE(SceneObject_CreateEdgeCollisionShape);
  1945. // Configure fixture definition.
  1946. b2FixtureDef* pFixtureDef = new b2FixtureDef( mDefaultFixture );
  1947. b2EdgeShape* pShape = new b2EdgeShape();
  1948. pShape->Set( localPositionStart, localPositionEnd );
  1949. pFixtureDef->shape = pShape;
  1950. if ( mpScene )
  1951. {
  1952. // Create and push fixture.
  1953. mCollisionFixtures.push_back( mpBody->CreateFixture( pFixtureDef ) );
  1954. // Destroy shape and fixture.
  1955. delete pShape;
  1956. delete pFixtureDef;
  1957. return mCollisionFixtures.size()-1;
  1958. }
  1959. // Push fixture definition.
  1960. mCollisionFixtureDefs.push_back( pFixtureDef );
  1961. return mCollisionFixtureDefs.size()-1;
  1962. }
  1963. //-----------------------------------------------------------------------------
  1964. S32 SceneObject::createEdgeCollisionShape( const b2Vec2& localPositionStart, const b2Vec2& localPositionEnd,
  1965. const bool hasAdjacentLocalPositionStart, const bool hasAdjacentLocalPositionEnd,
  1966. const b2Vec2& adjacentLocalPositionStart, const b2Vec2& adjacentLocalPositionEnd )
  1967. {
  1968. // Debug Profiling.
  1969. PROFILE_SCOPE(SceneObject_CreateEdgeCollisionShapeAdjacents);
  1970. // Configure fixture definition.
  1971. b2FixtureDef* pFixtureDef = new b2FixtureDef( mDefaultFixture );
  1972. b2EdgeShape* pShape = new b2EdgeShape();
  1973. pShape->Set( localPositionStart, localPositionEnd );
  1974. pShape->m_hasVertex0 = hasAdjacentLocalPositionStart;
  1975. pShape->m_hasVertex3 = hasAdjacentLocalPositionEnd;
  1976. pShape->m_vertex0 = adjacentLocalPositionStart;
  1977. pShape->m_vertex3 = adjacentLocalPositionEnd;
  1978. pFixtureDef->shape = pShape;
  1979. if ( mpScene )
  1980. {
  1981. // Create and push fixture.
  1982. mCollisionFixtures.push_back( mpBody->CreateFixture( pFixtureDef ) );
  1983. // Destroy shape and fixture.
  1984. delete pShape;
  1985. delete pFixtureDef;
  1986. return mCollisionFixtures.size()-1;
  1987. }
  1988. // Push fixture definition.
  1989. mCollisionFixtureDefs.push_back( pFixtureDef );
  1990. return mCollisionFixtureDefs.size()-1;
  1991. }
  1992. //-----------------------------------------------------------------------------
  1993. Vector2 SceneObject::getEdgeCollisionShapeLocalPositionStart( const U32 shapeIndex ) const
  1994. {
  1995. // Fetch shape.
  1996. const b2EdgeShape* pShape = getCollisionEdgeShape( shapeIndex );
  1997. return pShape->m_vertex1;
  1998. }
  1999. //-----------------------------------------------------------------------------
  2000. Vector2 SceneObject::getEdgeCollisionShapeLocalPositionEnd( const U32 shapeIndex ) const
  2001. {
  2002. // Fetch shape.
  2003. const b2EdgeShape* pShape = getCollisionEdgeShape( shapeIndex );
  2004. return pShape->m_vertex2;
  2005. }
  2006. //-----------------------------------------------------------------------------
  2007. bool SceneObject::getEdgeCollisionShapeHasAdjacentStart( const U32 shapeIndex ) const
  2008. {
  2009. // Fetch shape.
  2010. const b2EdgeShape* pShape = getCollisionEdgeShape( shapeIndex );
  2011. return pShape->m_hasVertex0;
  2012. }
  2013. //-----------------------------------------------------------------------------
  2014. bool SceneObject::getEdgeCollisionShapeHasAdjacentEnd( const U32 shapeIndex ) const
  2015. {
  2016. // Fetch shape.
  2017. const b2EdgeShape* pShape = getCollisionEdgeShape( shapeIndex );
  2018. return pShape->m_hasVertex3;
  2019. }
  2020. //-----------------------------------------------------------------------------
  2021. Vector2 SceneObject::getEdgeCollisionShapeAdjacentStart( const U32 shapeIndex ) const
  2022. {
  2023. // Fetch shape.
  2024. const b2EdgeShape* pShape = getCollisionEdgeShape( shapeIndex );
  2025. return pShape->m_vertex0;
  2026. }
  2027. //-----------------------------------------------------------------------------
  2028. Vector2 SceneObject::getEdgeCollisionShapeAdjacentEnd( const U32 shapeIndex ) const
  2029. {
  2030. // Fetch shape.
  2031. const b2EdgeShape* pShape = getCollisionEdgeShape( shapeIndex );
  2032. return pShape->m_vertex3;
  2033. }
  2034. //-----------------------------------------------------------------------------
  2035. void SceneObject::setBlendOptions( void )
  2036. {
  2037. // Set Blend Status.
  2038. if ( mBlendMode )
  2039. {
  2040. // Enable Blending.
  2041. glEnable( GL_BLEND );
  2042. // Set Blend Function.
  2043. glBlendFunc( mSrcBlendFactor, mDstBlendFactor );
  2044. // Set Colour.
  2045. glColor4f(mBlendColor.red,mBlendColor.green,mBlendColor.blue,mBlendColor.alpha );
  2046. }
  2047. else
  2048. {
  2049. // Disable Blending.
  2050. glDisable( GL_BLEND );
  2051. // Reset Colour.
  2052. glColor4f(1,1,1,1);
  2053. }
  2054. // Set Alpha Test.
  2055. if ( mAlphaTest >= 0.0f )
  2056. {
  2057. // Enable Test.
  2058. glEnable( GL_ALPHA_TEST );
  2059. glAlphaFunc( GL_GREATER, mAlphaTest );
  2060. }
  2061. else
  2062. {
  2063. // Disable Test.
  2064. glDisable( GL_ALPHA_TEST );
  2065. }
  2066. }
  2067. //-----------------------------------------------------------------------------
  2068. void SceneObject::resetBlendOptions( void )
  2069. {
  2070. // Disable Blending.
  2071. glDisable( GL_BLEND );
  2072. glDisable( GL_ALPHA_TEST);
  2073. // Reset Colour.
  2074. glColor4f(1,1,1,1);
  2075. }
  2076. //---------------------------------------------------------------------------------------------
  2077. void SceneObject::onInputEvent( StringTableEntry name, const GuiEvent& event, const Vector2& worldMousePosition )
  2078. {
  2079. // Debug Profiling.
  2080. PROFILE_SCOPE(SceneObject_OnInputEvent);
  2081. // Argument Buffers.
  2082. char argBuffer[3][32];
  2083. // ID
  2084. dSprintf(argBuffer[0], 32, "%d", event.eventID);
  2085. // Format Mouse-Position Buffer.
  2086. dSprintf(argBuffer[1], 32, "%g %g", worldMousePosition.x, worldMousePosition.y);
  2087. // Optional double click
  2088. dSprintf(argBuffer[2], 32, "%d", event.mouseClickCount);
  2089. // Call Scripts.
  2090. Con::executef(this, 4, name, argBuffer[0], argBuffer[1], argBuffer[2]);
  2091. }
  2092. //-----------------------------------------------------------------------------
  2093. void SceneObject::attachGui( GuiControl* pGuiControl, SceneWindow* pSceneWindow, const bool sizeControl )
  2094. {
  2095. // Attach Gui Control.
  2096. mpAttachedGui = pGuiControl;
  2097. // Attach SceneWindow.
  2098. mpAttachedGuiSceneWindow = pSceneWindow;
  2099. // Set Size Gui Flag.
  2100. mAttachedGuiSizeControl = sizeControl;
  2101. // Register Gui Control/Window References.
  2102. mpAttachedGui->registerReference( (SimObject**)&mpAttachedGui );
  2103. mpAttachedGuiSceneWindow->registerReference( (SimObject**)&mpAttachedGuiSceneWindow );
  2104. // Check/Adjust Parentage.
  2105. if ( mpAttachedGui->getParent() != mpAttachedGuiSceneWindow )
  2106. {
  2107. // Warn.
  2108. // Remove GuiControl from existing parent (if it has one).
  2109. if ( mpAttachedGui->getParent() )
  2110. {
  2111. mpAttachedGui->getParent()->removeObject( mpAttachedGui );
  2112. }
  2113. // Add it to the scene-window.
  2114. mpAttachedGuiSceneWindow->addObject( mpAttachedGui );
  2115. }
  2116. }
  2117. //-----------------------------------------------------------------------------
  2118. void SceneObject::detachGui( void )
  2119. {
  2120. // Unregister Gui Control Reference.
  2121. if ( mpAttachedGui )
  2122. {
  2123. // [neo, 5/7/2007 - #2997]
  2124. // Changed to UNregisterReference was registerReference which would crash later
  2125. mpAttachedGui->unregisterReference( (SimObject**)&mpAttachedGui );
  2126. mpAttachedGui = NULL;
  2127. }
  2128. // Unregister Gui Control Reference.
  2129. if ( mpAttachedGuiSceneWindow )
  2130. {
  2131. mpAttachedGuiSceneWindow->registerReference( (SimObject**)&mpAttachedGuiSceneWindow );
  2132. mpAttachedGuiSceneWindow = NULL;
  2133. }
  2134. }
  2135. //-----------------------------------------------------------------------------
  2136. void SceneObject::updateAttachedGui( void )
  2137. {
  2138. // Debug Profiling.
  2139. PROFILE_SCOPE(SceneObject_updateAttachedGui);
  2140. // Finish if either Gui Control or Window is invalid.
  2141. if ( !mpAttachedGui || !mpAttachedGuiSceneWindow )
  2142. return;
  2143. // Ignore if we're not in the scene that the scene-window is attached to.
  2144. if ( getScene() != mpAttachedGuiSceneWindow->getScene() )
  2145. {
  2146. // Warn.
  2147. Con::warnf("SceneObject::updateAttachedGui() - SceneWindow is not attached to my Scene!");
  2148. // Detach from GUI Control.
  2149. detachGui();
  2150. // Finish Here.
  2151. return;
  2152. }
  2153. // Calculate the GUI Controls' dimensions.
  2154. Point2I topLeftI, extentI;
  2155. // Size Control?
  2156. if ( mAttachedGuiSizeControl )
  2157. {
  2158. // Yes, so fetch Clip Rectangle; this forms the area we want to fix the Gui-Control to.
  2159. const RectF objAABB = getAABBRectangle();
  2160. // Fetch Top-Left.
  2161. Vector2 upperLeft = Vector2( objAABB.point.x, objAABB.point.y + objAABB.extent.y );
  2162. Vector2 lowerRight = Vector2( objAABB.point.x + objAABB.extent.x, objAABB.point.y );
  2163. // Convert Scene to Window Coordinates.
  2164. mpAttachedGuiSceneWindow->sceneToWindowPoint( upperLeft, upperLeft );
  2165. mpAttachedGuiSceneWindow->sceneToWindowPoint( lowerRight, lowerRight );
  2166. // Convert Control Dimensions.
  2167. topLeftI.set( S32(upperLeft.x), S32(upperLeft.y) );
  2168. extentI.set( S32(lowerRight.x-upperLeft.x), S32(lowerRight.y-upperLeft.y) );
  2169. }
  2170. else
  2171. {
  2172. // No, so center GUI-Control on objects position but don't resize it.
  2173. // Calculate Position from World Clip.
  2174. const RectF clipRectangle = getAABBRectangle();
  2175. // Calculate center position.
  2176. const Vector2 centerPosition = clipRectangle.point + Vector2(clipRectangle.len_x()*0.5f, clipRectangle.len_y()*0.5f);
  2177. // Convert Scene to Window Coordinates.
  2178. Vector2 positionI;
  2179. mpAttachedGuiSceneWindow->sceneToWindowPoint( centerPosition, positionI );
  2180. // Fetch Control Extents (which don't change here).
  2181. extentI = mpAttachedGui->getExtent();
  2182. // Calculate new top-left.
  2183. topLeftI.set( S32(positionI.x-extentI.x/2), S32(positionI.y-extentI.y/2) );
  2184. }
  2185. // Set Control Dimensions.
  2186. mpAttachedGui->resize( topLeftI, extentI );
  2187. }
  2188. //-----------------------------------------------------------------------------
  2189. void SceneObject::copyFrom( SceneObject* pSceneObject, const bool copyDynamicFields )
  2190. {
  2191. // Copy the specified object.
  2192. pSceneObject->copyTo( this );
  2193. // Copy over dynamic fields if requested.
  2194. if ( copyDynamicFields )
  2195. pSceneObject->assignDynamicFieldsFrom( this );
  2196. }
  2197. //-----------------------------------------------------------------------------
  2198. void SceneObject::copyTo( SimObject* obj )
  2199. {
  2200. // Debug Profiling.
  2201. PROFILE_SCOPE(SceneObject_CopyTo);
  2202. // Call parent.
  2203. Parent::copyTo(obj);
  2204. // Fetch object.
  2205. SceneObject* pSceneObject = dynamic_cast<SceneObject*>(obj);
  2206. // Sanity!
  2207. AssertFatal(pSceneObject != NULL, "SceneObject::copyTo() - Object is not the correct type.");
  2208. /// Lifetime.
  2209. pSceneObject->setLifetime( getLifetime() );
  2210. /// Scene Layers.
  2211. pSceneObject->setSceneLayer( getSceneLayer() );
  2212. /// Scene groups.
  2213. pSceneObject->setSceneGroup( getSceneGroup() );
  2214. /// Area.
  2215. pSceneObject->setSize( getSize() );
  2216. /// Position / Angle.
  2217. pSceneObject->setPosition( getPosition() );
  2218. pSceneObject->setAngle( getAngle() );
  2219. pSceneObject->setFixedAngle( getFixedAngle() );
  2220. /// Body.
  2221. pSceneObject->setBodyType( getBodyType() );
  2222. pSceneObject->setActive( getActive() );
  2223. pSceneObject->setAwake( getAwake() );
  2224. pSceneObject->setBullet( getBullet() );
  2225. pSceneObject->setSleepingAllowed( getSleepingAllowed() );
  2226. /// Collision control.
  2227. pSceneObject->setCollisionGroups( getCollisionGroupMask() );
  2228. pSceneObject->setCollisionLayers( getCollisionLayerMask() );
  2229. pSceneObject->setCollisionSuppress( getCollisionSuppress() );
  2230. pSceneObject->setGatherContacts( getGatherContacts() );
  2231. pSceneObject->setDefaultDensity( getDefaultDensity() );
  2232. pSceneObject->setDefaultFriction( getDefaultFriction() );
  2233. pSceneObject->setDefaultRestitution( getDefaultRestitution() );
  2234. /// Velocities.
  2235. pSceneObject->setLinearVelocity( getLinearVelocity() );
  2236. pSceneObject->setAngularVelocity( getAngularVelocity() );
  2237. pSceneObject->setLinearDamping( getLinearDamping() );
  2238. pSceneObject->setAngularDamping( getAngularDamping() );
  2239. /// Gravity scaling.
  2240. pSceneObject->setGravityScale( getGravityScale() );
  2241. /// Collision shapes.
  2242. copyCollisionShapes( pSceneObject, true );
  2243. /// Render visibility.
  2244. pSceneObject->setVisible( getVisible() );
  2245. /// Render blending.
  2246. pSceneObject->setBlendMode( getBlendMode() );
  2247. pSceneObject->setSrcBlendFactor( getSrcBlendFactor() );
  2248. pSceneObject->setDstBlendFactor( getDstBlendFactor() );
  2249. pSceneObject->setBlendColor( getBlendColor() );
  2250. pSceneObject->setAlphaTest( getAlphaTest() );
  2251. /// Render sorting.
  2252. pSceneObject->setSortPoint( getSortPoint() );
  2253. /// Input events.
  2254. pSceneObject->setUseInputEvents( getUseInputEvents() );
  2255. // Script callbacks.
  2256. pSceneObject->setUpdateCallback( getUpdateCallback() );
  2257. pSceneObject->setCollisionCallback( getCollisionCallback() );
  2258. pSceneObject->setSleepingCallback( getSleepingCallback() );
  2259. /// Misc.
  2260. pSceneObject->setBatchIsolated( getBatchIsolated() );
  2261. /// Debug mode.
  2262. setDebugOn( getDebugMask() );
  2263. }
  2264. //-----------------------------------------------------------------------------
  2265. S32 SceneObject::copyCollisionShapes( SceneObject* pSceneObject, const bool clearTargetShapes, const S32 shapeIndex )
  2266. {
  2267. // Sanity!
  2268. AssertFatal( pSceneObject != NULL, "SceneObject::copyCollisionShapes() - Cannot copy to a NULL scene object." );
  2269. // Clear the collision shapes.
  2270. if ( clearTargetShapes )
  2271. pSceneObject->clearCollisionShapes();
  2272. // Fetch collision shape count.
  2273. const U32 collisionShapeCount = getCollisionShapeCount();
  2274. // If a shape index is specified, is it valid?
  2275. if ( shapeIndex != INVALID_COLLISION_SHAPE_INDEX && shapeIndex >= (S32)collisionShapeCount )
  2276. {
  2277. // No, so warn.
  2278. Con::warnf( "SceneObject::copyCollisionShapes() - Invalid shape index '%d'.", shapeIndex );
  2279. return INVALID_COLLISION_SHAPE_INDEX;
  2280. }
  2281. // Finish if there are no collision shapes.
  2282. if ( collisionShapeCount == 0 )
  2283. return INVALID_COLLISION_SHAPE_INDEX;
  2284. // Calculate shape range.
  2285. const U32 startShapeIndex = shapeIndex >= 0 ? shapeIndex : 0;
  2286. const U32 endShapeIndex = shapeIndex >= 0 ? shapeIndex : collisionShapeCount -1;
  2287. // Iterate collision shapes.
  2288. for ( U32 index = startShapeIndex; index <= endShapeIndex; ++index )
  2289. {
  2290. b2FixtureDef fixtureDef;
  2291. if ( mpScene )
  2292. {
  2293. // Fetch fixture.
  2294. b2Fixture* pFixture = mCollisionFixtures[index];
  2295. // Fetch common details.
  2296. fixtureDef.density = pFixture->GetDensity();
  2297. fixtureDef.friction = pFixture->GetFriction();
  2298. fixtureDef.restitution = pFixture->GetRestitution();
  2299. fixtureDef.isSensor = pFixture->IsSensor();
  2300. fixtureDef.shape = pFixture->GetShape();
  2301. }
  2302. else
  2303. {
  2304. // Fetch fixture def.
  2305. b2FixtureDef* pFixtureDef = mCollisionFixtureDefs[index];
  2306. // Fetch common details.
  2307. fixtureDef = *pFixtureDef;
  2308. }
  2309. S32 newShapeIndex;
  2310. // Fetch shape type.
  2311. const b2Shape::Type shapeType = fixtureDef.shape->GetType();
  2312. // Copy appropriate shape type.
  2313. switch( shapeType )
  2314. {
  2315. case b2Shape::e_circle:
  2316. newShapeIndex = copyCircleCollisionShapeTo( pSceneObject, fixtureDef );
  2317. // Return the new shape if we're copying a specific index.
  2318. if ( shapeIndex >= 0 )
  2319. return newShapeIndex;
  2320. continue;
  2321. case b2Shape::e_polygon:
  2322. newShapeIndex = copyPolygonCollisionShapeTo( pSceneObject, fixtureDef );
  2323. // Return the new shape if we're copying a specific index.
  2324. if ( shapeIndex >= 0 )
  2325. return newShapeIndex;
  2326. continue;
  2327. case b2Shape::e_chain:
  2328. newShapeIndex = copyChainCollisionShapeTo( pSceneObject, fixtureDef );
  2329. // Return the new shape if we're copying a specific index.
  2330. if ( shapeIndex >= 0 )
  2331. return newShapeIndex;
  2332. continue;
  2333. case b2Shape::e_edge:
  2334. newShapeIndex = copyEdgeCollisionShapeTo( pSceneObject, fixtureDef );
  2335. // Return the new shape if we're copying a specific index.
  2336. if ( shapeIndex >= 0 )
  2337. return newShapeIndex;
  2338. continue;
  2339. default:
  2340. AssertFatal( false, "SceneObject::copyCollisionShapes() - Unsupported collision shape type encountered." );
  2341. }
  2342. }
  2343. // Return the first index if we're copying all the shapes.
  2344. if ( shapeIndex < 0 )
  2345. return 0;
  2346. return INVALID_COLLISION_SHAPE_INDEX;
  2347. }
  2348. //-----------------------------------------------------------------------------
  2349. S32 SceneObject::copyCircleCollisionShapeTo( SceneObject* pSceneObject, const b2FixtureDef& fixtureDef ) const
  2350. {
  2351. // Fetch shape.
  2352. const b2CircleShape* pShape = dynamic_cast<const b2CircleShape*>( fixtureDef.shape );
  2353. // Check shape.
  2354. if ( !pShape )
  2355. {
  2356. Con::errorf("SceneObject::copyCircleCollisionShapeTo() - Invalid shape.");
  2357. return INVALID_COLLISION_SHAPE_INDEX;
  2358. }
  2359. // Fetch shape details.
  2360. const F32 radius = pShape->m_radius;
  2361. const b2Vec2 localPosition = pShape->m_p;
  2362. // Copy shape.
  2363. const S32 shapeIndex = pSceneObject->createCircleCollisionShape( radius, localPosition );
  2364. // Was shape created.
  2365. if ( shapeIndex != -1 )
  2366. {
  2367. // Yes, so configure shape.
  2368. pSceneObject->setCollisionShapeDefinition( shapeIndex, fixtureDef );
  2369. }
  2370. return shapeIndex;
  2371. }
  2372. //-----------------------------------------------------------------------------
  2373. S32 SceneObject::copyPolygonCollisionShapeTo( SceneObject* pSceneObject, const b2FixtureDef& fixtureDef ) const
  2374. {
  2375. // Fetch shape.
  2376. const b2PolygonShape* pShape = dynamic_cast<const b2PolygonShape*>( fixtureDef.shape );
  2377. // Check shape.
  2378. if ( !pShape )
  2379. {
  2380. Con::errorf("SceneObject::copyPolygonCollisionShapeTo() - Invalid shape.");
  2381. return INVALID_COLLISION_SHAPE_INDEX;
  2382. }
  2383. // Fetch point count.
  2384. const U32 pointCount = pShape->GetVertexCount();
  2385. // Fetch local points.
  2386. const b2Vec2* plocalPoints = pShape->m_vertices;
  2387. // Copy shape.
  2388. const S32 shapeIndex = pSceneObject->createPolygonCollisionShape( pointCount, plocalPoints );
  2389. // Was shape created.
  2390. if ( shapeIndex != -1 )
  2391. {
  2392. // Yes, so configure shape.
  2393. pSceneObject->setCollisionShapeDefinition( shapeIndex, fixtureDef );
  2394. }
  2395. return shapeIndex;
  2396. }
  2397. //-----------------------------------------------------------------------------
  2398. S32 SceneObject::copyChainCollisionShapeTo( SceneObject* pSceneObject, const b2FixtureDef& fixtureDef ) const
  2399. {
  2400. // Fetch shape.
  2401. const b2ChainShape* pShape = dynamic_cast<const b2ChainShape*>( fixtureDef.shape );
  2402. // Check shape.
  2403. if ( !pShape )
  2404. {
  2405. Con::errorf("SceneObject::copyChainCollisionShapeTo() - Invalid shape.");
  2406. return INVALID_COLLISION_SHAPE_INDEX;
  2407. }
  2408. // Fetch point count.
  2409. const U32 pointCount = pShape->m_count;
  2410. // Fetch local points.
  2411. b2Vec2* localPoints = pShape->m_vertices;
  2412. // Fetch adjacent positions.
  2413. const bool hasAdjacentLocalPositionStart = pShape->m_hasPrevVertex;
  2414. const bool hasAdjacentLocalPositionEnd = pShape->m_hasNextVertex;
  2415. const b2Vec2 adjacentLocalPositionStart = pShape->m_prevVertex;
  2416. const b2Vec2 adjacentLocalPositionEnd = pShape->m_nextVertex;
  2417. // Create shape.
  2418. const S32 shapeIndex = pSceneObject->createChainCollisionShape(
  2419. pointCount, localPoints,
  2420. hasAdjacentLocalPositionStart, hasAdjacentLocalPositionEnd,
  2421. adjacentLocalPositionStart, adjacentLocalPositionEnd);
  2422. // Was shape created.
  2423. if ( shapeIndex != -1 )
  2424. {
  2425. // Yes, so configure shape.
  2426. pSceneObject->setCollisionShapeDefinition( shapeIndex, fixtureDef );
  2427. }
  2428. return shapeIndex;
  2429. }
  2430. //-----------------------------------------------------------------------------
  2431. S32 SceneObject::copyEdgeCollisionShapeTo( SceneObject* pSceneObject, const b2FixtureDef& fixtureDef ) const
  2432. {
  2433. // Fetch shape.
  2434. const b2EdgeShape* pShape = dynamic_cast<const b2EdgeShape*>( fixtureDef.shape );
  2435. // Check shape.
  2436. if ( !pShape )
  2437. {
  2438. Con::errorf("SceneObject::copyEdgeCollisionShapeTo() - Invalid shape.");
  2439. return INVALID_COLLISION_SHAPE_INDEX;
  2440. }
  2441. // Fetch positions.
  2442. const b2Vec2 localPosition1 = pShape->m_vertex1;
  2443. const b2Vec2 localPosition2 = pShape->m_vertex2;
  2444. const bool hasAdjacentLocalPosition1 = pShape->m_hasVertex0;
  2445. const bool hasAdjacentLocalPosition2 = pShape->m_hasVertex3;
  2446. const b2Vec2 adjacentLocalPosition1 = pShape->m_vertex0;
  2447. const b2Vec2 adjacentLocalPosition2 = pShape->m_vertex3;
  2448. // Create shape.
  2449. const S32 shapeIndex = pSceneObject->createEdgeCollisionShape(
  2450. localPosition1, localPosition2,
  2451. hasAdjacentLocalPosition1, hasAdjacentLocalPosition2,
  2452. adjacentLocalPosition1, adjacentLocalPosition2 );
  2453. // Was shape created.
  2454. if ( shapeIndex != -1 )
  2455. {
  2456. // Yes, so configure shape.
  2457. pSceneObject->setCollisionShapeDefinition( shapeIndex, fixtureDef );
  2458. }
  2459. return shapeIndex;
  2460. }
  2461. //-----------------------------------------------------------------------------
  2462. void SceneObject::safeDelete( void )
  2463. {
  2464. // Are we in a scene?
  2465. if ( getScene() )
  2466. {
  2467. // Yes, so add a delete-request to the scene.
  2468. getScene()->addDeleteRequest( this );
  2469. }
  2470. else
  2471. {
  2472. // No, so use standard SimObject helper.
  2473. deleteObject();
  2474. }
  2475. }
  2476. //-----------------------------------------------------------------------------
  2477. void SceneObject::addDestroyNotification( SceneObject* pSceneObject )
  2478. {
  2479. // Search list to see if we're already in it (finish if we are).
  2480. for ( U32 n = 0; n < (U32)mDestroyNotifyList.size(); n++ )
  2481. {
  2482. // In the list already?
  2483. if ( mDestroyNotifyList[n].mpSceneObject == pSceneObject )
  2484. {
  2485. // Yes, so just bump-up the reference count.
  2486. mDestroyNotifyList[n].mRefCount++;
  2487. // Finish here.
  2488. return;
  2489. }
  2490. }
  2491. // Add Destroy Notification.
  2492. tDestroyNotification notification;
  2493. notification.mpSceneObject = pSceneObject;
  2494. notification.mRefCount = 1;
  2495. // Add Notification.
  2496. mDestroyNotifyList.push_back( notification );
  2497. }
  2498. //-----------------------------------------------------------------------------
  2499. void SceneObject::removeDestroyNotification( SceneObject* pSceneObject )
  2500. {
  2501. // Find object in notification list.
  2502. for ( U32 n = 0; n < (U32)mDestroyNotifyList.size(); n++ )
  2503. {
  2504. // Our object?
  2505. if ( mDestroyNotifyList[n].mpSceneObject == pSceneObject )
  2506. {
  2507. // Yes, so reduce reference count.
  2508. mDestroyNotifyList[n].mRefCount--;
  2509. // Finish Here.
  2510. return;
  2511. }
  2512. }
  2513. }
  2514. //-----------------------------------------------------------------------------
  2515. void SceneObject::processDestroyNotifications( void )
  2516. {
  2517. // Find object in notification list.
  2518. while( mDestroyNotifyList.size() )
  2519. {
  2520. // Fetch Notification Item.
  2521. tDestroyNotification notification = mDestroyNotifyList.first();
  2522. // Only action if we've got a reference active.
  2523. if ( notification.mRefCount > 0 )
  2524. // Call Destroy Notification.
  2525. notification.mpSceneObject->onDestroyNotify( this );
  2526. // Remove it.
  2527. mDestroyNotifyList.pop_front();
  2528. }
  2529. // Sanity!
  2530. AssertFatal( mDestroyNotifyList.size() == 0, "SceneObject::processDestroyNotifications() - Notifications still pending!" );
  2531. }
  2532. //-----------------------------------------------------------------------------
  2533. void SceneObject::notifyComponentsAddToScene( void )
  2534. {
  2535. // Debug Profiling.
  2536. PROFILE_SCOPE(SceneObject_NotifyComponentsAddToScene);
  2537. // Notify components.
  2538. VectorPtr<SimComponent*>& componentList = lockComponentList();
  2539. for( SimComponentIterator itr = componentList.begin(); itr != componentList.end(); ++itr )
  2540. {
  2541. SimComponent *pComponent = *itr;
  2542. if( pComponent != NULL )
  2543. pComponent->onAddToScene();
  2544. }
  2545. unlockComponentList();
  2546. }
  2547. //-----------------------------------------------------------------------------
  2548. void SceneObject::notifyComponentsRemoveFromScene( void )
  2549. {
  2550. // Debug Profiling.
  2551. PROFILE_SCOPE(SceneObject_NotifyComponentsRemoveFromScene);
  2552. // Notify components.
  2553. VectorPtr<SimComponent*>& componentList = lockComponentList();
  2554. for( SimComponentIterator itr = componentList.begin(); itr != componentList.end(); ++itr )
  2555. {
  2556. SimComponent *pComponent = *itr;
  2557. if( pComponent != NULL )
  2558. pComponent->onRemoveFromScene();
  2559. }
  2560. unlockComponentList();
  2561. }
  2562. //-----------------------------------------------------------------------------
  2563. void SceneObject::notifyComponentsUpdate( void )
  2564. {
  2565. // Debug Profiling.
  2566. PROFILE_SCOPE(SceneObject_NotifyComponentsUpdate);
  2567. // Notify components.
  2568. VectorPtr<SimComponent*>& componentList = lockComponentList();
  2569. for( SimComponentIterator itr = componentList.begin(); itr != componentList.end(); ++itr )
  2570. {
  2571. SimComponent *pComponent = *itr;
  2572. if( pComponent != NULL )
  2573. pComponent->onUpdate();
  2574. }
  2575. unlockComponentList();
  2576. }
  2577. //-----------------------------------------------------------------------------
  2578. BehaviorInstance* SceneObject::behavior(const char *name)
  2579. {
  2580. // Debug Profiling.
  2581. PROFILE_SCOPE(SceneObject_BehaviorName);
  2582. StringTableEntry stName = StringTable->insert(name);
  2583. VectorPtr<SimComponent *>&componentList = lockComponentList();
  2584. for( SimComponentIterator nItr = componentList.begin(); nItr != componentList.end(); nItr++ )
  2585. {
  2586. BehaviorInstance* pComponent = dynamic_cast<BehaviorInstance*>(*nItr);
  2587. if( pComponent && StringTable->insert(pComponent->getTemplateName()) == stName )
  2588. {
  2589. unlockComponentList();
  2590. return pComponent;
  2591. }
  2592. }
  2593. unlockComponentList();
  2594. return NULL;
  2595. }
  2596. //-----------------------------------------------------------------------------
  2597. U32 SceneObject::getGlobalSceneObjectCount( void )
  2598. {
  2599. return sGlobalSceneObjectCount;
  2600. }
  2601. //-----------------------------------------------------------------------------
  2602. void SceneObject::onTamlCustomWrite( TamlCustomNodes& customNodes )
  2603. {
  2604. // Debug Profiling.
  2605. PROFILE_SCOPE(SceneObject_OnTamlCustomWrite);
  2606. // Call parent.
  2607. Parent::onTamlCustomWrite( customNodes );
  2608. // Fetch collision shape count.
  2609. const U32 collisionShapeCount = getCollisionShapeCount();
  2610. // Finish if no collision shapes.
  2611. if ( collisionShapeCount == 0 )
  2612. return;
  2613. // Add collision shape node.
  2614. TamlCustomNode* pCustomCollisionShapes = customNodes.addNode( shapeCustomNodeName );
  2615. // Iterate collision shapes.
  2616. for ( U32 shapeIndex = 0; shapeIndex < collisionShapeCount; ++shapeIndex )
  2617. {
  2618. // Fetch collision shape definition.
  2619. b2FixtureDef fixtureDef = getCollisionShapeDefinition( shapeIndex );
  2620. // Add collision shape node.
  2621. // NOTE: The name of the node will get updated shortly.
  2622. TamlCustomNode* pCollisionShapeNode = pCustomCollisionShapes->addNode( StringTable->EmptyString );
  2623. // Add common collision shape fields.
  2624. if ( mNotEqual( getDefaultDensity(), fixtureDef.density ) )
  2625. pCollisionShapeNode->addField( shapeDensityName, fixtureDef.density );
  2626. if ( mNotEqual( getDefaultFriction(), fixtureDef.friction ) )
  2627. pCollisionShapeNode->addField( shapeFrictionName, fixtureDef.friction );
  2628. if ( mNotEqual( getDefaultRestitution(), fixtureDef.restitution ) )
  2629. pCollisionShapeNode->addField( shapeRestitutionName, fixtureDef.restitution );
  2630. if ( fixtureDef.isSensor == true )
  2631. pCollisionShapeNode->addField( shapeSensorName, fixtureDef.isSensor );
  2632. // Populate collision shape appropriately.
  2633. switch( fixtureDef.shape->GetType() )
  2634. {
  2635. case b2Shape::e_circle:
  2636. {
  2637. // Set node name.
  2638. pCollisionShapeNode->setNodeName( circleTypeName );
  2639. // Fetch shape.
  2640. const b2CircleShape* pShape = dynamic_cast<const b2CircleShape*>( fixtureDef.shape );
  2641. // Sanity!
  2642. AssertFatal( pShape != NULL, "SceneObject::onTamlCustomWrite() - Invalid circle shape type returned." );
  2643. // Add radius property.
  2644. pCollisionShapeNode->addField( circleRadiusName, pShape->m_radius );
  2645. // Add offset property (if not zero).
  2646. if ( !Vector2(pShape->m_p).isZero() )
  2647. pCollisionShapeNode->addField( circleOffsetName, pShape->m_p );
  2648. }
  2649. break;
  2650. case b2Shape::e_polygon:
  2651. {
  2652. // Set node name.
  2653. pCollisionShapeNode->setNodeName( polygonTypeName );
  2654. // Fetch shape.
  2655. const b2PolygonShape* pShape = dynamic_cast<const b2PolygonShape*>( fixtureDef.shape );
  2656. // Sanity!
  2657. AssertFatal( pShape != NULL, "SceneObject::onTamlCustomWrite() - Invalid polygon shape type returned." );
  2658. // Fetch point count.
  2659. const U32 pointCount = pShape->GetVertexCount();
  2660. // Add shape properties.
  2661. for ( U32 pointIndex = 0; pointIndex < pointCount; ++pointIndex )
  2662. {
  2663. // Add point node.
  2664. TamlCustomNode* pPointNode = pCollisionShapeNode->addNode( polygonPointName );
  2665. // Fetch point.
  2666. const b2Vec2& point = pShape->GetVertex( pointIndex );
  2667. // Add point fields.
  2668. pPointNode->getNodeTextField().setFieldValue( StringTable->EmptyString, point );
  2669. }
  2670. }
  2671. break;
  2672. case b2Shape::e_chain:
  2673. {
  2674. // Set node name.
  2675. pCollisionShapeNode->setNodeName( chainTypeName );
  2676. // Fetch shape.
  2677. const b2ChainShape* pShape = dynamic_cast<const b2ChainShape*>( fixtureDef.shape );
  2678. // Sanity!
  2679. AssertFatal( pShape != NULL, "SceneObject::onTamlCustomWrite() - Invalid chain shape type returned." );
  2680. // Fetch point count.
  2681. const U32 pointCount = pShape->m_count;
  2682. // Add shape properties.
  2683. for ( U32 pointIndex = 0; pointIndex < pointCount; ++pointIndex )
  2684. {
  2685. // Add point node.
  2686. TamlCustomNode* pPointNode = pCollisionShapeNode->addNode( chainPointName );
  2687. // Add point fields.
  2688. pPointNode->getNodeTextField().setFieldValue( StringTable->EmptyString, pShape->m_vertices[pointIndex] );
  2689. }
  2690. // Add adjacent start point (if specified).
  2691. if ( pShape->m_hasPrevVertex )
  2692. pCollisionShapeNode->addField( chainAdjacentStartName, pShape->m_prevVertex );
  2693. // Add adjacent end point (if specified).
  2694. if ( pShape->m_hasNextVertex )
  2695. pCollisionShapeNode->addField( chainAdjacentEndName, pShape->m_nextVertex );
  2696. }
  2697. break;
  2698. case b2Shape::e_edge:
  2699. {
  2700. // Set node name.
  2701. pCollisionShapeNode->setNodeName( edgeTypeName );
  2702. // Fetch shape.
  2703. const b2EdgeShape* pShape = dynamic_cast<const b2EdgeShape*>( fixtureDef.shape );
  2704. // Sanity!
  2705. AssertFatal( pShape != NULL, "SceneObject::onTamlCustomWrite() - Invalid edge shape type returned." );
  2706. // Add start/end points.
  2707. pCollisionShapeNode->addField( edgeStartName, pShape->m_vertex1 );
  2708. pCollisionShapeNode->addField( edgeEndName, pShape->m_vertex2 );
  2709. // Add adjacent start point (if specified).
  2710. if ( pShape->m_hasVertex0 )
  2711. pCollisionShapeNode->addField( edgeAdjacentStartName, pShape->m_vertex0 );
  2712. // Add adjacent end point (if specified).
  2713. if ( pShape->m_hasVertex3 )
  2714. pCollisionShapeNode->addField( edgeAdjacentEndName, pShape->m_vertex3 );
  2715. }
  2716. break;
  2717. default:
  2718. // Sanity!
  2719. AssertFatal( false, "SceneObject::onTamlCustomWrite() - Unknown shape type detected." );
  2720. }
  2721. }
  2722. }
  2723. //-----------------------------------------------------------------------------
  2724. void SceneObject::onTamlCustomRead( const TamlCustomNodes& customNodes )
  2725. {
  2726. // Debug Profiling.
  2727. PROFILE_SCOPE(SceneObject_OnTamlCustomRead);
  2728. // Call parent.
  2729. Parent::onTamlCustomRead( customNodes );
  2730. // Find collision shape custom node.
  2731. const TamlCustomNode* pCustomCollisionShapes = customNodes.findNode( shapeCustomNodeName );
  2732. // Finish if we don't have collision shapes.
  2733. if ( pCustomCollisionShapes == NULL )
  2734. return;
  2735. // Fetch children shapes.
  2736. const TamlCustomNodeVector& collisionShapeChildren = pCustomCollisionShapes->getChildren();
  2737. // Iterate collision shapes.
  2738. for( TamlCustomNodeVector::const_iterator shapeNodeItr = collisionShapeChildren.begin(); shapeNodeItr != collisionShapeChildren.end(); ++shapeNodeItr )
  2739. {
  2740. // Fetch shape node.
  2741. TamlCustomNode* pShapeNode = *shapeNodeItr;
  2742. // Fetch shape name.
  2743. StringTableEntry shapeName = pShapeNode->getNodeName();
  2744. // Ready common fields.
  2745. F32 shapeDensity = getDefaultDensity();
  2746. F32 shapeFriction = getDefaultFriction();
  2747. F32 shapeRestitution = getDefaultRestitution();
  2748. bool shapeSensor = false;
  2749. S32 shapeIndex;
  2750. // Is this a circle shape?
  2751. if ( shapeName == circleTypeName )
  2752. {
  2753. // Yes, so ready fields.
  2754. F32 radius = 0.0f;
  2755. b2Vec2 offset( 0.0f, 0.0f );
  2756. // Fetch shape children.
  2757. const TamlCustomFieldVector& shapeFields = pShapeNode->getFields();
  2758. // Iterate property fields.
  2759. for ( TamlCustomFieldVector::const_iterator shapeFieldItr = shapeFields.begin(); shapeFieldItr != shapeFields.end(); ++shapeFieldItr )
  2760. {
  2761. // Fetch field.
  2762. const TamlCustomField* pField = *shapeFieldItr;
  2763. // Fetch property field name.
  2764. StringTableEntry fieldName = pField->getFieldName();
  2765. // Check common fields.
  2766. if ( fieldName == shapeDensityName )
  2767. {
  2768. pField->getFieldValue( shapeDensity );
  2769. }
  2770. else if ( fieldName == shapeFrictionName )
  2771. {
  2772. pField->getFieldValue( shapeFriction );
  2773. }
  2774. else if ( fieldName == shapeRestitutionName )
  2775. {
  2776. pField->getFieldValue( shapeRestitution );
  2777. }
  2778. else if ( fieldName == shapeSensorName )
  2779. {
  2780. pField->getFieldValue( shapeSensor );
  2781. }
  2782. // Check circle fields.
  2783. else if ( fieldName == circleRadiusName )
  2784. {
  2785. pField->getFieldValue( radius );
  2786. }
  2787. else if ( fieldName == circleOffsetName )
  2788. {
  2789. pField->getFieldValue( offset );
  2790. }
  2791. }
  2792. // Is radius valid?
  2793. if ( radius <= 0.0f )
  2794. {
  2795. // No, so warn.
  2796. Con::warnf( "SceneObject::onTamlCustomRead() - Invalid radius on circle collision shape '%g'. Using default.", radius );
  2797. // Set default.
  2798. radius = 1.0f;
  2799. }
  2800. // Create shape.
  2801. shapeIndex = createCircleCollisionShape( radius, offset );
  2802. }
  2803. // Is this a polygon shape?
  2804. else if ( shapeName == polygonTypeName )
  2805. {
  2806. // Yes, so ready fields.
  2807. b2Vec2 points[b2_maxPolygonVertices];
  2808. U32 pointCount = 0;
  2809. // Fetch shape fields.
  2810. const TamlCustomFieldVector& shapeFields = pShapeNode->getFields();
  2811. // Iterate property fields.
  2812. for ( TamlCustomFieldVector::const_iterator shapeFieldItr = shapeFields.begin(); shapeFieldItr != shapeFields.end(); ++shapeFieldItr )
  2813. {
  2814. // Fetch field.
  2815. const TamlCustomField* pField = *shapeFieldItr;
  2816. // Fetch property field name.
  2817. StringTableEntry fieldName = pField->getFieldName();
  2818. // Check common fields.
  2819. if ( fieldName == shapeDensityName )
  2820. {
  2821. pField->getFieldValue( shapeDensity );
  2822. }
  2823. else if ( fieldName == shapeFrictionName )
  2824. {
  2825. pField->getFieldValue( shapeFriction );
  2826. }
  2827. else if ( fieldName == shapeRestitutionName )
  2828. {
  2829. pField->getFieldValue( shapeRestitution );
  2830. }
  2831. else if ( fieldName == shapeSensorName )
  2832. {
  2833. pField->getFieldValue( shapeSensor );
  2834. }
  2835. // Check polygon fields.
  2836. else if ( pField->fieldNameBeginsWith( polygonPointName ) )
  2837. {
  2838. // Is the point count at maximum?
  2839. if ( pointCount == b2_maxPolygonVertices )
  2840. {
  2841. // Yes, so warn.
  2842. Con::warnf( "SceneObject::onTamlCustomRead() - Polygon point count exceed the maximum points '%d'.", b2_maxPolygonVertices );
  2843. continue;
  2844. }
  2845. b2Vec2 point;
  2846. pField->getFieldValue( point );
  2847. points[pointCount++] = point;
  2848. }
  2849. }
  2850. // Fetch shape children.
  2851. const TamlCustomNodeVector& shapeChildren = pShapeNode->getChildren();
  2852. // Fetch shape children count.
  2853. const U32 shapeChildrenCount = (U32)shapeChildren.size();
  2854. // Do we have any shape children.
  2855. if ( shapeChildrenCount > 0 )
  2856. {
  2857. // Yes, so iterate them.
  2858. for( TamlCustomNodeVector::const_iterator childItr = shapeChildren.begin(); childItr != shapeChildren.end(); ++childItr )
  2859. {
  2860. TamlCustomNode* pChildNode = *childItr;
  2861. // Skip if it's not a point.
  2862. if ( pChildNode->getNodeName() != polygonPointName )
  2863. continue;
  2864. // Skip if it's empty.
  2865. if ( pChildNode->getNodeTextField().isValueEmpty() )
  2866. continue;
  2867. // Read point.
  2868. b2Vec2 point;
  2869. pChildNode->getNodeTextField().getFieldValue( point );
  2870. points[pointCount++] = point;
  2871. }
  2872. }
  2873. // Is point count valid?
  2874. if ( pointCount == 0 )
  2875. {
  2876. // No, so warn.
  2877. Con::warnf( "SceneObject::onTamlCustomRead() - No points on polygon collision shape." );
  2878. continue;
  2879. }
  2880. // Create shape.
  2881. shapeIndex = createPolygonCollisionShape( pointCount, points );
  2882. }
  2883. // Is this a chain shape?
  2884. else if ( shapeName == chainTypeName )
  2885. {
  2886. // Yes, so ready fields.
  2887. Vector<b2Vec2> points;
  2888. bool hasAdjacentStartPoint;
  2889. bool hasAdjacentEndPoint;
  2890. b2Vec2 adjacentStartPoint;
  2891. b2Vec2 adjacentEndPoint;
  2892. // Fetch shape children.
  2893. const TamlCustomFieldVector& shapeFields = pShapeNode->getFields();
  2894. // Iterate property fields.
  2895. for ( TamlCustomFieldVector::const_iterator shapeFieldItr = shapeFields.begin(); shapeFieldItr != shapeFields.end(); ++shapeFieldItr )
  2896. {
  2897. // Fetch field.
  2898. const TamlCustomField* pField = *shapeFieldItr;
  2899. // Fetch property field name.
  2900. StringTableEntry fieldName = pField->getFieldName();
  2901. // Check common fields.
  2902. if ( fieldName == shapeDensityName )
  2903. {
  2904. pField->getFieldValue( shapeDensity );
  2905. }
  2906. else if ( fieldName == shapeFrictionName )
  2907. {
  2908. pField->getFieldValue( shapeFriction );
  2909. }
  2910. else if ( fieldName == shapeRestitutionName )
  2911. {
  2912. pField->getFieldValue( shapeRestitution );
  2913. }
  2914. else if ( fieldName == shapeSensorName )
  2915. {
  2916. pField->getFieldValue( shapeSensor );
  2917. }
  2918. // Check chain fields.
  2919. else if ( pField->fieldNameBeginsWith( chainPointName ) )
  2920. {
  2921. b2Vec2 point;
  2922. pField->getFieldValue( point );
  2923. points.push_back( point );
  2924. }
  2925. else if ( fieldName == chainAdjacentStartName )
  2926. {
  2927. pField->getFieldValue( adjacentStartPoint );
  2928. hasAdjacentStartPoint = true;
  2929. }
  2930. else if ( fieldName == chainAdjacentEndName )
  2931. {
  2932. pField->getFieldValue( adjacentEndPoint );
  2933. hasAdjacentEndPoint = true;
  2934. }
  2935. }
  2936. // Is point count valid?
  2937. if ( points.size() == 0 )
  2938. {
  2939. // No, so warn.
  2940. Con::warnf( "SceneObject::onTamlCustomRead() - No points on chain collision shape." );
  2941. continue;
  2942. }
  2943. // Create shape.
  2944. shapeIndex = createChainCollisionShape( points.size(), points.address(), hasAdjacentStartPoint, hasAdjacentEndPoint, adjacentStartPoint, adjacentEndPoint );
  2945. }
  2946. // Is this an edge shape?
  2947. else if ( shapeName == edgeTypeName )
  2948. {
  2949. // Yes, so ready fields.
  2950. b2Vec2 point0;
  2951. b2Vec2 point1;
  2952. bool hasAdjacentStartPoint;
  2953. bool hasAdjacentEndPoint;
  2954. b2Vec2 adjacentStartPoint;
  2955. b2Vec2 adjacentEndPoint;
  2956. // Fetch shape children.
  2957. const TamlCustomFieldVector& shapeFields = pShapeNode->getFields();
  2958. // Iterate property fields.
  2959. for ( TamlCustomFieldVector::const_iterator shapeFieldItr = shapeFields.begin(); shapeFieldItr != shapeFields.end(); ++shapeFieldItr )
  2960. {
  2961. // Fetch field.
  2962. const TamlCustomField* pField = *shapeFieldItr;
  2963. // Fetch property field name.
  2964. StringTableEntry fieldName = pField->getFieldName();
  2965. // Check common fields.
  2966. if ( fieldName == shapeDensityName )
  2967. {
  2968. pField->getFieldValue( shapeDensity );
  2969. }
  2970. else if ( fieldName == shapeFrictionName )
  2971. {
  2972. pField->getFieldValue( shapeFriction );
  2973. }
  2974. else if ( fieldName == shapeRestitutionName )
  2975. {
  2976. pField->getFieldValue( shapeRestitution );
  2977. }
  2978. else if ( fieldName == shapeSensorName )
  2979. {
  2980. pField->getFieldValue( shapeSensor );
  2981. }
  2982. // Check edge fields.
  2983. else if ( fieldName == edgeStartName )
  2984. {
  2985. pField->getFieldValue( point0 );
  2986. }
  2987. else if ( fieldName == edgeEndName )
  2988. {
  2989. pField->getFieldValue( point1 );
  2990. }
  2991. else if ( fieldName == edgeAdjacentStartName )
  2992. {
  2993. pField->getFieldValue( adjacentStartPoint );
  2994. hasAdjacentStartPoint = true;
  2995. }
  2996. else if ( fieldName == edgeAdjacentEndName )
  2997. {
  2998. pField->getFieldValue( adjacentEndPoint );
  2999. hasAdjacentEndPoint = true;
  3000. }
  3001. }
  3002. // Create shape.
  3003. shapeIndex = createEdgeCollisionShape( point0, point1, hasAdjacentStartPoint, hasAdjacentEndPoint, adjacentStartPoint, adjacentEndPoint );
  3004. }
  3005. // Unknown shape type!
  3006. else
  3007. {
  3008. // Warn.
  3009. Con::warnf( "Unknown shape type of '%s' encountered.", shapeName );
  3010. // Sanity!
  3011. AssertFatal( false, "SceneObject::onTamlCustomRead() - Unknown shape type detected." );
  3012. continue;
  3013. }
  3014. // Set common properties.
  3015. setCollisionShapeDensity( shapeIndex, shapeDensity );
  3016. setCollisionShapeFriction( shapeIndex, shapeFriction );
  3017. setCollisionShapeRestitution( shapeIndex, shapeRestitution );
  3018. setCollisionShapeIsSensor( shapeIndex, shapeSensor );
  3019. }
  3020. }
  3021. //-----------------------------------------------------------------------------
  3022. bool SceneObject::writeField(StringTableEntry fieldname, const char* value)
  3023. {
  3024. if (!Parent::writeField(fieldname, value))
  3025. return false;
  3026. // Never save the scene field.
  3027. if (dStricmp(fieldname, "scene") == 0)
  3028. return false;
  3029. return true;
  3030. }
  3031. //------------------------------------------------------------------------------
  3032. S32 QSORT_CALLBACK SceneObject::sceneObjectLayerDepthSort(const void* a, const void* b)
  3033. {
  3034. // Fetch scene objects.
  3035. SceneObject* pSceneObjectA = *((SceneObject**)a);
  3036. SceneObject* pSceneObjectB = *((SceneObject**)b);
  3037. // Fetch layers.
  3038. const U32 layerA = pSceneObjectA->getSceneLayer();
  3039. const U32 layerB = pSceneObjectB->getSceneLayer();
  3040. if ( layerA < layerB )
  3041. return -1;
  3042. if ( layerA > layerB )
  3043. return 1;
  3044. // Fetch layer depths.
  3045. const F32 depthA = pSceneObjectA->getSceneLayerDepth();
  3046. const F32 depthB = pSceneObjectB->getSceneLayerDepth();
  3047. return depthA < depthB ? 1 : depthA > depthB ? -1 : pSceneObjectA->getSerialId() - pSceneObjectB->getSerialId();
  3048. }
  3049. //-----------------------------------------------------------------------------
  3050. static EnumTable::Enums bodyTypeLookup[] =
  3051. {
  3052. { b2_staticBody, "static" },
  3053. { b2_kinematicBody, "kinematic" },
  3054. { b2_dynamicBody, "dynamic" },
  3055. };
  3056. EnumTable bodyTypeTable(sizeof(bodyTypeLookup) / sizeof(EnumTable::Enums), &bodyTypeLookup[0]);
  3057. //-----------------------------------------------------------------------------
  3058. static EnumTable::Enums collisionShapeTypeLookup[] =
  3059. {
  3060. { b2Shape::e_circle, "circle" },
  3061. { b2Shape::e_edge, "edge" },
  3062. { b2Shape::e_polygon, "polygon" },
  3063. { b2Shape::e_chain, "chain" },
  3064. };
  3065. EnumTable collisionShapeTypeTable(sizeof(collisionShapeTypeLookup) / sizeof(EnumTable::Enums), &collisionShapeTypeLookup[0]);
  3066. //-----------------------------------------------------------------------------
  3067. static EnumTable::Enums srcBlendFactorLookup[] =
  3068. {
  3069. { GL_ZERO, "ZERO" },
  3070. { GL_ONE, "ONE" },
  3071. { GL_DST_COLOR, "DST_COLOR" },
  3072. { GL_ONE_MINUS_DST_COLOR, "ONE_MINUS_DST_COLOR" },
  3073. { GL_SRC_ALPHA, "SRC_ALPHA" },
  3074. { GL_ONE_MINUS_SRC_ALPHA, "ONE_MINUS_SRC_ALPHA" },
  3075. { GL_DST_ALPHA, "DST_ALPHA" },
  3076. { GL_ONE_MINUS_DST_ALPHA, "ONE_MINUS_DST_ALPHA" },
  3077. { GL_SRC_ALPHA_SATURATE, "SRC_ALPHA_SATURATE" },
  3078. };
  3079. EnumTable srcBlendFactorTable(sizeof(srcBlendFactorLookup) / sizeof(EnumTable::Enums), &srcBlendFactorLookup[0]);
  3080. //-----------------------------------------------------------------------------
  3081. static EnumTable::Enums dstBlendFactorLookup[] =
  3082. {
  3083. { GL_ZERO, "ZERO" },
  3084. { GL_ONE, "ONE" },
  3085. { GL_SRC_COLOR, "SRC_COLOR" },
  3086. { GL_ONE_MINUS_SRC_COLOR, "ONE_MINUS_SRC_COLOR" },
  3087. { GL_SRC_ALPHA, "SRC_ALPHA" },
  3088. { GL_ONE_MINUS_SRC_ALPHA, "ONE_MINUS_SRC_ALPHA" },
  3089. { GL_DST_ALPHA, "DST_ALPHA" },
  3090. { GL_ONE_MINUS_DST_ALPHA, "ONE_MINUS_DST_ALPHA" },
  3091. };
  3092. EnumTable dstBlendFactorTable(sizeof(dstBlendFactorLookup) / sizeof(EnumTable::Enums), &dstBlendFactorLookup[0]);
  3093. //-----------------------------------------------------------------------------
  3094. b2BodyType SceneObject::getBodyTypeEnum(const char* label)
  3095. {
  3096. // Search for Mnemonic.
  3097. for (U32 i = 0; i < (sizeof(bodyTypeLookup) / sizeof(EnumTable::Enums)); i++)
  3098. {
  3099. if( dStricmp(bodyTypeLookup[i].label, label) == 0)
  3100. return (b2BodyType)bodyTypeLookup[i].index;
  3101. }
  3102. // Warn.
  3103. Con::warnf("SceneObject::getBodyTypeEnum() - Invalid body type of '%s'", label );
  3104. return (b2BodyType)-1;
  3105. }
  3106. //-----------------------------------------------------------------------------
  3107. const char* SceneObject::getBodyTypeDescription(const b2BodyType bodyType)
  3108. {
  3109. // Search for Mnemonic.
  3110. for (U32 i = 0; i < (sizeof(bodyTypeLookup) / sizeof(EnumTable::Enums)); i++)
  3111. {
  3112. if( bodyTypeLookup[i].index == bodyType )
  3113. return bodyTypeLookup[i].label;
  3114. }
  3115. // Warn.
  3116. Con::warnf( "SceneObject::getBodyTypeDescription() - Invalid body type." );
  3117. return StringTable->EmptyString;
  3118. }
  3119. //-----------------------------------------------------------------------------
  3120. b2Shape::Type SceneObject::getCollisionShapeTypeEnum(const char* label)
  3121. {
  3122. // Search for Mnemonic.
  3123. for (U32 i = 0; i < (sizeof(collisionShapeTypeLookup) / sizeof(EnumTable::Enums)); i++)
  3124. {
  3125. if( dStricmp(collisionShapeTypeLookup[i].label, label) == 0)
  3126. return (b2Shape::Type)collisionShapeTypeLookup[i].index;
  3127. }
  3128. // Warn!
  3129. Con::warnf("SceneObject::getCollisionShapeTypeEnum() - Invalid collision shape type of '%s'", label );
  3130. return b2Shape::e_typeCount;
  3131. }
  3132. //-----------------------------------------------------------------------------
  3133. const char* SceneObject::getCollisionShapeTypeDescription(const b2Shape::Type collisionShapeType)
  3134. {
  3135. // Search for Mnemonic.
  3136. for (U32 i = 0; i < (sizeof(collisionShapeTypeLookup) / sizeof(EnumTable::Enums)); i++)
  3137. {
  3138. if( collisionShapeTypeLookup[i].index == collisionShapeType )
  3139. return collisionShapeTypeLookup[i].label;
  3140. }
  3141. // Warn.
  3142. Con::warnf( "SceneObject::getCollisionShapeTypeDescription() - Invalid collision shape type." );
  3143. return StringTable->EmptyString;
  3144. }
  3145. //-----------------------------------------------------------------------------
  3146. S32 SceneObject::getSrcBlendFactorEnum(const char* label)
  3147. {
  3148. // Search for Mnemonic.
  3149. for (U32 i = 0; i < (sizeof(srcBlendFactorLookup) / sizeof(EnumTable::Enums)); i++)
  3150. {
  3151. if( dStricmp(srcBlendFactorLookup[i].label, label) == 0)
  3152. return(srcBlendFactorLookup[i].index);
  3153. }
  3154. // Warn.
  3155. Con::warnf("SceneObject::getSrcBlendFactorEnum() - Invalid source blend factor of '%s'", label );
  3156. return GL_INVALID_BLEND_FACTOR;
  3157. }
  3158. //-----------------------------------------------------------------------------
  3159. const char* SceneObject::getSrcBlendFactorDescription(const GLenum factor)
  3160. {
  3161. // Search for Mnemonic.
  3162. for (U32 i = 0; i < (sizeof(srcBlendFactorLookup) / sizeof(EnumTable::Enums)); i++)
  3163. {
  3164. if( srcBlendFactorLookup[i].index == (S32)factor )
  3165. return srcBlendFactorLookup[i].label;
  3166. }
  3167. // Warn.
  3168. Con::warnf( "SceneObject::getSrcBlendFactorDescription() - Invalid source blend factor." );
  3169. return StringTable->EmptyString;
  3170. }
  3171. //-----------------------------------------------------------------------------
  3172. S32 SceneObject::getDstBlendFactorEnum(const char* label)
  3173. {
  3174. // Search for Mnemonic.
  3175. for (U32 i = 0; i < (sizeof(dstBlendFactorLookup) / sizeof(EnumTable::Enums)); i++)
  3176. {
  3177. if( dStricmp(dstBlendFactorLookup[i].label, label) == 0)
  3178. return(dstBlendFactorLookup[i].index);
  3179. }
  3180. // Warn.
  3181. Con::warnf("SceneObject::getSrcBlendFactorEnum() - Invalid destination blend factor of '%s'", label );
  3182. return GL_INVALID_BLEND_FACTOR;
  3183. }
  3184. //-----------------------------------------------------------------------------
  3185. const char* SceneObject::getDstBlendFactorDescription(const GLenum factor)
  3186. {
  3187. // Search for Mnemonic.
  3188. for(U32 i = 0; i < (sizeof(dstBlendFactorLookup) / sizeof(EnumTable::Enums)); i++)
  3189. {
  3190. if( dstBlendFactorLookup[i].index == (S32)factor )
  3191. return dstBlendFactorLookup[i].label;
  3192. }
  3193. // Warn.
  3194. Con::warnf( "SceneObject::getDstBlendFactorDescription() - Invalid destination blend factor." );
  3195. return StringTable->EmptyString;
  3196. }