SceneObject.cc 153 KB

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