SceneObject.cc 156 KB

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