SceneObject.cc 136 KB

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