OdeScene.cs 187 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. //#define USE_DRAWSTUFF
  28. //#define SPAM
  29. using System;
  30. using System.Collections.Generic;
  31. using System.Diagnostics;
  32. using System.IO;
  33. using System.Linq;
  34. using System.Reflection;
  35. using System.Runtime.InteropServices;
  36. using System.Threading;
  37. using log4net;
  38. using Nini.Config;
  39. using Mono.Addins;
  40. using Ode.NET;
  41. using OpenMetaverse;
  42. #if USE_DRAWSTUFF
  43. using Drawstuff.NET;
  44. #endif
  45. using OpenSim.Framework;
  46. using OpenSim.Region.PhysicsModules.SharedBase;
  47. using OpenSim.Region.Framework.Scenes;
  48. using OpenSim.Region.Framework.Interfaces;
  49. namespace OpenSim.Region.PhysicsModule.ODE
  50. {
  51. public enum StatusIndicators : int
  52. {
  53. Generic = 0,
  54. Start = 1,
  55. End = 2
  56. }
  57. // public struct sCollisionData
  58. // {
  59. // public uint ColliderLocalId;
  60. // public uint CollidedWithLocalId;
  61. // public int NumberOfCollisions;
  62. // public int CollisionType;
  63. // public int StatusIndicator;
  64. // public int lastframe;
  65. // }
  66. [Flags]
  67. public enum CollisionCategories : int
  68. {
  69. Disabled = 0,
  70. Geom = 0x00000001,
  71. Body = 0x00000002,
  72. Space = 0x00000004,
  73. Character = 0x00000008,
  74. Land = 0x00000010,
  75. Water = 0x00000020,
  76. Wind = 0x00000040,
  77. Sensor = 0x00000080,
  78. Selected = 0x00000100
  79. }
  80. /// <summary>
  81. /// Material type for a primitive
  82. /// </summary>
  83. public enum Material : int
  84. {
  85. /// <summary></summary>
  86. Stone = 0,
  87. /// <summary></summary>
  88. Metal = 1,
  89. /// <summary></summary>
  90. Glass = 2,
  91. /// <summary></summary>
  92. Wood = 3,
  93. /// <summary></summary>
  94. Flesh = 4,
  95. /// <summary></summary>
  96. Plastic = 5,
  97. /// <summary></summary>
  98. Rubber = 6
  99. }
  100. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ODEPhysicsScene")]
  101. public class OdeScene : PhysicsScene
  102. {
  103. private readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.ToString());
  104. private bool m_Enabled = false;
  105. // private Dictionary<string, sCollisionData> m_storedCollisions = new Dictionary<string, sCollisionData>();
  106. /// <summary>
  107. /// Provide a sync object so that only one thread calls d.Collide() at a time across all OdeScene instances.
  108. /// </summary>
  109. /// <remarks>
  110. /// With ODE as of r1755 (though also tested on r1860), only one thread can call d.Collide() at a
  111. /// time, even where physics objects are in entirely different ODE worlds. This is because generating contacts
  112. /// uses a static cache at the ODE level.
  113. ///
  114. /// Without locking, simulators running multiple regions will eventually crash with a native stack trace similar
  115. /// to
  116. ///
  117. /// mono() [0x489171]
  118. /// mono() [0x4d154f]
  119. /// /lib/x86_64-linux-gnu/libpthread.so.0(+0xfc60) [0x7f6ded592c60]
  120. /// .../opensim/bin/libode-x86_64.so(_ZN6Opcode11OBBCollider8_CollideEPKNS_14AABBNoLeafNodeE+0xd7a) [0x7f6dd822628a]
  121. ///
  122. /// ODE provides an experimental option to cache in thread local storage but compiling ODE with this option
  123. /// causes OpenSimulator to immediately crash with a native stack trace similar to
  124. ///
  125. /// mono() [0x489171]
  126. /// mono() [0x4d154f]
  127. /// /lib/x86_64-linux-gnu/libpthread.so.0(+0xfc60) [0x7f03c9849c60]
  128. /// .../opensim/bin/libode-x86_64.so(_Z12dCollideCCTLP6dxGeomS0_iP12dContactGeomi+0x92) [0x7f03b44bcf82]
  129. /// </remarks>
  130. internal static Object UniversalColliderSyncObject = new Object();
  131. /// <summary>
  132. /// Is stats collecting enabled for this ODE scene?
  133. /// </summary>
  134. public bool CollectStats { get; set; }
  135. /// <summary>
  136. /// Statistics for this scene.
  137. /// </summary>
  138. private Dictionary<string, float> m_stats = new Dictionary<string, float>();
  139. /// <summary>
  140. /// Stat name for total number of avatars in this ODE scene.
  141. /// </summary>
  142. public const string ODETotalAvatarsStatName = "ODETotalAvatars";
  143. /// <summary>
  144. /// Stat name for total number of prims in this ODE scene.
  145. /// </summary>
  146. public const string ODETotalPrimsStatName = "ODETotalPrims";
  147. /// <summary>
  148. /// Stat name for total number of prims with active physics in this ODE scene.
  149. /// </summary>
  150. public const string ODEActivePrimsStatName = "ODEActivePrims";
  151. /// <summary>
  152. /// Stat name for the total time spent in ODE frame processing.
  153. /// </summary>
  154. /// <remarks>
  155. /// A sanity check for the main scene loop physics time.
  156. /// </remarks>
  157. public const string ODETotalFrameMsStatName = "ODETotalFrameMS";
  158. /// <summary>
  159. /// Stat name for time spent processing avatar taints per frame
  160. /// </summary>
  161. public const string ODEAvatarTaintMsStatName = "ODEAvatarTaintFrameMS";
  162. /// <summary>
  163. /// Stat name for time spent processing prim taints per frame
  164. /// </summary>
  165. public const string ODEPrimTaintMsStatName = "ODEPrimTaintFrameMS";
  166. /// <summary>
  167. /// Stat name for time spent calculating avatar forces per frame.
  168. /// </summary>
  169. public const string ODEAvatarForcesFrameMsStatName = "ODEAvatarForcesFrameMS";
  170. /// <summary>
  171. /// Stat name for time spent calculating prim forces per frame
  172. /// </summary>
  173. public const string ODEPrimForcesFrameMsStatName = "ODEPrimForcesFrameMS";
  174. /// <summary>
  175. /// Stat name for time spent fulfilling raycasting requests per frame
  176. /// </summary>
  177. public const string ODERaycastingFrameMsStatName = "ODERaycastingFrameMS";
  178. /// <summary>
  179. /// Stat name for time spent in native code that actually steps through the simulation.
  180. /// </summary>
  181. public const string ODENativeStepFrameMsStatName = "ODENativeStepFrameMS";
  182. /// <summary>
  183. /// Stat name for the number of milliseconds that ODE spends in native space collision code.
  184. /// </summary>
  185. public const string ODENativeSpaceCollisionFrameMsStatName = "ODENativeSpaceCollisionFrameMS";
  186. /// <summary>
  187. /// Stat name for milliseconds that ODE spends in native geom collision code.
  188. /// </summary>
  189. public const string ODENativeGeomCollisionFrameMsStatName = "ODENativeGeomCollisionFrameMS";
  190. /// <summary>
  191. /// Time spent in collision processing that is not spent in native space or geom collision code.
  192. /// </summary>
  193. public const string ODEOtherCollisionFrameMsStatName = "ODEOtherCollisionFrameMS";
  194. /// <summary>
  195. /// Stat name for time spent notifying listeners of collisions
  196. /// </summary>
  197. public const string ODECollisionNotificationFrameMsStatName = "ODECollisionNotificationFrameMS";
  198. /// <summary>
  199. /// Stat name for milliseconds spent updating avatar position and velocity
  200. /// </summary>
  201. public const string ODEAvatarUpdateFrameMsStatName = "ODEAvatarUpdateFrameMS";
  202. /// <summary>
  203. /// Stat name for the milliseconds spent updating prim position and velocity
  204. /// </summary>
  205. public const string ODEPrimUpdateFrameMsStatName = "ODEPrimUpdateFrameMS";
  206. /// <summary>
  207. /// Stat name for avatar collisions with another entity.
  208. /// </summary>
  209. public const string ODEAvatarContactsStatsName = "ODEAvatarContacts";
  210. /// <summary>
  211. /// Stat name for prim collisions with another entity.
  212. /// </summary>
  213. public const string ODEPrimContactsStatName = "ODEPrimContacts";
  214. /// <summary>
  215. /// Used to hold tick numbers for stat collection purposes.
  216. /// </summary>
  217. private int m_nativeCollisionStartTick;
  218. /// <summary>
  219. /// A messy way to tell if we need to avoid adding a collision time because this was already done in the callback.
  220. /// </summary>
  221. private bool m_inCollisionTiming;
  222. /// <summary>
  223. /// A temporary holder for the number of avatar collisions in a frame, so we can work out how many object
  224. /// collisions occured using the _perloopcontact if stats collection is enabled.
  225. /// </summary>
  226. private int m_tempAvatarCollisionsThisFrame;
  227. /// <summary>
  228. /// Used in calculating physics frame time dilation
  229. /// </summary>
  230. private int tickCountFrameRun;
  231. /// <summary>
  232. /// Used in calculating physics frame time dilation
  233. /// </summary>
  234. private int latertickcount;
  235. private Random fluidRandomizer = new Random(Environment.TickCount);
  236. private const uint m_regionWidth = Constants.RegionSize;
  237. private const uint m_regionHeight = Constants.RegionSize;
  238. private float ODE_STEPSIZE = 0.0178f;
  239. private float metersInSpace = 29.9f;
  240. private float m_timeDilation = 1.0f;
  241. public float gravityx = 0f;
  242. public float gravityy = 0f;
  243. public float gravityz = -9.8f;
  244. public float AvatarTerminalVelocity { get; set; }
  245. private float contactsurfacelayer = 0.001f;
  246. private int worldHashspaceLow = -4;
  247. private int worldHashspaceHigh = 128;
  248. private int smallHashspaceLow = -4;
  249. private int smallHashspaceHigh = 66;
  250. private float waterlevel = 0f;
  251. private int framecount = 0;
  252. //private int m_returncollisions = 10;
  253. private IntPtr contactgroup;
  254. internal IntPtr WaterGeom;
  255. private float nmTerrainContactFriction = 255.0f;
  256. private float nmTerrainContactBounce = 0.1f;
  257. private float nmTerrainContactERP = 0.1025f;
  258. private float mTerrainContactFriction = 75f;
  259. private float mTerrainContactBounce = 0.1f;
  260. private float mTerrainContactERP = 0.05025f;
  261. private float nmAvatarObjectContactFriction = 250f;
  262. private float nmAvatarObjectContactBounce = 0.1f;
  263. private float mAvatarObjectContactFriction = 75f;
  264. private float mAvatarObjectContactBounce = 0.1f;
  265. private float avPIDD = 3200f;
  266. private float avPIDP = 1400f;
  267. private float avCapRadius = 0.37f;
  268. private float avStandupTensor = 2000000f;
  269. /// <summary>
  270. /// true = old compatibility mode with leaning capsule; false = new corrected mode
  271. /// </summary>
  272. /// <remarks>
  273. /// Even when set to false, the capsule still tilts but this is done in a different way.
  274. /// </remarks>
  275. public bool IsAvCapsuleTilted { get; private set; }
  276. private float avDensity = 80f;
  277. // private float avHeightFudgeFactor = 0.52f;
  278. private float avMovementDivisorWalk = 1.3f;
  279. private float avMovementDivisorRun = 0.8f;
  280. private float minimumGroundFlightOffset = 3f;
  281. public float maximumMassObject = 10000.01f;
  282. public bool meshSculptedPrim = true;
  283. public bool forceSimplePrimMeshing = false;
  284. public float meshSculptLOD = 32;
  285. public float MeshSculptphysicalLOD = 16;
  286. public float geomDefaultDensity = 10.000006836f;
  287. public int geomContactPointsStartthrottle = 3;
  288. public int geomUpdatesPerThrottledUpdate = 15;
  289. private const int avatarExpectedContacts = 3;
  290. public float bodyPIDD = 35f;
  291. public float bodyPIDG = 25;
  292. public int geomCrossingFailuresBeforeOutofbounds = 5;
  293. public float bodyMotorJointMaxforceTensor = 2;
  294. public int bodyFramesAutoDisable = 20;
  295. private float[] _watermap;
  296. private bool m_filterCollisions = true;
  297. private d.NearCallback nearCallback;
  298. public d.TriCallback triCallback;
  299. public d.TriArrayCallback triArrayCallback;
  300. /// <summary>
  301. /// Avatars in the physics scene.
  302. /// </summary>
  303. private readonly HashSet<OdeCharacter> _characters = new HashSet<OdeCharacter>();
  304. /// <summary>
  305. /// Prims in the physics scene.
  306. /// </summary>
  307. private readonly HashSet<OdePrim> _prims = new HashSet<OdePrim>();
  308. /// <summary>
  309. /// Prims in the physics scene that are subject to physics, not just collisions.
  310. /// </summary>
  311. private readonly HashSet<OdePrim> _activeprims = new HashSet<OdePrim>();
  312. /// <summary>
  313. /// Prims that the simulator has created/deleted/updated and so need updating in ODE.
  314. /// </summary>
  315. private readonly HashSet<OdePrim> _taintedPrims = new HashSet<OdePrim>();
  316. /// <summary>
  317. /// Record a character that has taints to be processed.
  318. /// </summary>
  319. private readonly HashSet<OdeCharacter> _taintedActors = new HashSet<OdeCharacter>();
  320. /// <summary>
  321. /// Keep record of contacts in the physics loop so that we can remove duplicates.
  322. /// </summary>
  323. private readonly List<d.ContactGeom> _perloopContact = new List<d.ContactGeom>();
  324. /// <summary>
  325. /// A dictionary of actors that should receive collision events.
  326. /// </summary>
  327. private readonly Dictionary<uint, PhysicsActor> m_collisionEventActors = new Dictionary<uint, PhysicsActor>();
  328. /// <summary>
  329. /// A dictionary of collision event changes that are waiting to be processed.
  330. /// </summary>
  331. private readonly Dictionary<uint, PhysicsActor> m_collisionEventActorsChanges = new Dictionary<uint, PhysicsActor>();
  332. /// <summary>
  333. /// Maps a unique geometry id (a memory location) to a physics actor name.
  334. /// </summary>
  335. /// <remarks>
  336. /// Only actors participating in collisions have geometries. This has to be maintained separately from
  337. /// actor_name_map because terrain and water currently don't conceptually have a physics actor of their own
  338. /// apart from the singleton PANull
  339. /// </remarks>
  340. public Dictionary<IntPtr, String> geom_name_map = new Dictionary<IntPtr, String>();
  341. /// <summary>
  342. /// Maps a unique geometry id (a memory location) to a physics actor.
  343. /// </summary>
  344. /// <remarks>
  345. /// Only actors participating in collisions have geometries.
  346. /// </remarks>
  347. public Dictionary<IntPtr, PhysicsActor> actor_name_map = new Dictionary<IntPtr, PhysicsActor>();
  348. /// <summary>
  349. /// Defects list to remove characters that no longer have finite positions due to some other bug.
  350. /// </summary>
  351. /// <remarks>
  352. /// Used repeatedly in Simulate() but initialized once here.
  353. /// </remarks>
  354. private readonly List<OdeCharacter> defects = new List<OdeCharacter>();
  355. private bool m_NINJA_physics_joints_enabled = false;
  356. //private Dictionary<String, IntPtr> jointpart_name_map = new Dictionary<String,IntPtr>();
  357. private readonly Dictionary<String, List<PhysicsJoint>> joints_connecting_actor = new Dictionary<String, List<PhysicsJoint>>();
  358. private d.ContactGeom[] contacts;
  359. /// <summary>
  360. /// Lock only briefly. accessed by external code (to request new joints) and by OdeScene.Simulate() to move those joints into pending/active
  361. /// </summary>
  362. private readonly List<PhysicsJoint> requestedJointsToBeCreated = new List<PhysicsJoint>();
  363. /// <summary>
  364. /// can lock for longer. accessed only by OdeScene.
  365. /// </summary>
  366. private readonly List<PhysicsJoint> pendingJoints = new List<PhysicsJoint>();
  367. /// <summary>
  368. /// can lock for longer. accessed only by OdeScene.
  369. /// </summary>
  370. private readonly List<PhysicsJoint> activeJoints = new List<PhysicsJoint>();
  371. /// <summary>
  372. /// lock only briefly. accessed by external code (to request deletion of joints) and by OdeScene.Simulate() to move those joints out of pending/active
  373. /// </summary>
  374. private readonly List<string> requestedJointsToBeDeleted = new List<string>();
  375. private Object externalJointRequestsLock = new Object();
  376. private readonly Dictionary<String, PhysicsJoint> SOPName_to_activeJoint = new Dictionary<String, PhysicsJoint>();
  377. private readonly Dictionary<String, PhysicsJoint> SOPName_to_pendingJoint = new Dictionary<String, PhysicsJoint>();
  378. private readonly DoubleDictionary<Vector3, IntPtr, IntPtr> RegionTerrain = new DoubleDictionary<Vector3, IntPtr, IntPtr>();
  379. private readonly Dictionary<IntPtr,float[]> TerrainHeightFieldHeights = new Dictionary<IntPtr, float[]>();
  380. private d.Contact contact;
  381. private d.Contact TerrainContact;
  382. private d.Contact AvatarMovementprimContact;
  383. private d.Contact AvatarMovementTerrainContact;
  384. private d.Contact WaterContact;
  385. private d.Contact[,] m_materialContacts;
  386. //Ckrinke: Comment out until used. We declare it, initialize it, but do not use it
  387. //Ckrinke private int m_randomizeWater = 200;
  388. private int m_physicsiterations = 10;
  389. private const float m_SkipFramesAtms = 0.40f; // Drop frames gracefully at a 400 ms lag
  390. private readonly PhysicsActor PANull = new NullPhysicsActor();
  391. // private float step_time = 0.0f;
  392. //Ckrinke: Comment out until used. We declare it, initialize it, but do not use it
  393. //Ckrinke private int ms = 0;
  394. public IntPtr world;
  395. //private bool returncollisions = false;
  396. // private uint obj1LocalID = 0;
  397. private uint obj2LocalID = 0;
  398. //private int ctype = 0;
  399. private OdeCharacter cc1;
  400. private OdePrim cp1;
  401. private OdeCharacter cc2;
  402. private OdePrim cp2;
  403. private int p1ExpectedPoints = 0;
  404. private int p2ExpectedPoints = 0;
  405. //private int cStartStop = 0;
  406. //private string cDictKey = "";
  407. public IntPtr space;
  408. //private IntPtr tmpSpace;
  409. // split static geometry collision handling into spaces of 30 meters
  410. public IntPtr[,] staticPrimspace;
  411. /// <summary>
  412. /// Used to lock the entire physics scene. Locked during the main part of Simulate()
  413. /// </summary>
  414. internal Object OdeLock = new Object();
  415. private bool _worldInitialized = false;
  416. public IMesher mesher;
  417. private IConfigSource m_config;
  418. public bool physics_logging = false;
  419. public int physics_logging_interval = 0;
  420. public bool physics_logging_append_existing_logfile = false;
  421. private bool avplanted = false;
  422. private bool av_av_collisions_off = false;
  423. public d.Vector3 xyz = new d.Vector3(128.1640f, 128.3079f, 25.7600f);
  424. public d.Vector3 hpr = new d.Vector3(125.5000f, -17.0000f, 0.0000f);
  425. // TODO: unused: private uint heightmapWidth = m_regionWidth + 1;
  426. // TODO: unused: private uint heightmapHeight = m_regionHeight + 1;
  427. // TODO: unused: private uint heightmapWidthSamples;
  428. // TODO: unused: private uint heightmapHeightSamples;
  429. private volatile int m_global_contactcount = 0;
  430. private Vector3 m_worldOffset = Vector3.Zero;
  431. public Vector2 WorldExtents = new Vector2((int)Constants.RegionSize, (int)Constants.RegionSize);
  432. private PhysicsScene m_parentScene = null;
  433. private ODERayCastRequestManager m_rayCastManager;
  434. #region INonSharedRegionModule
  435. public string Name
  436. {
  437. get { return "OpenDynamicsEngine"; }
  438. }
  439. public Type ReplaceableInterface
  440. {
  441. get { return null; }
  442. }
  443. public void Initialise(IConfigSource source)
  444. {
  445. // TODO: Move this out of Startup
  446. IConfig config = source.Configs["Startup"];
  447. if (config != null)
  448. {
  449. string physics = config.GetString("physics", string.Empty);
  450. if (physics == Name)
  451. {
  452. m_Enabled = true;
  453. m_config = source;
  454. // We do this so that OpenSimulator on Windows loads the correct native ODE library depending on whether
  455. // it's running as a 32-bit process or a 64-bit one. By invoking LoadLibary here, later DLLImports
  456. // will find it already loaded later on.
  457. //
  458. // This isn't necessary for other platforms (e.g. Mac OSX and Linux) since the DLL used can be
  459. // controlled in Ode.NET.dll.config
  460. if (Util.IsWindows())
  461. Util.LoadArchSpecificWindowsDll("ode.dll");
  462. // Initializing ODE only when a scene is created allows alternative ODE plugins to co-habit (according to
  463. // http://opensimulator.org/mantis/view.php?id=2750).
  464. d.InitODE();
  465. }
  466. }
  467. }
  468. public void Close()
  469. {
  470. }
  471. public void AddRegion(Scene scene)
  472. {
  473. if (!m_Enabled)
  474. return;
  475. EngineType = Name;
  476. PhysicsSceneName = EngineType + "/" + scene.RegionInfo.RegionName;
  477. scene.RegisterModuleInterface<PhysicsScene>(this);
  478. Vector3 extent = new Vector3(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY, scene.RegionInfo.RegionSizeZ);
  479. Initialise();
  480. InitialiseFromConfig(m_config);
  481. base.Initialise(scene.PhysicsRequestAsset, scene.Heightmap.GetFloatsSerialised(), (float)scene.RegionInfo.RegionSettings.WaterHeight);
  482. }
  483. public void RemoveRegion(Scene scene)
  484. {
  485. if (!m_Enabled)
  486. return;
  487. }
  488. public void RegionLoaded(Scene scene)
  489. {
  490. if (!m_Enabled)
  491. return;
  492. mesher = scene.RequestModuleInterface<IMesher>();
  493. if (mesher == null)
  494. m_log.WarnFormat("[ODE SCENE]: No mesher in {0}. Things will not work well.", PhysicsSceneName);
  495. }
  496. #endregion
  497. /// <summary>
  498. /// Initiailizes the scene
  499. /// Sets many properties that ODE requires to be stable
  500. /// These settings need to be tweaked 'exactly' right or weird stuff happens.
  501. /// </summary>
  502. private void Initialise()
  503. {
  504. nearCallback = near;
  505. triCallback = TriCallback;
  506. triArrayCallback = TriArrayCallback;
  507. m_rayCastManager = new ODERayCastRequestManager(this);
  508. // Create the world and the first space
  509. world = d.WorldCreate();
  510. space = d.HashSpaceCreate(IntPtr.Zero);
  511. contactgroup = d.JointGroupCreate(0);
  512. d.WorldSetAutoDisableFlag(world, false);
  513. #if USE_DRAWSTUFF
  514. Thread viewthread = new Thread(new ParameterizedThreadStart(startvisualization));
  515. viewthread.Start();
  516. #endif
  517. _watermap = new float[258 * 258];
  518. // Zero out the prim spaces array (we split our space into smaller spaces so
  519. // we can hit test less.
  520. }
  521. #if USE_DRAWSTUFF
  522. public void startvisualization(object o)
  523. {
  524. ds.Functions fn;
  525. fn.version = ds.VERSION;
  526. fn.start = new ds.CallbackFunction(start);
  527. fn.step = new ds.CallbackFunction(step);
  528. fn.command = new ds.CallbackFunction(command);
  529. fn.stop = null;
  530. fn.path_to_textures = "./textures";
  531. string[] args = new string[0];
  532. ds.SimulationLoop(args.Length, args, 352, 288, ref fn);
  533. }
  534. #endif
  535. // Initialize from configs
  536. private void InitialiseFromConfig(IConfigSource config)
  537. {
  538. InitializeExtraStats();
  539. m_config = config;
  540. // Defaults
  541. if (Environment.OSVersion.Platform == PlatformID.Unix)
  542. {
  543. avPIDD = 3200.0f;
  544. avPIDP = 1400.0f;
  545. avStandupTensor = 2000000f;
  546. }
  547. else
  548. {
  549. avPIDD = 2200.0f;
  550. avPIDP = 900.0f;
  551. avStandupTensor = 550000f;
  552. }
  553. int contactsPerCollision = 80;
  554. if (m_config != null)
  555. {
  556. IConfig physicsconfig = m_config.Configs["ODEPhysicsSettings"];
  557. if (physicsconfig != null)
  558. {
  559. CollectStats = physicsconfig.GetBoolean("collect_stats", false);
  560. gravityx = physicsconfig.GetFloat("world_gravityx", 0f);
  561. gravityy = physicsconfig.GetFloat("world_gravityy", 0f);
  562. gravityz = physicsconfig.GetFloat("world_gravityz", -9.8f);
  563. float avatarTerminalVelocity = physicsconfig.GetFloat("avatar_terminal_velocity", 54f);
  564. AvatarTerminalVelocity = Util.Clamp<float>(avatarTerminalVelocity, 0, 255f);
  565. if (AvatarTerminalVelocity != avatarTerminalVelocity)
  566. {
  567. m_log.WarnFormat(
  568. "[ODE SCENE]: avatar_terminal_velocity of {0} is invalid. Clamping to {1}",
  569. avatarTerminalVelocity, AvatarTerminalVelocity);
  570. }
  571. worldHashspaceLow = physicsconfig.GetInt("world_hashspace_size_low", -4);
  572. worldHashspaceHigh = physicsconfig.GetInt("world_hashspace_size_high", 128);
  573. metersInSpace = physicsconfig.GetFloat("meters_in_small_space", 29.9f);
  574. smallHashspaceLow = physicsconfig.GetInt("small_hashspace_size_low", -4);
  575. smallHashspaceHigh = physicsconfig.GetInt("small_hashspace_size_high", 66);
  576. contactsurfacelayer = physicsconfig.GetFloat("world_contact_surface_layer", 0.001f);
  577. nmTerrainContactFriction = physicsconfig.GetFloat("nm_terraincontact_friction", 255.0f);
  578. nmTerrainContactBounce = physicsconfig.GetFloat("nm_terraincontact_bounce", 0.1f);
  579. nmTerrainContactERP = physicsconfig.GetFloat("nm_terraincontact_erp", 0.1025f);
  580. mTerrainContactFriction = physicsconfig.GetFloat("m_terraincontact_friction", 75f);
  581. mTerrainContactBounce = physicsconfig.GetFloat("m_terraincontact_bounce", 0.05f);
  582. mTerrainContactERP = physicsconfig.GetFloat("m_terraincontact_erp", 0.05025f);
  583. nmAvatarObjectContactFriction = physicsconfig.GetFloat("objectcontact_friction", 250f);
  584. nmAvatarObjectContactBounce = physicsconfig.GetFloat("objectcontact_bounce", 0.2f);
  585. mAvatarObjectContactFriction = physicsconfig.GetFloat("m_avatarobjectcontact_friction", 75f);
  586. mAvatarObjectContactBounce = physicsconfig.GetFloat("m_avatarobjectcontact_bounce", 0.1f);
  587. ODE_STEPSIZE = physicsconfig.GetFloat("world_stepsize", ODE_STEPSIZE);
  588. m_physicsiterations = physicsconfig.GetInt("world_internal_steps_without_collisions", 10);
  589. avDensity = physicsconfig.GetFloat("av_density", 80f);
  590. // avHeightFudgeFactor = physicsconfig.GetFloat("av_height_fudge_factor", 0.52f);
  591. avMovementDivisorWalk = physicsconfig.GetFloat("av_movement_divisor_walk", 1.3f);
  592. avMovementDivisorRun = physicsconfig.GetFloat("av_movement_divisor_run", 0.8f);
  593. avCapRadius = physicsconfig.GetFloat("av_capsule_radius", 0.37f);
  594. avplanted = physicsconfig.GetBoolean("av_planted", false);
  595. av_av_collisions_off = physicsconfig.GetBoolean("av_av_collisions_off", false);
  596. IsAvCapsuleTilted = physicsconfig.GetBoolean("av_capsule_tilted", false);
  597. contactsPerCollision = physicsconfig.GetInt("contacts_per_collision", 80);
  598. geomContactPointsStartthrottle = physicsconfig.GetInt("geom_contactpoints_start_throttling", 5);
  599. geomUpdatesPerThrottledUpdate = physicsconfig.GetInt("geom_updates_before_throttled_update", 15);
  600. geomCrossingFailuresBeforeOutofbounds = physicsconfig.GetInt("geom_crossing_failures_before_outofbounds", 5);
  601. geomDefaultDensity = physicsconfig.GetFloat("geometry_default_density", 10.000006836f);
  602. bodyFramesAutoDisable = physicsconfig.GetInt("body_frames_auto_disable", 20);
  603. bodyPIDD = physicsconfig.GetFloat("body_pid_derivative", 35f);
  604. bodyPIDG = physicsconfig.GetFloat("body_pid_gain", 25f);
  605. forceSimplePrimMeshing = physicsconfig.GetBoolean("force_simple_prim_meshing", forceSimplePrimMeshing);
  606. meshSculptedPrim = physicsconfig.GetBoolean("mesh_sculpted_prim", true);
  607. meshSculptLOD = physicsconfig.GetFloat("mesh_lod", 32f);
  608. MeshSculptphysicalLOD = physicsconfig.GetFloat("mesh_physical_lod", 16f);
  609. m_filterCollisions = physicsconfig.GetBoolean("filter_collisions", false);
  610. if (Environment.OSVersion.Platform == PlatformID.Unix)
  611. {
  612. avPIDD = physicsconfig.GetFloat("av_pid_derivative_linux", 2200.0f);
  613. avPIDP = physicsconfig.GetFloat("av_pid_proportional_linux", 900.0f);
  614. avStandupTensor = physicsconfig.GetFloat("av_capsule_standup_tensor_linux", 550000f);
  615. bodyMotorJointMaxforceTensor = physicsconfig.GetFloat("body_motor_joint_maxforce_tensor_linux", 5f);
  616. }
  617. else
  618. {
  619. avPIDD = physicsconfig.GetFloat("av_pid_derivative_win", 2200.0f);
  620. avPIDP = physicsconfig.GetFloat("av_pid_proportional_win", 900.0f);
  621. avStandupTensor = physicsconfig.GetFloat("av_capsule_standup_tensor_win", 550000f);
  622. bodyMotorJointMaxforceTensor = physicsconfig.GetFloat("body_motor_joint_maxforce_tensor_win", 5f);
  623. }
  624. physics_logging = physicsconfig.GetBoolean("physics_logging", false);
  625. physics_logging_interval = physicsconfig.GetInt("physics_logging_interval", 0);
  626. physics_logging_append_existing_logfile = physicsconfig.GetBoolean("physics_logging_append_existing_logfile", false);
  627. m_NINJA_physics_joints_enabled = physicsconfig.GetBoolean("use_NINJA_physics_joints", false);
  628. minimumGroundFlightOffset = physicsconfig.GetFloat("minimum_ground_flight_offset", 3f);
  629. maximumMassObject = physicsconfig.GetFloat("maximum_mass_object", 10000.01f);
  630. }
  631. }
  632. contacts = new d.ContactGeom[contactsPerCollision];
  633. staticPrimspace = new IntPtr[(int)(300 / metersInSpace), (int)(300 / metersInSpace)];
  634. // Centeral contact friction and bounce
  635. // ckrinke 11/10/08 Enabling soft_erp but not soft_cfm until I figure out why
  636. // an avatar falls through in Z but not in X or Y when walking on a prim.
  637. contact.surface.mode |= d.ContactFlags.SoftERP;
  638. contact.surface.mu = nmAvatarObjectContactFriction;
  639. contact.surface.bounce = nmAvatarObjectContactBounce;
  640. contact.surface.soft_cfm = 0.010f;
  641. contact.surface.soft_erp = 0.010f;
  642. // Terrain contact friction and Bounce
  643. // This is the *non* moving version. Use this when an avatar
  644. // isn't moving to keep it in place better
  645. TerrainContact.surface.mode |= d.ContactFlags.SoftERP;
  646. TerrainContact.surface.mu = nmTerrainContactFriction;
  647. TerrainContact.surface.bounce = nmTerrainContactBounce;
  648. TerrainContact.surface.soft_erp = nmTerrainContactERP;
  649. WaterContact.surface.mode |= (d.ContactFlags.SoftERP | d.ContactFlags.SoftCFM);
  650. WaterContact.surface.mu = 0f; // No friction
  651. WaterContact.surface.bounce = 0.0f; // No bounce
  652. WaterContact.surface.soft_cfm = 0.010f;
  653. WaterContact.surface.soft_erp = 0.010f;
  654. // Prim contact friction and bounce
  655. // THis is the *non* moving version of friction and bounce
  656. // Use this when an avatar comes in contact with a prim
  657. // and is moving
  658. AvatarMovementprimContact.surface.mu = mAvatarObjectContactFriction;
  659. AvatarMovementprimContact.surface.bounce = mAvatarObjectContactBounce;
  660. // Terrain contact friction bounce and various error correcting calculations
  661. // Use this when an avatar is in contact with the terrain and moving.
  662. AvatarMovementTerrainContact.surface.mode |= d.ContactFlags.SoftERP;
  663. AvatarMovementTerrainContact.surface.mu = mTerrainContactFriction;
  664. AvatarMovementTerrainContact.surface.bounce = mTerrainContactBounce;
  665. AvatarMovementTerrainContact.surface.soft_erp = mTerrainContactERP;
  666. /*
  667. <summary></summary>
  668. Stone = 0,
  669. /// <summary></summary>
  670. Metal = 1,
  671. /// <summary></summary>
  672. Glass = 2,
  673. /// <summary></summary>
  674. Wood = 3,
  675. /// <summary></summary>
  676. Flesh = 4,
  677. /// <summary></summary>
  678. Plastic = 5,
  679. /// <summary></summary>
  680. Rubber = 6
  681. */
  682. m_materialContacts = new d.Contact[7,2];
  683. m_materialContacts[(int)Material.Stone, 0] = new d.Contact();
  684. m_materialContacts[(int)Material.Stone, 0].surface.mode |= d.ContactFlags.SoftERP;
  685. m_materialContacts[(int)Material.Stone, 0].surface.mu = nmAvatarObjectContactFriction;
  686. m_materialContacts[(int)Material.Stone, 0].surface.bounce = nmAvatarObjectContactBounce;
  687. m_materialContacts[(int)Material.Stone, 0].surface.soft_cfm = 0.010f;
  688. m_materialContacts[(int)Material.Stone, 0].surface.soft_erp = 0.010f;
  689. m_materialContacts[(int)Material.Stone, 1] = new d.Contact();
  690. m_materialContacts[(int)Material.Stone, 1].surface.mode |= d.ContactFlags.SoftERP;
  691. m_materialContacts[(int)Material.Stone, 1].surface.mu = mAvatarObjectContactFriction;
  692. m_materialContacts[(int)Material.Stone, 1].surface.bounce = mAvatarObjectContactBounce;
  693. m_materialContacts[(int)Material.Stone, 1].surface.soft_cfm = 0.010f;
  694. m_materialContacts[(int)Material.Stone, 1].surface.soft_erp = 0.010f;
  695. m_materialContacts[(int)Material.Metal, 0] = new d.Contact();
  696. m_materialContacts[(int)Material.Metal, 0].surface.mode |= d.ContactFlags.SoftERP;
  697. m_materialContacts[(int)Material.Metal, 0].surface.mu = nmAvatarObjectContactFriction;
  698. m_materialContacts[(int)Material.Metal, 0].surface.bounce = nmAvatarObjectContactBounce;
  699. m_materialContacts[(int)Material.Metal, 0].surface.soft_cfm = 0.010f;
  700. m_materialContacts[(int)Material.Metal, 0].surface.soft_erp = 0.010f;
  701. m_materialContacts[(int)Material.Metal, 1] = new d.Contact();
  702. m_materialContacts[(int)Material.Metal, 1].surface.mode |= d.ContactFlags.SoftERP;
  703. m_materialContacts[(int)Material.Metal, 1].surface.mu = mAvatarObjectContactFriction;
  704. m_materialContacts[(int)Material.Metal, 1].surface.bounce = mAvatarObjectContactBounce;
  705. m_materialContacts[(int)Material.Metal, 1].surface.soft_cfm = 0.010f;
  706. m_materialContacts[(int)Material.Metal, 1].surface.soft_erp = 0.010f;
  707. m_materialContacts[(int)Material.Glass, 0] = new d.Contact();
  708. m_materialContacts[(int)Material.Glass, 0].surface.mode |= d.ContactFlags.SoftERP;
  709. m_materialContacts[(int)Material.Glass, 0].surface.mu = 1f;
  710. m_materialContacts[(int)Material.Glass, 0].surface.bounce = 0.5f;
  711. m_materialContacts[(int)Material.Glass, 0].surface.soft_cfm = 0.010f;
  712. m_materialContacts[(int)Material.Glass, 0].surface.soft_erp = 0.010f;
  713. /*
  714. private float nmAvatarObjectContactFriction = 250f;
  715. private float nmAvatarObjectContactBounce = 0.1f;
  716. private float mAvatarObjectContactFriction = 75f;
  717. private float mAvatarObjectContactBounce = 0.1f;
  718. */
  719. m_materialContacts[(int)Material.Glass, 1] = new d.Contact();
  720. m_materialContacts[(int)Material.Glass, 1].surface.mode |= d.ContactFlags.SoftERP;
  721. m_materialContacts[(int)Material.Glass, 1].surface.mu = 1f;
  722. m_materialContacts[(int)Material.Glass, 1].surface.bounce = 0.5f;
  723. m_materialContacts[(int)Material.Glass, 1].surface.soft_cfm = 0.010f;
  724. m_materialContacts[(int)Material.Glass, 1].surface.soft_erp = 0.010f;
  725. m_materialContacts[(int)Material.Wood, 0] = new d.Contact();
  726. m_materialContacts[(int)Material.Wood, 0].surface.mode |= d.ContactFlags.SoftERP;
  727. m_materialContacts[(int)Material.Wood, 0].surface.mu = nmAvatarObjectContactFriction;
  728. m_materialContacts[(int)Material.Wood, 0].surface.bounce = nmAvatarObjectContactBounce;
  729. m_materialContacts[(int)Material.Wood, 0].surface.soft_cfm = 0.010f;
  730. m_materialContacts[(int)Material.Wood, 0].surface.soft_erp = 0.010f;
  731. m_materialContacts[(int)Material.Wood, 1] = new d.Contact();
  732. m_materialContacts[(int)Material.Wood, 1].surface.mode |= d.ContactFlags.SoftERP;
  733. m_materialContacts[(int)Material.Wood, 1].surface.mu = mAvatarObjectContactFriction;
  734. m_materialContacts[(int)Material.Wood, 1].surface.bounce = mAvatarObjectContactBounce;
  735. m_materialContacts[(int)Material.Wood, 1].surface.soft_cfm = 0.010f;
  736. m_materialContacts[(int)Material.Wood, 1].surface.soft_erp = 0.010f;
  737. m_materialContacts[(int)Material.Flesh, 0] = new d.Contact();
  738. m_materialContacts[(int)Material.Flesh, 0].surface.mode |= d.ContactFlags.SoftERP;
  739. m_materialContacts[(int)Material.Flesh, 0].surface.mu = nmAvatarObjectContactFriction;
  740. m_materialContacts[(int)Material.Flesh, 0].surface.bounce = nmAvatarObjectContactBounce;
  741. m_materialContacts[(int)Material.Flesh, 0].surface.soft_cfm = 0.010f;
  742. m_materialContacts[(int)Material.Flesh, 0].surface.soft_erp = 0.010f;
  743. m_materialContacts[(int)Material.Flesh, 1] = new d.Contact();
  744. m_materialContacts[(int)Material.Flesh, 1].surface.mode |= d.ContactFlags.SoftERP;
  745. m_materialContacts[(int)Material.Flesh, 1].surface.mu = mAvatarObjectContactFriction;
  746. m_materialContacts[(int)Material.Flesh, 1].surface.bounce = mAvatarObjectContactBounce;
  747. m_materialContacts[(int)Material.Flesh, 1].surface.soft_cfm = 0.010f;
  748. m_materialContacts[(int)Material.Flesh, 1].surface.soft_erp = 0.010f;
  749. m_materialContacts[(int)Material.Plastic, 0] = new d.Contact();
  750. m_materialContacts[(int)Material.Plastic, 0].surface.mode |= d.ContactFlags.SoftERP;
  751. m_materialContacts[(int)Material.Plastic, 0].surface.mu = nmAvatarObjectContactFriction;
  752. m_materialContacts[(int)Material.Plastic, 0].surface.bounce = nmAvatarObjectContactBounce;
  753. m_materialContacts[(int)Material.Plastic, 0].surface.soft_cfm = 0.010f;
  754. m_materialContacts[(int)Material.Plastic, 0].surface.soft_erp = 0.010f;
  755. m_materialContacts[(int)Material.Plastic, 1] = new d.Contact();
  756. m_materialContacts[(int)Material.Plastic, 1].surface.mode |= d.ContactFlags.SoftERP;
  757. m_materialContacts[(int)Material.Plastic, 1].surface.mu = mAvatarObjectContactFriction;
  758. m_materialContacts[(int)Material.Plastic, 1].surface.bounce = mAvatarObjectContactBounce;
  759. m_materialContacts[(int)Material.Plastic, 1].surface.soft_cfm = 0.010f;
  760. m_materialContacts[(int)Material.Plastic, 1].surface.soft_erp = 0.010f;
  761. m_materialContacts[(int)Material.Rubber, 0] = new d.Contact();
  762. m_materialContacts[(int)Material.Rubber, 0].surface.mode |= d.ContactFlags.SoftERP;
  763. m_materialContacts[(int)Material.Rubber, 0].surface.mu = nmAvatarObjectContactFriction;
  764. m_materialContacts[(int)Material.Rubber, 0].surface.bounce = nmAvatarObjectContactBounce;
  765. m_materialContacts[(int)Material.Rubber, 0].surface.soft_cfm = 0.010f;
  766. m_materialContacts[(int)Material.Rubber, 0].surface.soft_erp = 0.010f;
  767. m_materialContacts[(int)Material.Rubber, 1] = new d.Contact();
  768. m_materialContacts[(int)Material.Rubber, 1].surface.mode |= d.ContactFlags.SoftERP;
  769. m_materialContacts[(int)Material.Rubber, 1].surface.mu = mAvatarObjectContactFriction;
  770. m_materialContacts[(int)Material.Rubber, 1].surface.bounce = mAvatarObjectContactBounce;
  771. m_materialContacts[(int)Material.Rubber, 1].surface.soft_cfm = 0.010f;
  772. m_materialContacts[(int)Material.Rubber, 1].surface.soft_erp = 0.010f;
  773. d.HashSpaceSetLevels(space, worldHashspaceLow, worldHashspaceHigh);
  774. // Set the gravity,, don't disable things automatically (we set it explicitly on some things)
  775. d.WorldSetGravity(world, gravityx, gravityy, gravityz);
  776. d.WorldSetContactSurfaceLayer(world, contactsurfacelayer);
  777. d.WorldSetLinearDamping(world, 256f);
  778. d.WorldSetAngularDamping(world, 256f);
  779. d.WorldSetAngularDampingThreshold(world, 256f);
  780. d.WorldSetLinearDampingThreshold(world, 256f);
  781. d.WorldSetMaxAngularSpeed(world, 256f);
  782. // Set how many steps we go without running collision testing
  783. // This is in addition to the step size.
  784. // Essentially Steps * m_physicsiterations
  785. d.WorldSetQuickStepNumIterations(world, m_physicsiterations);
  786. //d.WorldSetContactMaxCorrectingVel(world, 1000.0f);
  787. for (int i = 0; i < staticPrimspace.GetLength(0); i++)
  788. {
  789. for (int j = 0; j < staticPrimspace.GetLength(1); j++)
  790. {
  791. staticPrimspace[i, j] = IntPtr.Zero;
  792. }
  793. }
  794. _worldInitialized = true;
  795. }
  796. // internal void waitForSpaceUnlock(IntPtr space)
  797. // {
  798. // //if (space != IntPtr.Zero)
  799. // //while (d.SpaceLockQuery(space)) { } // Wait and do nothing
  800. // }
  801. // /// <summary>
  802. // /// Debug space message for printing the space that a prim/avatar is in.
  803. // /// </summary>
  804. // /// <param name="pos"></param>
  805. // /// <returns>Returns which split up space the given position is in.</returns>
  806. // public string whichspaceamIin(Vector3 pos)
  807. // {
  808. // return calculateSpaceForGeom(pos).ToString();
  809. // }
  810. #region Collision Detection
  811. /// <summary>
  812. /// Collides two geometries.
  813. /// </summary>
  814. /// <returns></returns>
  815. /// <param name='geom1'></param>
  816. /// <param name='geom2'>/param>
  817. /// <param name='maxContacts'></param>
  818. /// <param name='contactsArray'></param>
  819. /// <param name='contactGeomSize'></param>
  820. private int CollideGeoms(
  821. IntPtr geom1, IntPtr geom2, int maxContacts, Ode.NET.d.ContactGeom[] contactsArray, int contactGeomSize)
  822. {
  823. int count;
  824. lock (OdeScene.UniversalColliderSyncObject)
  825. {
  826. // We do this inside the lock so that we don't count any delay in acquiring it
  827. if (CollectStats)
  828. m_nativeCollisionStartTick = Util.EnvironmentTickCount();
  829. count = d.Collide(geom1, geom2, maxContacts, contactsArray, contactGeomSize);
  830. }
  831. // We do this outside the lock so that any waiting threads aren't held up, though the effect is probably
  832. // negligable
  833. if (CollectStats)
  834. m_stats[ODENativeGeomCollisionFrameMsStatName]
  835. += Util.EnvironmentTickCountSubtract(m_nativeCollisionStartTick);
  836. return count;
  837. }
  838. /// <summary>
  839. /// Collide two spaces or a space and a geometry.
  840. /// </summary>
  841. /// <param name='space1'></param>
  842. /// <param name='space2'>/param>
  843. /// <param name='data'></param>
  844. private void CollideSpaces(IntPtr space1, IntPtr space2, IntPtr data)
  845. {
  846. if (CollectStats)
  847. {
  848. m_inCollisionTiming = true;
  849. m_nativeCollisionStartTick = Util.EnvironmentTickCount();
  850. }
  851. d.SpaceCollide2(space1, space2, data, nearCallback);
  852. if (CollectStats && m_inCollisionTiming)
  853. {
  854. m_stats[ODENativeSpaceCollisionFrameMsStatName]
  855. += Util.EnvironmentTickCountSubtract(m_nativeCollisionStartTick);
  856. m_inCollisionTiming = false;
  857. }
  858. }
  859. /// <summary>
  860. /// This is our near callback. A geometry is near a body
  861. /// </summary>
  862. /// <param name="space">The space that contains the geoms. Remember, spaces are also geoms</param>
  863. /// <param name="g1">a geometry or space</param>
  864. /// <param name="g2">another geometry or space</param>
  865. private void near(IntPtr space, IntPtr g1, IntPtr g2)
  866. {
  867. if (CollectStats && m_inCollisionTiming)
  868. {
  869. m_stats[ODENativeSpaceCollisionFrameMsStatName]
  870. += Util.EnvironmentTickCountSubtract(m_nativeCollisionStartTick);
  871. m_inCollisionTiming = false;
  872. }
  873. // m_log.DebugFormat("[PHYSICS]: Colliding {0} and {1} in {2}", g1, g2, space);
  874. // no lock here! It's invoked from within Simulate(), which is thread-locked
  875. // Test if we're colliding a geom with a space.
  876. // If so we have to drill down into the space recursively
  877. if (d.GeomIsSpace(g1) || d.GeomIsSpace(g2))
  878. {
  879. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  880. return;
  881. // Separating static prim geometry spaces.
  882. // We'll be calling near recursivly if one
  883. // of them is a space to find all of the
  884. // contact points in the space
  885. try
  886. {
  887. CollideSpaces(g1, g2, IntPtr.Zero);
  888. }
  889. catch (AccessViolationException)
  890. {
  891. m_log.Error("[ODE SCENE]: Unable to collide test a space");
  892. return;
  893. }
  894. //Colliding a space or a geom with a space or a geom. so drill down
  895. //Collide all geoms in each space..
  896. //if (d.GeomIsSpace(g1)) d.SpaceCollide(g1, IntPtr.Zero, nearCallback);
  897. //if (d.GeomIsSpace(g2)) d.SpaceCollide(g2, IntPtr.Zero, nearCallback);
  898. return;
  899. }
  900. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  901. return;
  902. IntPtr b1 = d.GeomGetBody(g1);
  903. IntPtr b2 = d.GeomGetBody(g2);
  904. // d.GeomClassID id = d.GeomGetClass(g1);
  905. String name1 = null;
  906. String name2 = null;
  907. if (!geom_name_map.TryGetValue(g1, out name1))
  908. {
  909. name1 = "null";
  910. }
  911. if (!geom_name_map.TryGetValue(g2, out name2))
  912. {
  913. name2 = "null";
  914. }
  915. //if (id == d.GeomClassId.TriMeshClass)
  916. //{
  917. // m_log.InfoFormat("near: A collision was detected between {1} and {2}", 0, name1, name2);
  918. //m_log.Debug("near: A collision was detected between {1} and {2}", 0, name1, name2);
  919. //}
  920. // Figure out how many contact points we have
  921. int count = 0;
  922. try
  923. {
  924. // Colliding Geom To Geom
  925. // This portion of the function 'was' blatantly ripped off from BoxStack.cs
  926. if (g1 == g2)
  927. return; // Can't collide with yourself
  928. if (b1 != IntPtr.Zero && b2 != IntPtr.Zero && d.AreConnectedExcluding(b1, b2, d.JointType.Contact))
  929. return;
  930. count = CollideGeoms(g1, g2, contacts.Length, contacts, d.ContactGeom.SizeOf);
  931. // All code after this is only relevant if we have any collisions
  932. if (count <= 0)
  933. return;
  934. if (count > contacts.Length)
  935. m_log.Error("[ODE SCENE]: Got " + count + " contacts when we asked for a maximum of " + contacts.Length);
  936. }
  937. catch (SEHException)
  938. {
  939. m_log.Error(
  940. "[ODE SCENE]: The Operating system shut down ODE because of corrupt memory. This could be a result of really irregular terrain. If this repeats continuously, restart using Basic Physics and terrain fill your terrain. Restarting the sim.");
  941. base.TriggerPhysicsBasedRestart();
  942. }
  943. catch (Exception e)
  944. {
  945. m_log.ErrorFormat("[ODE SCENE]: Unable to collide test an object: {0}", e.Message);
  946. return;
  947. }
  948. PhysicsActor p1;
  949. PhysicsActor p2;
  950. p1ExpectedPoints = 0;
  951. p2ExpectedPoints = 0;
  952. if (!actor_name_map.TryGetValue(g1, out p1))
  953. {
  954. p1 = PANull;
  955. }
  956. if (!actor_name_map.TryGetValue(g2, out p2))
  957. {
  958. p2 = PANull;
  959. }
  960. ContactPoint maxDepthContact = new ContactPoint();
  961. if (p1.CollisionScore + count >= float.MaxValue)
  962. p1.CollisionScore = 0;
  963. p1.CollisionScore += count;
  964. if (p2.CollisionScore + count >= float.MaxValue)
  965. p2.CollisionScore = 0;
  966. p2.CollisionScore += count;
  967. for (int i = 0; i < count; i++)
  968. {
  969. d.ContactGeom curContact = contacts[i];
  970. if (curContact.depth > maxDepthContact.PenetrationDepth)
  971. {
  972. maxDepthContact = new ContactPoint(
  973. new Vector3(curContact.pos.X, curContact.pos.Y, curContact.pos.Z),
  974. new Vector3(curContact.normal.X, curContact.normal.Y, curContact.normal.Z),
  975. curContact.depth
  976. );
  977. }
  978. //m_log.Warn("[CCOUNT]: " + count);
  979. IntPtr joint;
  980. // If we're colliding with terrain, use 'TerrainContact' instead of contact.
  981. // allows us to have different settings
  982. // We only need to test p2 for 'jump crouch purposes'
  983. if (p2 is OdeCharacter && p1.PhysicsActorType == (int)ActorTypes.Prim)
  984. {
  985. // Testing if the collision is at the feet of the avatar
  986. //m_log.DebugFormat("[PHYSICS]: {0} - {1} - {2} - {3}", curContact.pos.Z, p2.Position.Z, (p2.Position.Z - curContact.pos.Z), (p2.Size.Z * 0.6f));
  987. if ((p2.Position.Z - curContact.pos.Z) > (p2.Size.Z * 0.6f))
  988. p2.IsColliding = true;
  989. }
  990. else
  991. {
  992. p2.IsColliding = true;
  993. }
  994. //if ((framecount % m_returncollisions) == 0)
  995. switch (p1.PhysicsActorType)
  996. {
  997. case (int)ActorTypes.Agent:
  998. p1ExpectedPoints = avatarExpectedContacts;
  999. p2.CollidingObj = true;
  1000. break;
  1001. case (int)ActorTypes.Prim:
  1002. if (p1 != null && p1 is OdePrim)
  1003. p1ExpectedPoints = ((OdePrim) p1).ExpectedCollisionContacts;
  1004. if (p2.Velocity.LengthSquared() > 0.0f)
  1005. p2.CollidingObj = true;
  1006. break;
  1007. case (int)ActorTypes.Unknown:
  1008. p2.CollidingGround = true;
  1009. break;
  1010. default:
  1011. p2.CollidingGround = true;
  1012. break;
  1013. }
  1014. // we don't want prim or avatar to explode
  1015. #region InterPenetration Handling - Unintended physics explosions
  1016. # region disabled code1
  1017. if (curContact.depth >= 0.08f)
  1018. {
  1019. //This is disabled at the moment only because it needs more tweaking
  1020. //It will eventually be uncommented
  1021. /*
  1022. if (contact.depth >= 1.00f)
  1023. {
  1024. //m_log.Debug("[PHYSICS]: " + contact.depth.ToString());
  1025. }
  1026. //If you interpenetrate a prim with an agent
  1027. if ((p2.PhysicsActorType == (int) ActorTypes.Agent &&
  1028. p1.PhysicsActorType == (int) ActorTypes.Prim) ||
  1029. (p1.PhysicsActorType == (int) ActorTypes.Agent &&
  1030. p2.PhysicsActorType == (int) ActorTypes.Prim))
  1031. {
  1032. //contact.depth = contact.depth * 4.15f;
  1033. /*
  1034. if (p2.PhysicsActorType == (int) ActorTypes.Agent)
  1035. {
  1036. p2.CollidingObj = true;
  1037. contact.depth = 0.003f;
  1038. p2.Velocity = p2.Velocity + new PhysicsVector(0, 0, 2.5f);
  1039. OdeCharacter character = (OdeCharacter) p2;
  1040. character.SetPidStatus(true);
  1041. contact.pos = new d.Vector3(contact.pos.X + (p1.Size.X / 2), contact.pos.Y + (p1.Size.Y / 2), contact.pos.Z + (p1.Size.Z / 2));
  1042. }
  1043. else
  1044. {
  1045. //contact.depth = 0.0000000f;
  1046. }
  1047. if (p1.PhysicsActorType == (int) ActorTypes.Agent)
  1048. {
  1049. p1.CollidingObj = true;
  1050. contact.depth = 0.003f;
  1051. p1.Velocity = p1.Velocity + new PhysicsVector(0, 0, 2.5f);
  1052. contact.pos = new d.Vector3(contact.pos.X + (p2.Size.X / 2), contact.pos.Y + (p2.Size.Y / 2), contact.pos.Z + (p2.Size.Z / 2));
  1053. OdeCharacter character = (OdeCharacter)p1;
  1054. character.SetPidStatus(true);
  1055. }
  1056. else
  1057. {
  1058. //contact.depth = 0.0000000f;
  1059. }
  1060. }
  1061. */
  1062. // If you interpenetrate a prim with another prim
  1063. /*
  1064. if (p1.PhysicsActorType == (int) ActorTypes.Prim && p2.PhysicsActorType == (int) ActorTypes.Prim)
  1065. {
  1066. #region disabledcode2
  1067. //OdePrim op1 = (OdePrim)p1;
  1068. //OdePrim op2 = (OdePrim)p2;
  1069. //op1.m_collisionscore++;
  1070. //op2.m_collisionscore++;
  1071. //if (op1.m_collisionscore > 8000 || op2.m_collisionscore > 8000)
  1072. //{
  1073. //op1.m_taintdisable = true;
  1074. //AddPhysicsActorTaint(p1);
  1075. //op2.m_taintdisable = true;
  1076. //AddPhysicsActorTaint(p2);
  1077. //}
  1078. //if (contact.depth >= 0.25f)
  1079. //{
  1080. // Don't collide, one or both prim will expld.
  1081. //op1.m_interpenetrationcount++;
  1082. //op2.m_interpenetrationcount++;
  1083. //interpenetrations_before_disable = 200;
  1084. //if (op1.m_interpenetrationcount >= interpenetrations_before_disable)
  1085. //{
  1086. //op1.m_taintdisable = true;
  1087. //AddPhysicsActorTaint(p1);
  1088. //}
  1089. //if (op2.m_interpenetrationcount >= interpenetrations_before_disable)
  1090. //{
  1091. // op2.m_taintdisable = true;
  1092. //AddPhysicsActorTaint(p2);
  1093. //}
  1094. //contact.depth = contact.depth / 8f;
  1095. //contact.normal = new d.Vector3(0, 0, 1);
  1096. //}
  1097. //if (op1.m_disabled || op2.m_disabled)
  1098. //{
  1099. //Manually disabled objects stay disabled
  1100. //contact.depth = 0f;
  1101. //}
  1102. #endregion
  1103. }
  1104. */
  1105. #endregion
  1106. if (curContact.depth >= 1.00f)
  1107. {
  1108. //m_log.Info("[P]: " + contact.depth.ToString());
  1109. if ((p2.PhysicsActorType == (int) ActorTypes.Agent &&
  1110. p1.PhysicsActorType == (int) ActorTypes.Unknown) ||
  1111. (p1.PhysicsActorType == (int) ActorTypes.Agent &&
  1112. p2.PhysicsActorType == (int) ActorTypes.Unknown))
  1113. {
  1114. if (p2.PhysicsActorType == (int) ActorTypes.Agent)
  1115. {
  1116. if (p2 is OdeCharacter)
  1117. {
  1118. OdeCharacter character = (OdeCharacter) p2;
  1119. //p2.CollidingObj = true;
  1120. curContact.depth = 0.00000003f;
  1121. p2.Velocity = p2.Velocity + new Vector3(0f, 0f, 0.5f);
  1122. curContact.pos =
  1123. new d.Vector3(curContact.pos.X + (p1.Size.X/2),
  1124. curContact.pos.Y + (p1.Size.Y/2),
  1125. curContact.pos.Z + (p1.Size.Z/2));
  1126. character.SetPidStatus(true);
  1127. }
  1128. }
  1129. if (p1.PhysicsActorType == (int) ActorTypes.Agent)
  1130. {
  1131. if (p1 is OdeCharacter)
  1132. {
  1133. OdeCharacter character = (OdeCharacter) p1;
  1134. //p2.CollidingObj = true;
  1135. curContact.depth = 0.00000003f;
  1136. p1.Velocity = p1.Velocity + new Vector3(0f, 0f, 0.5f);
  1137. curContact.pos =
  1138. new d.Vector3(curContact.pos.X + (p1.Size.X/2),
  1139. curContact.pos.Y + (p1.Size.Y/2),
  1140. curContact.pos.Z + (p1.Size.Z/2));
  1141. character.SetPidStatus(true);
  1142. }
  1143. }
  1144. }
  1145. }
  1146. }
  1147. #endregion
  1148. // Logic for collision handling
  1149. // Note, that if *all* contacts are skipped (VolumeDetect)
  1150. // The prim still detects (and forwards) collision events but
  1151. // appears to be phantom for the world
  1152. Boolean skipThisContact = false;
  1153. if ((p1 is OdePrim) && (((OdePrim)p1).m_isVolumeDetect))
  1154. skipThisContact = true; // No collision on volume detect prims
  1155. if (av_av_collisions_off)
  1156. if ((p1 is OdeCharacter) && (p2 is OdeCharacter))
  1157. skipThisContact = true;
  1158. if (!skipThisContact && (p2 is OdePrim) && (((OdePrim)p2).m_isVolumeDetect))
  1159. skipThisContact = true; // No collision on volume detect prims
  1160. if (!skipThisContact && curContact.depth < 0f)
  1161. skipThisContact = true;
  1162. if (!skipThisContact && checkDupe(curContact, p2.PhysicsActorType))
  1163. skipThisContact = true;
  1164. const int maxContactsbeforedeath = 4000;
  1165. joint = IntPtr.Zero;
  1166. if (!skipThisContact)
  1167. {
  1168. _perloopContact.Add(curContact);
  1169. if (name1 == "Terrain" || name2 == "Terrain")
  1170. {
  1171. if ((p2.PhysicsActorType == (int) ActorTypes.Agent) &&
  1172. (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f))
  1173. {
  1174. p2ExpectedPoints = avatarExpectedContacts;
  1175. // Avatar is moving on terrain, use the movement terrain contact
  1176. AvatarMovementTerrainContact.geom = curContact;
  1177. if (m_global_contactcount < maxContactsbeforedeath)
  1178. {
  1179. joint = d.JointCreateContact(world, contactgroup, ref AvatarMovementTerrainContact);
  1180. m_global_contactcount++;
  1181. }
  1182. }
  1183. else
  1184. {
  1185. if (p2.PhysicsActorType == (int)ActorTypes.Agent)
  1186. {
  1187. p2ExpectedPoints = avatarExpectedContacts;
  1188. // Avatar is standing on terrain, use the non moving terrain contact
  1189. TerrainContact.geom = curContact;
  1190. if (m_global_contactcount < maxContactsbeforedeath)
  1191. {
  1192. joint = d.JointCreateContact(world, contactgroup, ref TerrainContact);
  1193. m_global_contactcount++;
  1194. }
  1195. }
  1196. else
  1197. {
  1198. if (p2.PhysicsActorType == (int)ActorTypes.Prim && p1.PhysicsActorType == (int)ActorTypes.Prim)
  1199. {
  1200. // prim prim contact
  1201. // int pj294950 = 0;
  1202. int movintYN = 0;
  1203. int material = (int) Material.Wood;
  1204. // prim terrain contact
  1205. if (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f)
  1206. {
  1207. movintYN = 1;
  1208. }
  1209. if (p2 is OdePrim)
  1210. {
  1211. material = ((OdePrim) p2).m_material;
  1212. p2ExpectedPoints = ((OdePrim)p2).ExpectedCollisionContacts;
  1213. }
  1214. // Unnessesary because p1 is defined above
  1215. //if (p1 is OdePrim)
  1216. // {
  1217. // p1ExpectedPoints = ((OdePrim)p1).ExpectedCollisionContacts;
  1218. // }
  1219. //m_log.DebugFormat("Material: {0}", material);
  1220. m_materialContacts[material, movintYN].geom = curContact;
  1221. if (m_global_contactcount < maxContactsbeforedeath)
  1222. {
  1223. joint = d.JointCreateContact(world, contactgroup, ref m_materialContacts[material, movintYN]);
  1224. m_global_contactcount++;
  1225. }
  1226. }
  1227. else
  1228. {
  1229. int movintYN = 0;
  1230. // prim terrain contact
  1231. if (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f)
  1232. {
  1233. movintYN = 1;
  1234. }
  1235. int material = (int)Material.Wood;
  1236. if (p2 is OdePrim)
  1237. {
  1238. material = ((OdePrim)p2).m_material;
  1239. p2ExpectedPoints = ((OdePrim)p2).ExpectedCollisionContacts;
  1240. }
  1241. //m_log.DebugFormat("Material: {0}", material);
  1242. m_materialContacts[material, movintYN].geom = curContact;
  1243. if (m_global_contactcount < maxContactsbeforedeath)
  1244. {
  1245. joint = d.JointCreateContact(world, contactgroup, ref m_materialContacts[material, movintYN]);
  1246. m_global_contactcount++;
  1247. }
  1248. }
  1249. }
  1250. }
  1251. //if (p2.PhysicsActorType == (int)ActorTypes.Prim)
  1252. //{
  1253. //m_log.Debug("[PHYSICS]: prim contacting with ground");
  1254. //}
  1255. }
  1256. else if (name1 == "Water" || name2 == "Water")
  1257. {
  1258. /*
  1259. if ((p2.PhysicsActorType == (int) ActorTypes.Prim))
  1260. {
  1261. }
  1262. else
  1263. {
  1264. }
  1265. */
  1266. //WaterContact.surface.soft_cfm = 0.0000f;
  1267. //WaterContact.surface.soft_erp = 0.00000f;
  1268. if (curContact.depth > 0.1f)
  1269. {
  1270. curContact.depth *= 52;
  1271. //contact.normal = new d.Vector3(0, 0, 1);
  1272. //contact.pos = new d.Vector3(0, 0, contact.pos.Z - 5f);
  1273. }
  1274. WaterContact.geom = curContact;
  1275. if (m_global_contactcount < maxContactsbeforedeath)
  1276. {
  1277. joint = d.JointCreateContact(world, contactgroup, ref WaterContact);
  1278. m_global_contactcount++;
  1279. }
  1280. //m_log.Info("[PHYSICS]: Prim Water Contact" + contact.depth);
  1281. }
  1282. else
  1283. {
  1284. if ((p2.PhysicsActorType == (int)ActorTypes.Agent))
  1285. {
  1286. p2ExpectedPoints = avatarExpectedContacts;
  1287. if ((Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f))
  1288. {
  1289. // Avatar is moving on a prim, use the Movement prim contact
  1290. AvatarMovementprimContact.geom = curContact;
  1291. if (m_global_contactcount < maxContactsbeforedeath)
  1292. {
  1293. joint = d.JointCreateContact(world, contactgroup, ref AvatarMovementprimContact);
  1294. m_global_contactcount++;
  1295. }
  1296. }
  1297. else
  1298. {
  1299. // Avatar is standing still on a prim, use the non movement contact
  1300. contact.geom = curContact;
  1301. if (m_global_contactcount < maxContactsbeforedeath)
  1302. {
  1303. joint = d.JointCreateContact(world, contactgroup, ref contact);
  1304. m_global_contactcount++;
  1305. }
  1306. }
  1307. }
  1308. else if (p2.PhysicsActorType == (int)ActorTypes.Prim)
  1309. {
  1310. //p1.PhysicsActorType
  1311. int material = (int)Material.Wood;
  1312. if (p2 is OdePrim)
  1313. {
  1314. material = ((OdePrim)p2).m_material;
  1315. p2ExpectedPoints = ((OdePrim)p2).ExpectedCollisionContacts;
  1316. }
  1317. //m_log.DebugFormat("Material: {0}", material);
  1318. m_materialContacts[material, 0].geom = curContact;
  1319. if (m_global_contactcount < maxContactsbeforedeath)
  1320. {
  1321. joint = d.JointCreateContact(world, contactgroup, ref m_materialContacts[material, 0]);
  1322. m_global_contactcount++;
  1323. }
  1324. }
  1325. }
  1326. if (m_global_contactcount < maxContactsbeforedeath && joint != IntPtr.Zero) // stack collide!
  1327. {
  1328. d.JointAttach(joint, b1, b2);
  1329. m_global_contactcount++;
  1330. }
  1331. }
  1332. collision_accounting_events(p1, p2, maxDepthContact);
  1333. if (count > ((p1ExpectedPoints + p2ExpectedPoints) * 0.25) + (geomContactPointsStartthrottle))
  1334. {
  1335. // If there are more then 3 contact points, it's likely
  1336. // that we've got a pile of objects, so ...
  1337. // We don't want to send out hundreds of terse updates over and over again
  1338. // so lets throttle them and send them again after it's somewhat sorted out.
  1339. p2.ThrottleUpdates = true;
  1340. }
  1341. //m_log.Debug(count.ToString());
  1342. //m_log.Debug("near: A collision was detected between {1} and {2}", 0, name1, name2);
  1343. }
  1344. }
  1345. private bool checkDupe(d.ContactGeom contactGeom, int atype)
  1346. {
  1347. if (!m_filterCollisions)
  1348. return false;
  1349. bool result = false;
  1350. ActorTypes at = (ActorTypes)atype;
  1351. foreach (d.ContactGeom contact in _perloopContact)
  1352. {
  1353. //if ((contact.g1 == contactGeom.g1 && contact.g2 == contactGeom.g2))
  1354. //{
  1355. // || (contact.g2 == contactGeom.g1 && contact.g1 == contactGeom.g2)
  1356. if (at == ActorTypes.Agent)
  1357. {
  1358. if (((Math.Abs(contactGeom.normal.X - contact.normal.X) < 1.026f)
  1359. && (Math.Abs(contactGeom.normal.Y - contact.normal.Y) < 0.303f)
  1360. && (Math.Abs(contactGeom.normal.Z - contact.normal.Z) < 0.065f)))
  1361. {
  1362. if (Math.Abs(contact.depth - contactGeom.depth) < 0.052f)
  1363. {
  1364. //contactGeom.depth *= .00005f;
  1365. //m_log.DebugFormat("[Collsion]: Depth {0}", Math.Abs(contact.depth - contactGeom.depth));
  1366. // m_log.DebugFormat("[Collision]: <{0},{1},{2}>", Math.Abs(contactGeom.normal.X - contact.normal.X), Math.Abs(contactGeom.normal.Y - contact.normal.Y), Math.Abs(contactGeom.normal.Z - contact.normal.Z));
  1367. result = true;
  1368. break;
  1369. }
  1370. // else
  1371. // {
  1372. // //m_log.DebugFormat("[Collsion]: Depth {0}", Math.Abs(contact.depth - contactGeom.depth));
  1373. // }
  1374. }
  1375. // else
  1376. // {
  1377. // //m_log.DebugFormat("[Collision]: <{0},{1},{2}>", Math.Abs(contactGeom.normal.X - contact.normal.X), Math.Abs(contactGeom.normal.Y - contact.normal.Y), Math.Abs(contactGeom.normal.Z - contact.normal.Z));
  1378. // //int i = 0;
  1379. // }
  1380. }
  1381. else if (at == ActorTypes.Prim)
  1382. {
  1383. //d.AABB aabb1 = new d.AABB();
  1384. //d.AABB aabb2 = new d.AABB();
  1385. //d.GeomGetAABB(contactGeom.g2, out aabb2);
  1386. //d.GeomGetAABB(contactGeom.g1, out aabb1);
  1387. //aabb1.
  1388. if (((Math.Abs(contactGeom.normal.X - contact.normal.X) < 1.026f) && (Math.Abs(contactGeom.normal.Y - contact.normal.Y) < 0.303f) && (Math.Abs(contactGeom.normal.Z - contact.normal.Z) < 0.065f)))
  1389. {
  1390. if (contactGeom.normal.X == contact.normal.X && contactGeom.normal.Y == contact.normal.Y && contactGeom.normal.Z == contact.normal.Z)
  1391. {
  1392. if (Math.Abs(contact.depth - contactGeom.depth) < 0.272f)
  1393. {
  1394. result = true;
  1395. break;
  1396. }
  1397. }
  1398. //m_log.DebugFormat("[Collision]: Depth {0}", Math.Abs(contact.depth - contactGeom.depth));
  1399. //m_log.DebugFormat("[Collision]: <{0},{1},{2}>", Math.Abs(contactGeom.normal.X - contact.normal.X), Math.Abs(contactGeom.normal.Y - contact.normal.Y), Math.Abs(contactGeom.normal.Z - contact.normal.Z));
  1400. }
  1401. }
  1402. }
  1403. return result;
  1404. }
  1405. private void collision_accounting_events(PhysicsActor p1, PhysicsActor p2, ContactPoint contact)
  1406. {
  1407. // obj1LocalID = 0;
  1408. //returncollisions = false;
  1409. obj2LocalID = 0;
  1410. //ctype = 0;
  1411. //cStartStop = 0;
  1412. if (!p2.SubscribedEvents() && !p1.SubscribedEvents())
  1413. return;
  1414. switch ((ActorTypes)p2.PhysicsActorType)
  1415. {
  1416. case ActorTypes.Agent:
  1417. cc2 = (OdeCharacter)p2;
  1418. // obj1LocalID = cc2.m_localID;
  1419. switch ((ActorTypes)p1.PhysicsActorType)
  1420. {
  1421. case ActorTypes.Agent:
  1422. cc1 = (OdeCharacter)p1;
  1423. obj2LocalID = cc1.LocalID;
  1424. cc1.AddCollisionEvent(cc2.LocalID, contact);
  1425. //ctype = (int)CollisionCategories.Character;
  1426. //if (cc1.CollidingObj)
  1427. //cStartStop = (int)StatusIndicators.Generic;
  1428. //else
  1429. //cStartStop = (int)StatusIndicators.Start;
  1430. //returncollisions = true;
  1431. break;
  1432. case ActorTypes.Prim:
  1433. if (p1 is OdePrim)
  1434. {
  1435. cp1 = (OdePrim) p1;
  1436. obj2LocalID = cp1.LocalID;
  1437. cp1.AddCollisionEvent(cc2.LocalID, contact);
  1438. }
  1439. //ctype = (int)CollisionCategories.Geom;
  1440. //if (cp1.CollidingObj)
  1441. //cStartStop = (int)StatusIndicators.Generic;
  1442. //else
  1443. //cStartStop = (int)StatusIndicators.Start;
  1444. //returncollisions = true;
  1445. break;
  1446. case ActorTypes.Ground:
  1447. case ActorTypes.Unknown:
  1448. obj2LocalID = 0;
  1449. //ctype = (int)CollisionCategories.Land;
  1450. //returncollisions = true;
  1451. break;
  1452. }
  1453. cc2.AddCollisionEvent(obj2LocalID, contact);
  1454. break;
  1455. case ActorTypes.Prim:
  1456. if (p2 is OdePrim)
  1457. {
  1458. cp2 = (OdePrim) p2;
  1459. // obj1LocalID = cp2.m_localID;
  1460. switch ((ActorTypes) p1.PhysicsActorType)
  1461. {
  1462. case ActorTypes.Agent:
  1463. if (p1 is OdeCharacter)
  1464. {
  1465. cc1 = (OdeCharacter) p1;
  1466. obj2LocalID = cc1.LocalID;
  1467. cc1.AddCollisionEvent(cp2.LocalID, contact);
  1468. //ctype = (int)CollisionCategories.Character;
  1469. //if (cc1.CollidingObj)
  1470. //cStartStop = (int)StatusIndicators.Generic;
  1471. //else
  1472. //cStartStop = (int)StatusIndicators.Start;
  1473. //returncollisions = true;
  1474. }
  1475. break;
  1476. case ActorTypes.Prim:
  1477. if (p1 is OdePrim)
  1478. {
  1479. cp1 = (OdePrim) p1;
  1480. obj2LocalID = cp1.LocalID;
  1481. cp1.AddCollisionEvent(cp2.LocalID, contact);
  1482. //ctype = (int)CollisionCategories.Geom;
  1483. //if (cp1.CollidingObj)
  1484. //cStartStop = (int)StatusIndicators.Generic;
  1485. //else
  1486. //cStartStop = (int)StatusIndicators.Start;
  1487. //returncollisions = true;
  1488. }
  1489. break;
  1490. case ActorTypes.Ground:
  1491. case ActorTypes.Unknown:
  1492. obj2LocalID = 0;
  1493. //ctype = (int)CollisionCategories.Land;
  1494. //returncollisions = true;
  1495. break;
  1496. }
  1497. cp2.AddCollisionEvent(obj2LocalID, contact);
  1498. }
  1499. break;
  1500. }
  1501. //if (returncollisions)
  1502. //{
  1503. //lock (m_storedCollisions)
  1504. //{
  1505. //cDictKey = obj1LocalID.ToString() + obj2LocalID.ToString() + cStartStop.ToString() + ctype.ToString();
  1506. //if (m_storedCollisions.ContainsKey(cDictKey))
  1507. //{
  1508. //sCollisionData objd = m_storedCollisions[cDictKey];
  1509. //objd.NumberOfCollisions += 1;
  1510. //objd.lastframe = framecount;
  1511. //m_storedCollisions[cDictKey] = objd;
  1512. //}
  1513. //else
  1514. //{
  1515. //sCollisionData objd = new sCollisionData();
  1516. //objd.ColliderLocalId = obj1LocalID;
  1517. //objd.CollidedWithLocalId = obj2LocalID;
  1518. //objd.CollisionType = ctype;
  1519. //objd.NumberOfCollisions = 1;
  1520. //objd.lastframe = framecount;
  1521. //objd.StatusIndicator = cStartStop;
  1522. //m_storedCollisions.Add(cDictKey, objd);
  1523. //}
  1524. //}
  1525. // }
  1526. }
  1527. private int TriArrayCallback(IntPtr trimesh, IntPtr refObject, int[] triangleIndex, int triCount)
  1528. {
  1529. /* String name1 = null;
  1530. String name2 = null;
  1531. if (!geom_name_map.TryGetValue(trimesh, out name1))
  1532. {
  1533. name1 = "null";
  1534. }
  1535. if (!geom_name_map.TryGetValue(refObject, out name2))
  1536. {
  1537. name2 = "null";
  1538. }
  1539. m_log.InfoFormat("TriArrayCallback: A collision was detected between {1} and {2}", 0, name1, name2);
  1540. */
  1541. return 1;
  1542. }
  1543. private int TriCallback(IntPtr trimesh, IntPtr refObject, int triangleIndex)
  1544. {
  1545. // String name1 = null;
  1546. // String name2 = null;
  1547. //
  1548. // if (!geom_name_map.TryGetValue(trimesh, out name1))
  1549. // {
  1550. // name1 = "null";
  1551. // }
  1552. //
  1553. // if (!geom_name_map.TryGetValue(refObject, out name2))
  1554. // {
  1555. // name2 = "null";
  1556. // }
  1557. // m_log.InfoFormat("TriCallback: A collision was detected between {1} and {2}. Index was {3}", 0, name1, name2, triangleIndex);
  1558. d.Vector3 v0 = new d.Vector3();
  1559. d.Vector3 v1 = new d.Vector3();
  1560. d.Vector3 v2 = new d.Vector3();
  1561. d.GeomTriMeshGetTriangle(trimesh, 0, ref v0, ref v1, ref v2);
  1562. // m_log.DebugFormat("Triangle {0} is <{1},{2},{3}>, <{4},{5},{6}>, <{7},{8},{9}>", triangleIndex, v0.X, v0.Y, v0.Z, v1.X, v1.Y, v1.Z, v2.X, v2.Y, v2.Z);
  1563. return 1;
  1564. }
  1565. /// <summary>
  1566. /// This is our collision testing routine in ODE
  1567. /// </summary>
  1568. private void collision_optimized()
  1569. {
  1570. _perloopContact.Clear();
  1571. foreach (OdeCharacter chr in _characters)
  1572. {
  1573. // Reset the collision values to false
  1574. // since we don't know if we're colliding yet
  1575. if (chr.Shell == IntPtr.Zero || chr.Body == IntPtr.Zero)
  1576. continue;
  1577. chr.IsColliding = false;
  1578. chr.CollidingGround = false;
  1579. chr.CollidingObj = false;
  1580. // Test the avatar's geometry for collision with the space
  1581. // This will return near and the space that they are the closest to
  1582. // And we'll run this again against the avatar and the space segment
  1583. // This will return with a bunch of possible objects in the space segment
  1584. // and we'll run it again on all of them.
  1585. try
  1586. {
  1587. CollideSpaces(space, chr.Shell, IntPtr.Zero);
  1588. }
  1589. catch (AccessViolationException)
  1590. {
  1591. m_log.ErrorFormat("[ODE SCENE]: Unable to space collide {0}", PhysicsSceneName);
  1592. }
  1593. //float terrainheight = GetTerrainHeightAtXY(chr.Position.X, chr.Position.Y);
  1594. //if (chr.Position.Z + (chr.Velocity.Z * timeStep) < terrainheight + 10)
  1595. //{
  1596. //chr.Position.Z = terrainheight + 10.0f;
  1597. //forcedZ = true;
  1598. //}
  1599. }
  1600. if (CollectStats)
  1601. {
  1602. m_tempAvatarCollisionsThisFrame = _perloopContact.Count;
  1603. m_stats[ODEAvatarContactsStatsName] += m_tempAvatarCollisionsThisFrame;
  1604. }
  1605. List<OdePrim> removeprims = null;
  1606. foreach (OdePrim chr in _activeprims)
  1607. {
  1608. if (chr.Body != IntPtr.Zero && d.BodyIsEnabled(chr.Body) && (!chr.m_disabled))
  1609. {
  1610. try
  1611. {
  1612. lock (chr)
  1613. {
  1614. if (space != IntPtr.Zero && chr.prim_geom != IntPtr.Zero && chr.m_taintremove == false)
  1615. {
  1616. CollideSpaces(space, chr.prim_geom, IntPtr.Zero);
  1617. }
  1618. else
  1619. {
  1620. if (removeprims == null)
  1621. {
  1622. removeprims = new List<OdePrim>();
  1623. }
  1624. removeprims.Add(chr);
  1625. m_log.Error(
  1626. "[ODE SCENE]: unable to collide test active prim against space. The space was zero, the geom was zero or it was in the process of being removed. Removed it from the active prim list. This needs to be fixed!");
  1627. }
  1628. }
  1629. }
  1630. catch (AccessViolationException)
  1631. {
  1632. m_log.Error("[ODE SCENE]: Unable to space collide");
  1633. }
  1634. }
  1635. }
  1636. if (CollectStats)
  1637. m_stats[ODEPrimContactsStatName] += _perloopContact.Count - m_tempAvatarCollisionsThisFrame;
  1638. if (removeprims != null)
  1639. {
  1640. foreach (OdePrim chr in removeprims)
  1641. {
  1642. _activeprims.Remove(chr);
  1643. }
  1644. }
  1645. }
  1646. #endregion
  1647. public override void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents)
  1648. {
  1649. m_worldOffset = offset;
  1650. WorldExtents = new Vector2(extents.X, extents.Y);
  1651. m_parentScene = pScene;
  1652. }
  1653. // Recovered for use by fly height. Kitto Flora
  1654. internal float GetTerrainHeightAtXY(float x, float y)
  1655. {
  1656. int offsetX = ((int)(x / (int)Constants.RegionSize)) * (int)Constants.RegionSize;
  1657. int offsetY = ((int)(y / (int)Constants.RegionSize)) * (int)Constants.RegionSize;
  1658. IntPtr heightFieldGeom = IntPtr.Zero;
  1659. if (RegionTerrain.TryGetValue(new Vector3(offsetX,offsetY,0), out heightFieldGeom))
  1660. {
  1661. if (heightFieldGeom != IntPtr.Zero)
  1662. {
  1663. if (TerrainHeightFieldHeights.ContainsKey(heightFieldGeom))
  1664. {
  1665. int index;
  1666. if ((int)x > WorldExtents.X || (int)y > WorldExtents.Y ||
  1667. (int)x < 0.001f || (int)y < 0.001f)
  1668. return 0;
  1669. x = x - offsetX;
  1670. y = y - offsetY;
  1671. index = (int)((int)x * ((int)Constants.RegionSize + 2) + (int)y);
  1672. if (index < TerrainHeightFieldHeights[heightFieldGeom].Length)
  1673. {
  1674. //m_log.DebugFormat("x{0} y{1} = {2}", x, y, (float)TerrainHeightFieldHeights[heightFieldGeom][index]);
  1675. return (float)TerrainHeightFieldHeights[heightFieldGeom][index];
  1676. }
  1677. else
  1678. return 0f;
  1679. }
  1680. else
  1681. {
  1682. return 0f;
  1683. }
  1684. }
  1685. else
  1686. {
  1687. return 0f;
  1688. }
  1689. }
  1690. else
  1691. {
  1692. return 0f;
  1693. }
  1694. }
  1695. // End recovered. Kitto Flora
  1696. /// <summary>
  1697. /// Add actor to the list that should receive collision events in the simulate loop.
  1698. /// </summary>
  1699. /// <param name="obj"></param>
  1700. internal void AddCollisionEventReporting(PhysicsActor obj)
  1701. {
  1702. // m_log.DebugFormat("[PHYSICS]: Adding {0} {1} to collision event reporting", obj.SOPName, obj.LocalID);
  1703. lock (m_collisionEventActorsChanges)
  1704. m_collisionEventActorsChanges[obj.LocalID] = obj;
  1705. }
  1706. /// <summary>
  1707. /// Remove actor from the list that should receive collision events in the simulate loop.
  1708. /// </summary>
  1709. /// <param name="obj"></param>
  1710. internal void RemoveCollisionEventReporting(PhysicsActor obj)
  1711. {
  1712. // m_log.DebugFormat("[PHYSICS]: Removing {0} {1} from collision event reporting", obj.SOPName, obj.LocalID);
  1713. lock (m_collisionEventActorsChanges)
  1714. m_collisionEventActorsChanges[obj.LocalID] = null;
  1715. }
  1716. #region Add/Remove Entities
  1717. public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 velocity, Vector3 size, bool isFlying)
  1718. {
  1719. OdeCharacter newAv
  1720. = new OdeCharacter(
  1721. avName, this, position, velocity, size, avPIDD, avPIDP,
  1722. avCapRadius, avStandupTensor, avDensity,
  1723. avMovementDivisorWalk, avMovementDivisorRun);
  1724. newAv.Flying = isFlying;
  1725. newAv.MinimumGroundFlightOffset = minimumGroundFlightOffset;
  1726. newAv.m_avatarplanted = avplanted;
  1727. return newAv;
  1728. }
  1729. public override void RemoveAvatar(PhysicsActor actor)
  1730. {
  1731. // m_log.DebugFormat(
  1732. // "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2}",
  1733. // actor.Name, actor.LocalID, Name);
  1734. ((OdeCharacter) actor).Destroy();
  1735. }
  1736. internal void AddCharacter(OdeCharacter chr)
  1737. {
  1738. chr.m_avatarplanted = avplanted;
  1739. if (!_characters.Contains(chr))
  1740. {
  1741. _characters.Add(chr);
  1742. // m_log.DebugFormat(
  1743. // "[ODE SCENE]: Adding physics character {0} {1} to physics scene {2}. Count now {3}",
  1744. // chr.Name, chr.LocalID, Name, _characters.Count);
  1745. if (chr.bad)
  1746. m_log.ErrorFormat("[ODE SCENE]: Added BAD actor {0} to characters list", chr.m_uuid);
  1747. }
  1748. else
  1749. {
  1750. m_log.ErrorFormat(
  1751. "[ODE SCENE]: Tried to add character {0} {1} but they are already in the set!",
  1752. chr.Name, chr.LocalID);
  1753. }
  1754. }
  1755. internal void RemoveCharacter(OdeCharacter chr)
  1756. {
  1757. if (_characters.Contains(chr))
  1758. {
  1759. _characters.Remove(chr);
  1760. // m_log.DebugFormat(
  1761. // "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2}. Count now {3}",
  1762. // chr.Name, chr.LocalID, Name, _characters.Count);
  1763. }
  1764. else
  1765. {
  1766. m_log.ErrorFormat(
  1767. "[ODE SCENE]: Tried to remove character {0} {1} but they are not in the list!",
  1768. chr.Name, chr.LocalID);
  1769. }
  1770. }
  1771. private PhysicsActor AddPrim(String name, Vector3 position, Vector3 size, Quaternion rotation,
  1772. PrimitiveBaseShape pbs, bool isphysical, uint localID)
  1773. {
  1774. Vector3 pos = position;
  1775. Vector3 siz = size;
  1776. Quaternion rot = rotation;
  1777. OdePrim newPrim;
  1778. lock (OdeLock)
  1779. {
  1780. newPrim = new OdePrim(name, this, pos, siz, rot, pbs, isphysical);
  1781. lock (_prims)
  1782. _prims.Add(newPrim);
  1783. }
  1784. newPrim.LocalID = localID;
  1785. return newPrim;
  1786. }
  1787. /// <summary>
  1788. /// Make this prim subject to physics.
  1789. /// </summary>
  1790. /// <param name="prim"></param>
  1791. internal void ActivatePrim(OdePrim prim)
  1792. {
  1793. // adds active prim.. (ones that should be iterated over in collisions_optimized
  1794. if (!_activeprims.Contains(prim))
  1795. _activeprims.Add(prim);
  1796. //else
  1797. // m_log.Warn("[PHYSICS]: Double Entry in _activeprims detected, potential crash immenent");
  1798. }
  1799. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  1800. Vector3 size, Quaternion rotation, bool isPhysical, uint localid)
  1801. {
  1802. // m_log.DebugFormat("[ODE SCENE]: Adding physics prim {0} {1} to physics scene {2}", primName, localid, Name);
  1803. return AddPrim(primName, position, size, rotation, pbs, isPhysical, localid);
  1804. }
  1805. public override float TimeDilation
  1806. {
  1807. get { return m_timeDilation; }
  1808. }
  1809. public override bool SupportsNINJAJoints
  1810. {
  1811. get { return m_NINJA_physics_joints_enabled; }
  1812. }
  1813. // internal utility function: must be called within a lock (OdeLock)
  1814. private void InternalAddActiveJoint(PhysicsJoint joint)
  1815. {
  1816. activeJoints.Add(joint);
  1817. SOPName_to_activeJoint.Add(joint.ObjectNameInScene, joint);
  1818. }
  1819. // internal utility function: must be called within a lock (OdeLock)
  1820. private void InternalAddPendingJoint(OdePhysicsJoint joint)
  1821. {
  1822. pendingJoints.Add(joint);
  1823. SOPName_to_pendingJoint.Add(joint.ObjectNameInScene, joint);
  1824. }
  1825. // internal utility function: must be called within a lock (OdeLock)
  1826. private void InternalRemovePendingJoint(PhysicsJoint joint)
  1827. {
  1828. pendingJoints.Remove(joint);
  1829. SOPName_to_pendingJoint.Remove(joint.ObjectNameInScene);
  1830. }
  1831. // internal utility function: must be called within a lock (OdeLock)
  1832. private void InternalRemoveActiveJoint(PhysicsJoint joint)
  1833. {
  1834. activeJoints.Remove(joint);
  1835. SOPName_to_activeJoint.Remove(joint.ObjectNameInScene);
  1836. }
  1837. public override void DumpJointInfo()
  1838. {
  1839. string hdr = "[NINJA] JOINTINFO: ";
  1840. foreach (PhysicsJoint j in pendingJoints)
  1841. {
  1842. m_log.Debug(hdr + " pending joint, Name: " + j.ObjectNameInScene + " raw parms:" + j.RawParams);
  1843. }
  1844. m_log.Debug(hdr + pendingJoints.Count + " total pending joints");
  1845. foreach (string jointName in SOPName_to_pendingJoint.Keys)
  1846. {
  1847. m_log.Debug(hdr + " pending joints dict contains Name: " + jointName);
  1848. }
  1849. m_log.Debug(hdr + SOPName_to_pendingJoint.Keys.Count + " total pending joints dict entries");
  1850. foreach (PhysicsJoint j in activeJoints)
  1851. {
  1852. m_log.Debug(hdr + " active joint, Name: " + j.ObjectNameInScene + " raw parms:" + j.RawParams);
  1853. }
  1854. m_log.Debug(hdr + activeJoints.Count + " total active joints");
  1855. foreach (string jointName in SOPName_to_activeJoint.Keys)
  1856. {
  1857. m_log.Debug(hdr + " active joints dict contains Name: " + jointName);
  1858. }
  1859. m_log.Debug(hdr + SOPName_to_activeJoint.Keys.Count + " total active joints dict entries");
  1860. m_log.Debug(hdr + " Per-body joint connectivity information follows.");
  1861. m_log.Debug(hdr + joints_connecting_actor.Keys.Count + " bodies are connected by joints.");
  1862. foreach (string actorName in joints_connecting_actor.Keys)
  1863. {
  1864. m_log.Debug(hdr + " Actor " + actorName + " has the following joints connecting it");
  1865. foreach (PhysicsJoint j in joints_connecting_actor[actorName])
  1866. {
  1867. m_log.Debug(hdr + " * joint Name: " + j.ObjectNameInScene + " raw parms:" + j.RawParams);
  1868. }
  1869. m_log.Debug(hdr + joints_connecting_actor[actorName].Count + " connecting joints total for this actor");
  1870. }
  1871. }
  1872. public override void RequestJointDeletion(string ObjectNameInScene)
  1873. {
  1874. lock (externalJointRequestsLock)
  1875. {
  1876. if (!requestedJointsToBeDeleted.Contains(ObjectNameInScene)) // forbid same deletion request from entering twice to prevent spurious deletions processed asynchronously
  1877. {
  1878. requestedJointsToBeDeleted.Add(ObjectNameInScene);
  1879. }
  1880. }
  1881. }
  1882. private void DeleteRequestedJoints()
  1883. {
  1884. List<string> myRequestedJointsToBeDeleted;
  1885. lock (externalJointRequestsLock)
  1886. {
  1887. // make a local copy of the shared list for processing (threading issues)
  1888. myRequestedJointsToBeDeleted = new List<string>(requestedJointsToBeDeleted);
  1889. }
  1890. foreach (string jointName in myRequestedJointsToBeDeleted)
  1891. {
  1892. lock (OdeLock)
  1893. {
  1894. //m_log.Debug("[NINJA] trying to deleting requested joint " + jointName);
  1895. if (SOPName_to_activeJoint.ContainsKey(jointName) || SOPName_to_pendingJoint.ContainsKey(jointName))
  1896. {
  1897. OdePhysicsJoint joint = null;
  1898. if (SOPName_to_activeJoint.ContainsKey(jointName))
  1899. {
  1900. joint = SOPName_to_activeJoint[jointName] as OdePhysicsJoint;
  1901. InternalRemoveActiveJoint(joint);
  1902. }
  1903. else if (SOPName_to_pendingJoint.ContainsKey(jointName))
  1904. {
  1905. joint = SOPName_to_pendingJoint[jointName] as OdePhysicsJoint;
  1906. InternalRemovePendingJoint(joint);
  1907. }
  1908. if (joint != null)
  1909. {
  1910. //m_log.Debug("joint.BodyNames.Count is " + joint.BodyNames.Count + " and contents " + joint.BodyNames);
  1911. for (int iBodyName = 0; iBodyName < 2; iBodyName++)
  1912. {
  1913. string bodyName = joint.BodyNames[iBodyName];
  1914. if (bodyName != "NULL")
  1915. {
  1916. joints_connecting_actor[bodyName].Remove(joint);
  1917. if (joints_connecting_actor[bodyName].Count == 0)
  1918. {
  1919. joints_connecting_actor.Remove(bodyName);
  1920. }
  1921. }
  1922. }
  1923. DoJointDeactivated(joint);
  1924. if (joint.jointID != IntPtr.Zero)
  1925. {
  1926. d.JointDestroy(joint.jointID);
  1927. joint.jointID = IntPtr.Zero;
  1928. //DoJointErrorMessage(joint, "successfully destroyed joint " + jointName);
  1929. }
  1930. else
  1931. {
  1932. //m_log.Warn("[NINJA] Ignoring re-request to destroy joint " + jointName);
  1933. }
  1934. }
  1935. else
  1936. {
  1937. // DoJointErrorMessage(joint, "coult not find joint to destroy based on name " + jointName);
  1938. }
  1939. }
  1940. else
  1941. {
  1942. // DoJointErrorMessage(joint, "WARNING - joint removal failed, joint " + jointName);
  1943. }
  1944. }
  1945. }
  1946. // remove processed joints from the shared list
  1947. lock (externalJointRequestsLock)
  1948. {
  1949. foreach (string jointName in myRequestedJointsToBeDeleted)
  1950. {
  1951. requestedJointsToBeDeleted.Remove(jointName);
  1952. }
  1953. }
  1954. }
  1955. // for pending joints we don't know if their associated bodies exist yet or not.
  1956. // the joint is actually created during processing of the taints
  1957. private void CreateRequestedJoints()
  1958. {
  1959. List<PhysicsJoint> myRequestedJointsToBeCreated;
  1960. lock (externalJointRequestsLock)
  1961. {
  1962. // make a local copy of the shared list for processing (threading issues)
  1963. myRequestedJointsToBeCreated = new List<PhysicsJoint>(requestedJointsToBeCreated);
  1964. }
  1965. foreach (PhysicsJoint joint in myRequestedJointsToBeCreated)
  1966. {
  1967. lock (OdeLock)
  1968. {
  1969. if (SOPName_to_pendingJoint.ContainsKey(joint.ObjectNameInScene) && SOPName_to_pendingJoint[joint.ObjectNameInScene] != null)
  1970. {
  1971. DoJointErrorMessage(joint, "WARNING: ignoring request to re-add already pending joint Name:" + joint.ObjectNameInScene + " type:" + joint.Type + " parms: " + joint.RawParams + " pos: " + joint.Position + " rot:" + joint.Rotation);
  1972. continue;
  1973. }
  1974. if (SOPName_to_activeJoint.ContainsKey(joint.ObjectNameInScene) && SOPName_to_activeJoint[joint.ObjectNameInScene] != null)
  1975. {
  1976. DoJointErrorMessage(joint, "WARNING: ignoring request to re-add already active joint Name:" + joint.ObjectNameInScene + " type:" + joint.Type + " parms: " + joint.RawParams + " pos: " + joint.Position + " rot:" + joint.Rotation);
  1977. continue;
  1978. }
  1979. InternalAddPendingJoint(joint as OdePhysicsJoint);
  1980. if (joint.BodyNames.Count >= 2)
  1981. {
  1982. for (int iBodyName = 0; iBodyName < 2; iBodyName++)
  1983. {
  1984. string bodyName = joint.BodyNames[iBodyName];
  1985. if (bodyName != "NULL")
  1986. {
  1987. if (!joints_connecting_actor.ContainsKey(bodyName))
  1988. {
  1989. joints_connecting_actor.Add(bodyName, new List<PhysicsJoint>());
  1990. }
  1991. joints_connecting_actor[bodyName].Add(joint);
  1992. }
  1993. }
  1994. }
  1995. }
  1996. }
  1997. // remove processed joints from shared list
  1998. lock (externalJointRequestsLock)
  1999. {
  2000. foreach (PhysicsJoint joint in myRequestedJointsToBeCreated)
  2001. {
  2002. requestedJointsToBeCreated.Remove(joint);
  2003. }
  2004. }
  2005. }
  2006. /// <summary>
  2007. /// Add a request for joint creation.
  2008. /// </summary>
  2009. /// <remarks>
  2010. /// this joint will just be added to a waiting list that is NOT processed during the main
  2011. /// Simulate() loop (to avoid deadlocks). After Simulate() is finished, we handle unprocessed joint requests.
  2012. /// </remarks>
  2013. /// <param name="objectNameInScene"></param>
  2014. /// <param name="jointType"></param>
  2015. /// <param name="position"></param>
  2016. /// <param name="rotation"></param>
  2017. /// <param name="parms"></param>
  2018. /// <param name="bodyNames"></param>
  2019. /// <param name="trackedBodyName"></param>
  2020. /// <param name="localRotation"></param>
  2021. /// <returns></returns>
  2022. public override PhysicsJoint RequestJointCreation(
  2023. string objectNameInScene, PhysicsJointType jointType, Vector3 position,
  2024. Quaternion rotation, string parms, List<string> bodyNames, string trackedBodyName, Quaternion localRotation)
  2025. {
  2026. OdePhysicsJoint joint = new OdePhysicsJoint();
  2027. joint.ObjectNameInScene = objectNameInScene;
  2028. joint.Type = jointType;
  2029. joint.Position = position;
  2030. joint.Rotation = rotation;
  2031. joint.RawParams = parms;
  2032. joint.BodyNames = new List<string>(bodyNames);
  2033. joint.TrackedBodyName = trackedBodyName;
  2034. joint.LocalRotation = localRotation;
  2035. joint.jointID = IntPtr.Zero;
  2036. joint.ErrorMessageCount = 0;
  2037. lock (externalJointRequestsLock)
  2038. {
  2039. if (!requestedJointsToBeCreated.Contains(joint)) // forbid same creation request from entering twice
  2040. {
  2041. requestedJointsToBeCreated.Add(joint);
  2042. }
  2043. }
  2044. return joint;
  2045. }
  2046. private void RemoveAllJointsConnectedToActor(PhysicsActor actor)
  2047. {
  2048. //m_log.Debug("RemoveAllJointsConnectedToActor: start");
  2049. if (actor.SOPName != null && joints_connecting_actor.ContainsKey(actor.SOPName) && joints_connecting_actor[actor.SOPName] != null)
  2050. {
  2051. List<PhysicsJoint> jointsToRemove = new List<PhysicsJoint>();
  2052. //TODO: merge these 2 loops (originally it was needed to avoid altering a list being iterated over, but it is no longer needed due to the joint request queue mechanism)
  2053. foreach (PhysicsJoint j in joints_connecting_actor[actor.SOPName])
  2054. {
  2055. jointsToRemove.Add(j);
  2056. }
  2057. foreach (PhysicsJoint j in jointsToRemove)
  2058. {
  2059. //m_log.Debug("RemoveAllJointsConnectedToActor: about to request deletion of " + j.ObjectNameInScene);
  2060. RequestJointDeletion(j.ObjectNameInScene);
  2061. //m_log.Debug("RemoveAllJointsConnectedToActor: done request deletion of " + j.ObjectNameInScene);
  2062. j.TrackedBodyName = null; // *IMMEDIATELY* prevent any further movement of this joint (else a deleted actor might cause spurious tracking motion of the joint for a few frames, leading to the joint proxy object disappearing)
  2063. }
  2064. }
  2065. }
  2066. public override void RemoveAllJointsConnectedToActorThreadLocked(PhysicsActor actor)
  2067. {
  2068. //m_log.Debug("RemoveAllJointsConnectedToActorThreadLocked: start");
  2069. lock (OdeLock)
  2070. {
  2071. //m_log.Debug("RemoveAllJointsConnectedToActorThreadLocked: got lock");
  2072. RemoveAllJointsConnectedToActor(actor);
  2073. }
  2074. }
  2075. // normally called from within OnJointMoved, which is called from within a lock (OdeLock)
  2076. public override Vector3 GetJointAnchor(PhysicsJoint joint)
  2077. {
  2078. Debug.Assert(joint.IsInPhysicsEngine);
  2079. d.Vector3 pos = new d.Vector3();
  2080. if (!(joint is OdePhysicsJoint))
  2081. {
  2082. DoJointErrorMessage(joint, "warning: non-ODE joint requesting anchor: " + joint.ObjectNameInScene);
  2083. }
  2084. else
  2085. {
  2086. OdePhysicsJoint odeJoint = (OdePhysicsJoint)joint;
  2087. switch (odeJoint.Type)
  2088. {
  2089. case PhysicsJointType.Ball:
  2090. d.JointGetBallAnchor(odeJoint.jointID, out pos);
  2091. break;
  2092. case PhysicsJointType.Hinge:
  2093. d.JointGetHingeAnchor(odeJoint.jointID, out pos);
  2094. break;
  2095. }
  2096. }
  2097. return new Vector3(pos.X, pos.Y, pos.Z);
  2098. }
  2099. /// <summary>
  2100. /// Get joint axis.
  2101. /// </summary>
  2102. /// <remarks>
  2103. /// normally called from within OnJointMoved, which is called from within a lock (OdeLock)
  2104. /// WARNING: ODE sometimes returns <0,0,0> as the joint axis! Therefore this function
  2105. /// appears to be unreliable. Fortunately we can compute the joint axis ourselves by
  2106. /// keeping track of the joint's original orientation relative to one of the involved bodies.
  2107. /// </remarks>
  2108. /// <param name="joint"></param>
  2109. /// <returns></returns>
  2110. public override Vector3 GetJointAxis(PhysicsJoint joint)
  2111. {
  2112. Debug.Assert(joint.IsInPhysicsEngine);
  2113. d.Vector3 axis = new d.Vector3();
  2114. if (!(joint is OdePhysicsJoint))
  2115. {
  2116. DoJointErrorMessage(joint, "warning: non-ODE joint requesting anchor: " + joint.ObjectNameInScene);
  2117. }
  2118. else
  2119. {
  2120. OdePhysicsJoint odeJoint = (OdePhysicsJoint)joint;
  2121. switch (odeJoint.Type)
  2122. {
  2123. case PhysicsJointType.Ball:
  2124. DoJointErrorMessage(joint, "warning - axis requested for ball joint: " + joint.ObjectNameInScene);
  2125. break;
  2126. case PhysicsJointType.Hinge:
  2127. d.JointGetHingeAxis(odeJoint.jointID, out axis);
  2128. break;
  2129. }
  2130. }
  2131. return new Vector3(axis.X, axis.Y, axis.Z);
  2132. }
  2133. /// <summary>
  2134. /// Stop this prim being subject to physics
  2135. /// </summary>
  2136. /// <param name="prim"></param>
  2137. internal void DeactivatePrim(OdePrim prim)
  2138. {
  2139. _activeprims.Remove(prim);
  2140. }
  2141. public override void RemovePrim(PhysicsActor prim)
  2142. {
  2143. // As with all ODE physics operations, we don't remove the prim immediately but signal that it should be
  2144. // removed in the next physics simulate pass.
  2145. if (prim is OdePrim)
  2146. {
  2147. lock (OdeLock)
  2148. {
  2149. OdePrim p = (OdePrim) prim;
  2150. p.setPrimForRemoval();
  2151. AddPhysicsActorTaint(prim);
  2152. }
  2153. }
  2154. }
  2155. /// <summary>
  2156. /// This is called from within simulate but outside the locked portion
  2157. /// We need to do our own locking here
  2158. /// (Note: As of 20110801 this no longer appears to be true - this is being called within lock (odeLock) in
  2159. /// Simulate() -- justincc).
  2160. ///
  2161. /// Essentially, we need to remove the prim from our space segment, whatever segment it's in.
  2162. ///
  2163. /// If there are no more prim in the segment, we need to empty (spacedestroy)the segment and reclaim memory
  2164. /// that the space was using.
  2165. /// </summary>
  2166. /// <param name="prim"></param>
  2167. internal void RemovePrimThreadLocked(OdePrim prim)
  2168. {
  2169. // m_log.DebugFormat("[ODE SCENE]: Removing physical prim {0} {1}", prim.Name, prim.LocalID);
  2170. lock (prim)
  2171. {
  2172. RemoveCollisionEventReporting(prim);
  2173. if (prim.prim_geom != IntPtr.Zero)
  2174. {
  2175. prim.ResetTaints();
  2176. if (prim.IsPhysical)
  2177. {
  2178. prim.disableBody();
  2179. if (prim.childPrim)
  2180. {
  2181. prim.childPrim = false;
  2182. prim.Body = IntPtr.Zero;
  2183. prim.m_disabled = true;
  2184. prim.IsPhysical = false;
  2185. }
  2186. }
  2187. // we don't want to remove the main space
  2188. // If the geometry is in the targetspace, remove it from the target space
  2189. //m_log.Warn(prim.m_targetSpace);
  2190. //if (prim.m_targetSpace != IntPtr.Zero)
  2191. //{
  2192. //if (d.SpaceQuery(prim.m_targetSpace, prim.prim_geom))
  2193. //{
  2194. //if (d.GeomIsSpace(prim.m_targetSpace))
  2195. //{
  2196. //waitForSpaceUnlock(prim.m_targetSpace);
  2197. //d.SpaceRemove(prim.m_targetSpace, prim.prim_geom);
  2198. prim.m_targetSpace = IntPtr.Zero;
  2199. //}
  2200. //else
  2201. //{
  2202. // m_log.Info("[Physics]: Invalid Scene passed to 'removeprim from scene':" +
  2203. //((OdePrim)prim).m_targetSpace.ToString());
  2204. //}
  2205. //}
  2206. //}
  2207. //m_log.Warn(prim.prim_geom);
  2208. if (!prim.RemoveGeom())
  2209. m_log.Warn("[ODE SCENE]: Unable to remove prim from physics scene");
  2210. lock (_prims)
  2211. _prims.Remove(prim);
  2212. //If there are no more geometries in the sub-space, we don't need it in the main space anymore
  2213. //if (d.SpaceGetNumGeoms(prim.m_targetSpace) == 0)
  2214. //{
  2215. //if (prim.m_targetSpace != null)
  2216. //{
  2217. //if (d.GeomIsSpace(prim.m_targetSpace))
  2218. //{
  2219. //waitForSpaceUnlock(prim.m_targetSpace);
  2220. //d.SpaceRemove(space, prim.m_targetSpace);
  2221. // free up memory used by the space.
  2222. //d.SpaceDestroy(prim.m_targetSpace);
  2223. //int[] xyspace = calculateSpaceArrayItemFromPos(prim.Position);
  2224. //resetSpaceArrayItemToZero(xyspace[0], xyspace[1]);
  2225. //}
  2226. //else
  2227. //{
  2228. //m_log.Info("[Physics]: Invalid Scene passed to 'removeprim from scene':" +
  2229. //((OdePrim) prim).m_targetSpace.ToString());
  2230. //}
  2231. //}
  2232. //}
  2233. if (SupportsNINJAJoints)
  2234. RemoveAllJointsConnectedToActorThreadLocked(prim);
  2235. }
  2236. }
  2237. }
  2238. #endregion
  2239. #region Space Separation Calculation
  2240. /// <summary>
  2241. /// Takes a space pointer and zeros out the array we're using to hold the spaces
  2242. /// </summary>
  2243. /// <param name="pSpace"></param>
  2244. private void resetSpaceArrayItemToZero(IntPtr pSpace)
  2245. {
  2246. for (int x = 0; x < staticPrimspace.GetLength(0); x++)
  2247. {
  2248. for (int y = 0; y < staticPrimspace.GetLength(1); y++)
  2249. {
  2250. if (staticPrimspace[x, y] == pSpace)
  2251. staticPrimspace[x, y] = IntPtr.Zero;
  2252. }
  2253. }
  2254. }
  2255. // private void resetSpaceArrayItemToZero(int arrayitemX, int arrayitemY)
  2256. // {
  2257. // staticPrimspace[arrayitemX, arrayitemY] = IntPtr.Zero;
  2258. // }
  2259. /// <summary>
  2260. /// Called when a static prim moves. Allocates a space for the prim based on its position
  2261. /// </summary>
  2262. /// <param name="geom">the pointer to the geom that moved</param>
  2263. /// <param name="pos">the position that the geom moved to</param>
  2264. /// <param name="currentspace">a pointer to the space it was in before it was moved.</param>
  2265. /// <returns>a pointer to the new space it's in</returns>
  2266. internal IntPtr recalculateSpaceForGeom(IntPtr geom, Vector3 pos, IntPtr currentspace)
  2267. {
  2268. // Called from setting the Position and Size of an ODEPrim so
  2269. // it's already in locked space.
  2270. // we don't want to remove the main space
  2271. // we don't need to test physical here because this function should
  2272. // never be called if the prim is physical(active)
  2273. // All physical prim end up in the root space
  2274. //Thread.Sleep(20);
  2275. if (currentspace != space)
  2276. {
  2277. //m_log.Info("[SPACE]: C:" + currentspace.ToString() + " g:" + geom.ToString());
  2278. //if (currentspace == IntPtr.Zero)
  2279. //{
  2280. //int adfadf = 0;
  2281. //}
  2282. if (d.SpaceQuery(currentspace, geom) && currentspace != IntPtr.Zero)
  2283. {
  2284. if (d.GeomIsSpace(currentspace))
  2285. {
  2286. // waitForSpaceUnlock(currentspace);
  2287. d.SpaceRemove(currentspace, geom);
  2288. }
  2289. else
  2290. {
  2291. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" + currentspace +
  2292. " Geom:" + geom);
  2293. }
  2294. }
  2295. else
  2296. {
  2297. IntPtr sGeomIsIn = d.GeomGetSpace(geom);
  2298. if (sGeomIsIn != IntPtr.Zero)
  2299. {
  2300. if (d.GeomIsSpace(currentspace))
  2301. {
  2302. // waitForSpaceUnlock(sGeomIsIn);
  2303. d.SpaceRemove(sGeomIsIn, geom);
  2304. }
  2305. else
  2306. {
  2307. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  2308. sGeomIsIn + " Geom:" + geom);
  2309. }
  2310. }
  2311. }
  2312. //If there are no more geometries in the sub-space, we don't need it in the main space anymore
  2313. if (d.SpaceGetNumGeoms(currentspace) == 0)
  2314. {
  2315. if (currentspace != IntPtr.Zero)
  2316. {
  2317. if (d.GeomIsSpace(currentspace))
  2318. {
  2319. // waitForSpaceUnlock(currentspace);
  2320. // waitForSpaceUnlock(space);
  2321. d.SpaceRemove(space, currentspace);
  2322. // free up memory used by the space.
  2323. //d.SpaceDestroy(currentspace);
  2324. resetSpaceArrayItemToZero(currentspace);
  2325. }
  2326. else
  2327. {
  2328. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  2329. currentspace + " Geom:" + geom);
  2330. }
  2331. }
  2332. }
  2333. }
  2334. else
  2335. {
  2336. // this is a physical object that got disabled. ;.;
  2337. if (currentspace != IntPtr.Zero && geom != IntPtr.Zero)
  2338. {
  2339. if (d.SpaceQuery(currentspace, geom))
  2340. {
  2341. if (d.GeomIsSpace(currentspace))
  2342. {
  2343. // waitForSpaceUnlock(currentspace);
  2344. d.SpaceRemove(currentspace, geom);
  2345. }
  2346. else
  2347. {
  2348. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  2349. currentspace + " Geom:" + geom);
  2350. }
  2351. }
  2352. else
  2353. {
  2354. IntPtr sGeomIsIn = d.GeomGetSpace(geom);
  2355. if (sGeomIsIn != IntPtr.Zero)
  2356. {
  2357. if (d.GeomIsSpace(sGeomIsIn))
  2358. {
  2359. // waitForSpaceUnlock(sGeomIsIn);
  2360. d.SpaceRemove(sGeomIsIn, geom);
  2361. }
  2362. else
  2363. {
  2364. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  2365. sGeomIsIn + " Geom:" + geom);
  2366. }
  2367. }
  2368. }
  2369. }
  2370. }
  2371. // The routines in the Position and Size sections do the 'inserting' into the space,
  2372. // so all we have to do is make sure that the space that we're putting the prim into
  2373. // is in the 'main' space.
  2374. int[] iprimspaceArrItem = calculateSpaceArrayItemFromPos(pos);
  2375. IntPtr newspace = calculateSpaceForGeom(pos);
  2376. if (newspace == IntPtr.Zero)
  2377. {
  2378. newspace = createprimspace(iprimspaceArrItem[0], iprimspaceArrItem[1]);
  2379. d.HashSpaceSetLevels(newspace, smallHashspaceLow, smallHashspaceHigh);
  2380. }
  2381. return newspace;
  2382. }
  2383. /// <summary>
  2384. /// Creates a new space at X Y
  2385. /// </summary>
  2386. /// <param name="iprimspaceArrItemX"></param>
  2387. /// <param name="iprimspaceArrItemY"></param>
  2388. /// <returns>A pointer to the created space</returns>
  2389. internal IntPtr createprimspace(int iprimspaceArrItemX, int iprimspaceArrItemY)
  2390. {
  2391. // creating a new space for prim and inserting it into main space.
  2392. staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY] = d.HashSpaceCreate(IntPtr.Zero);
  2393. d.GeomSetCategoryBits(staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY], (int)CollisionCategories.Space);
  2394. // waitForSpaceUnlock(space);
  2395. d.SpaceSetSublevel(space, 1);
  2396. d.SpaceAdd(space, staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY]);
  2397. return staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY];
  2398. }
  2399. /// <summary>
  2400. /// Calculates the space the prim should be in by its position
  2401. /// </summary>
  2402. /// <param name="pos"></param>
  2403. /// <returns>a pointer to the space. This could be a new space or reused space.</returns>
  2404. internal IntPtr calculateSpaceForGeom(Vector3 pos)
  2405. {
  2406. int[] xyspace = calculateSpaceArrayItemFromPos(pos);
  2407. //m_log.Info("[Physics]: Attempting to use arrayItem: " + xyspace[0].ToString() + "," + xyspace[1].ToString());
  2408. return staticPrimspace[xyspace[0], xyspace[1]];
  2409. }
  2410. /// <summary>
  2411. /// Holds the space allocation logic
  2412. /// </summary>
  2413. /// <param name="pos"></param>
  2414. /// <returns>an array item based on the position</returns>
  2415. internal int[] calculateSpaceArrayItemFromPos(Vector3 pos)
  2416. {
  2417. int[] returnint = new int[2];
  2418. returnint[0] = (int) (pos.X/metersInSpace);
  2419. if (returnint[0] > ((int) (259f/metersInSpace)))
  2420. returnint[0] = ((int) (259f/metersInSpace));
  2421. if (returnint[0] < 0)
  2422. returnint[0] = 0;
  2423. returnint[1] = (int) (pos.Y/metersInSpace);
  2424. if (returnint[1] > ((int) (259f/metersInSpace)))
  2425. returnint[1] = ((int) (259f/metersInSpace));
  2426. if (returnint[1] < 0)
  2427. returnint[1] = 0;
  2428. return returnint;
  2429. }
  2430. #endregion
  2431. /// <summary>
  2432. /// Routine to figure out if we need to mesh this prim with our mesher
  2433. /// </summary>
  2434. /// <param name="pbs"></param>
  2435. /// <returns></returns>
  2436. internal bool needsMeshing(PrimitiveBaseShape pbs)
  2437. {
  2438. // most of this is redundant now as the mesher will return null if it cant mesh a prim
  2439. // but we still need to check for sculptie meshing being enabled so this is the most
  2440. // convenient place to do it for now...
  2441. // //if (pbs.PathCurve == (byte)Primitive.PathCurve.Circle && pbs.ProfileCurve == (byte)Primitive.ProfileCurve.Circle && pbs.PathScaleY <= 0.75f)
  2442. // //m_log.Debug("needsMeshing: " + " pathCurve: " + pbs.PathCurve.ToString() + " profileCurve: " + pbs.ProfileCurve.ToString() + " pathScaleY: " + Primitive.UnpackPathScale(pbs.PathScaleY).ToString());
  2443. int iPropertiesNotSupportedDefault = 0;
  2444. if (pbs.SculptEntry && !meshSculptedPrim)
  2445. {
  2446. #if SPAM
  2447. m_log.Warn("NonMesh");
  2448. #endif
  2449. return false;
  2450. }
  2451. // if it's a standard box or sphere with no cuts, hollows, twist or top shear, return false since ODE can use an internal representation for the prim
  2452. if (!forceSimplePrimMeshing && !pbs.SculptEntry)
  2453. {
  2454. if ((pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight)
  2455. || (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1
  2456. && pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z))
  2457. {
  2458. if (pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0
  2459. && pbs.ProfileHollow == 0
  2460. && pbs.PathTwist == 0 && pbs.PathTwistBegin == 0
  2461. && pbs.PathBegin == 0 && pbs.PathEnd == 0
  2462. && pbs.PathTaperX == 0 && pbs.PathTaperY == 0
  2463. && pbs.PathScaleX == 100 && pbs.PathScaleY == 100
  2464. && pbs.PathShearX == 0 && pbs.PathShearY == 0)
  2465. {
  2466. #if SPAM
  2467. m_log.Warn("NonMesh");
  2468. #endif
  2469. return false;
  2470. }
  2471. }
  2472. }
  2473. if (pbs.ProfileHollow != 0)
  2474. iPropertiesNotSupportedDefault++;
  2475. if ((pbs.PathBegin != 0) || pbs.PathEnd != 0)
  2476. iPropertiesNotSupportedDefault++;
  2477. if ((pbs.PathTwistBegin != 0) || (pbs.PathTwist != 0))
  2478. iPropertiesNotSupportedDefault++;
  2479. if ((pbs.ProfileBegin != 0) || pbs.ProfileEnd != 0)
  2480. iPropertiesNotSupportedDefault++;
  2481. if ((pbs.PathScaleX != 100) || (pbs.PathScaleY != 100))
  2482. iPropertiesNotSupportedDefault++;
  2483. if ((pbs.PathShearX != 0) || (pbs.PathShearY != 0))
  2484. iPropertiesNotSupportedDefault++;
  2485. if (pbs.ProfileShape == ProfileShape.Circle && pbs.PathCurve == (byte)Extrusion.Straight)
  2486. iPropertiesNotSupportedDefault++;
  2487. if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1 && (pbs.Scale.X != pbs.Scale.Y || pbs.Scale.Y != pbs.Scale.Z || pbs.Scale.Z != pbs.Scale.X))
  2488. iPropertiesNotSupportedDefault++;
  2489. if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte) Extrusion.Curve1)
  2490. iPropertiesNotSupportedDefault++;
  2491. // test for torus
  2492. if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Square)
  2493. {
  2494. if (pbs.PathCurve == (byte)Extrusion.Curve1)
  2495. {
  2496. iPropertiesNotSupportedDefault++;
  2497. }
  2498. }
  2499. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
  2500. {
  2501. if (pbs.PathCurve == (byte)Extrusion.Straight)
  2502. {
  2503. iPropertiesNotSupportedDefault++;
  2504. }
  2505. // ProfileCurve seems to combine hole shape and profile curve so we need to only compare against the lower 3 bits
  2506. else if (pbs.PathCurve == (byte)Extrusion.Curve1)
  2507. {
  2508. iPropertiesNotSupportedDefault++;
  2509. }
  2510. }
  2511. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
  2512. {
  2513. if (pbs.PathCurve == (byte)Extrusion.Curve1 || pbs.PathCurve == (byte)Extrusion.Curve2)
  2514. {
  2515. iPropertiesNotSupportedDefault++;
  2516. }
  2517. }
  2518. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
  2519. {
  2520. if (pbs.PathCurve == (byte)Extrusion.Straight)
  2521. {
  2522. iPropertiesNotSupportedDefault++;
  2523. }
  2524. else if (pbs.PathCurve == (byte)Extrusion.Curve1)
  2525. {
  2526. iPropertiesNotSupportedDefault++;
  2527. }
  2528. }
  2529. if (pbs.SculptEntry && meshSculptedPrim)
  2530. iPropertiesNotSupportedDefault++;
  2531. if (iPropertiesNotSupportedDefault == 0)
  2532. {
  2533. #if SPAM
  2534. m_log.Warn("NonMesh");
  2535. #endif
  2536. return false;
  2537. }
  2538. #if SPAM
  2539. m_log.Debug("Mesh");
  2540. #endif
  2541. return true;
  2542. }
  2543. /// <summary>
  2544. /// Called after our prim properties are set Scale, position etc.
  2545. /// </summary>
  2546. /// <remarks>
  2547. /// We use this event queue like method to keep changes to the physical scene occuring in the threadlocked mutex
  2548. /// This assures us that we have no race conditions
  2549. /// </remarks>
  2550. /// <param name="actor"></param>
  2551. public override void AddPhysicsActorTaint(PhysicsActor actor)
  2552. {
  2553. if (actor is OdePrim)
  2554. {
  2555. OdePrim taintedprim = ((OdePrim)actor);
  2556. lock (_taintedPrims)
  2557. _taintedPrims.Add(taintedprim);
  2558. }
  2559. else if (actor is OdeCharacter)
  2560. {
  2561. OdeCharacter taintedchar = ((OdeCharacter)actor);
  2562. lock (_taintedActors)
  2563. {
  2564. _taintedActors.Add(taintedchar);
  2565. if (taintedchar.bad)
  2566. m_log.ErrorFormat("[ODE SCENE]: Added BAD actor {0} to tainted actors", taintedchar.m_uuid);
  2567. }
  2568. }
  2569. }
  2570. /// <summary>
  2571. /// This is our main simulate loop
  2572. /// </summary>
  2573. /// <remarks>
  2574. /// It's thread locked by a Mutex in the scene.
  2575. /// It holds Collisions, it instructs ODE to step through the physical reactions
  2576. /// It moves the objects around in memory
  2577. /// It calls the methods that report back to the object owners.. (scenepresence, SceneObjectGroup)
  2578. /// </remarks>
  2579. /// <param name="timeStep"></param>
  2580. /// <returns>The number of frames simulated over that period.</returns>
  2581. public override float Simulate(float timeStep)
  2582. {
  2583. if (!_worldInitialized) return 11f;
  2584. int startFrameTick = CollectStats ? Util.EnvironmentTickCount() : 0;
  2585. int tempTick = 0, tempTick2 = 0;
  2586. if (framecount >= int.MaxValue)
  2587. framecount = 0;
  2588. framecount++;
  2589. float fps = 0;
  2590. float timeLeft = timeStep;
  2591. //m_log.Info(timeStep.ToString());
  2592. // step_time += timeSte
  2593. //
  2594. // // If We're loaded down by something else,
  2595. // // or debugging with the Visual Studio project on pause
  2596. // // skip a few frames to catch up gracefully.
  2597. // // without shooting the physicsactors all over the place
  2598. //
  2599. // if (step_time >= m_SkipFramesAtms)
  2600. // {
  2601. // // Instead of trying to catch up, it'll do 5 physics frames only
  2602. // step_time = ODE_STEPSIZE;
  2603. // m_physicsiterations = 5;
  2604. // }
  2605. // else
  2606. // {
  2607. // m_physicsiterations = 10;
  2608. // }
  2609. // We change _collisionEventPrimChanges to avoid locking _collisionEventPrim itself and causing potential
  2610. // deadlock if the collision event tries to lock something else later on which is already locked by a
  2611. // caller that is adding or removing the collision event.
  2612. lock (m_collisionEventActorsChanges)
  2613. {
  2614. foreach (KeyValuePair<uint, PhysicsActor> kvp in m_collisionEventActorsChanges)
  2615. {
  2616. if (kvp.Value == null)
  2617. m_collisionEventActors.Remove(kvp.Key);
  2618. else
  2619. m_collisionEventActors[kvp.Key] = kvp.Value;
  2620. }
  2621. m_collisionEventActorsChanges.Clear();
  2622. }
  2623. if (SupportsNINJAJoints)
  2624. {
  2625. DeleteRequestedJoints(); // this must be outside of the lock (OdeLock) to avoid deadlocks
  2626. CreateRequestedJoints(); // this must be outside of the lock (OdeLock) to avoid deadlocks
  2627. }
  2628. lock (OdeLock)
  2629. {
  2630. // Process 10 frames if the sim is running normal..
  2631. // process 5 frames if the sim is running slow
  2632. //try
  2633. //{
  2634. //d.WorldSetQuickStepNumIterations(world, m_physicsiterations);
  2635. //}
  2636. //catch (StackOverflowException)
  2637. //{
  2638. // m_log.Error("[PHYSICS]: The operating system wasn't able to allocate enough memory for the simulation. Restarting the sim.");
  2639. // ode.drelease(world);
  2640. //base.TriggerPhysicsBasedRestart();
  2641. //}
  2642. // Figure out the Frames Per Second we're going at.
  2643. //(step_time == 0.004f, there's 250 of those per second. Times the step time/step size
  2644. fps = (timeStep / ODE_STEPSIZE) * 1000;
  2645. // HACK: Using a time dilation of 1.0 to debug rubberbanding issues
  2646. //m_timeDilation = Math.Min((step_time / ODE_STEPSIZE) / (0.09375f / ODE_STEPSIZE), 1.0f);
  2647. while (timeLeft > 0.0f)
  2648. {
  2649. try
  2650. {
  2651. if (CollectStats)
  2652. tempTick = Util.EnvironmentTickCount();
  2653. lock (_taintedActors)
  2654. {
  2655. foreach (OdeCharacter character in _taintedActors)
  2656. character.ProcessTaints();
  2657. _taintedActors.Clear();
  2658. }
  2659. if (CollectStats)
  2660. {
  2661. tempTick2 = Util.EnvironmentTickCount();
  2662. m_stats[ODEAvatarTaintMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2663. tempTick = tempTick2;
  2664. }
  2665. lock (_taintedPrims)
  2666. {
  2667. foreach (OdePrim prim in _taintedPrims)
  2668. {
  2669. if (prim.m_taintremove)
  2670. {
  2671. // Console.WriteLine("Simulate calls RemovePrimThreadLocked for {0}", prim.Name);
  2672. RemovePrimThreadLocked(prim);
  2673. }
  2674. else
  2675. {
  2676. // Console.WriteLine("Simulate calls ProcessTaints for {0}", prim.Name);
  2677. prim.ProcessTaints();
  2678. }
  2679. prim.m_collisionscore = 0;
  2680. // This loop can block up the Heartbeat for a very long time on large regions.
  2681. // We need to let the Watchdog know that the Heartbeat is not dead
  2682. // NOTE: This is currently commented out, but if things like OAR loading are
  2683. // timing the heartbeat out we will need to uncomment it
  2684. //Watchdog.UpdateThread();
  2685. }
  2686. if (SupportsNINJAJoints)
  2687. SimulatePendingNINJAJoints();
  2688. _taintedPrims.Clear();
  2689. }
  2690. if (CollectStats)
  2691. {
  2692. tempTick2 = Util.EnvironmentTickCount();
  2693. m_stats[ODEPrimTaintMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2694. tempTick = tempTick2;
  2695. }
  2696. // Move characters
  2697. foreach (OdeCharacter actor in _characters)
  2698. actor.Move(defects);
  2699. if (defects.Count != 0)
  2700. {
  2701. foreach (OdeCharacter actor in defects)
  2702. {
  2703. m_log.ErrorFormat(
  2704. "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2} due to defect found when moving",
  2705. actor.Name, actor.LocalID, PhysicsSceneName);
  2706. RemoveCharacter(actor);
  2707. actor.DestroyOdeStructures();
  2708. }
  2709. defects.Clear();
  2710. }
  2711. if (CollectStats)
  2712. {
  2713. tempTick2 = Util.EnvironmentTickCount();
  2714. m_stats[ODEAvatarForcesFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2715. tempTick = tempTick2;
  2716. }
  2717. // Move other active objects
  2718. foreach (OdePrim prim in _activeprims)
  2719. {
  2720. prim.m_collisionscore = 0;
  2721. prim.Move(timeStep);
  2722. }
  2723. if (CollectStats)
  2724. {
  2725. tempTick2 = Util.EnvironmentTickCount();
  2726. m_stats[ODEPrimForcesFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2727. tempTick = tempTick2;
  2728. }
  2729. //if ((framecount % m_randomizeWater) == 0)
  2730. // randomizeWater(waterlevel);
  2731. //int RayCastTimeMS = m_rayCastManager.ProcessQueuedRequests();
  2732. m_rayCastManager.ProcessQueuedRequests();
  2733. if (CollectStats)
  2734. {
  2735. tempTick2 = Util.EnvironmentTickCount();
  2736. m_stats[ODERaycastingFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2737. tempTick = tempTick2;
  2738. }
  2739. collision_optimized();
  2740. if (CollectStats)
  2741. {
  2742. tempTick2 = Util.EnvironmentTickCount();
  2743. m_stats[ODEOtherCollisionFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2744. tempTick = tempTick2;
  2745. }
  2746. foreach (PhysicsActor obj in m_collisionEventActors.Values)
  2747. {
  2748. // m_log.DebugFormat("[PHYSICS]: Assessing {0} {1} for collision events", obj.SOPName, obj.LocalID);
  2749. switch ((ActorTypes)obj.PhysicsActorType)
  2750. {
  2751. case ActorTypes.Agent:
  2752. OdeCharacter cobj = (OdeCharacter)obj;
  2753. cobj.AddCollisionFrameTime(100);
  2754. cobj.SendCollisions();
  2755. break;
  2756. case ActorTypes.Prim:
  2757. OdePrim pobj = (OdePrim)obj;
  2758. pobj.SendCollisions();
  2759. break;
  2760. }
  2761. }
  2762. // if (m_global_contactcount > 0)
  2763. // m_log.DebugFormat(
  2764. // "[PHYSICS]: Collision contacts to process this frame = {0}", m_global_contactcount);
  2765. m_global_contactcount = 0;
  2766. if (CollectStats)
  2767. {
  2768. tempTick2 = Util.EnvironmentTickCount();
  2769. m_stats[ODECollisionNotificationFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2770. tempTick = tempTick2;
  2771. }
  2772. d.WorldQuickStep(world, ODE_STEPSIZE);
  2773. if (CollectStats)
  2774. m_stats[ODENativeStepFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick);
  2775. d.JointGroupEmpty(contactgroup);
  2776. }
  2777. catch (Exception e)
  2778. {
  2779. m_log.ErrorFormat("[ODE SCENE]: {0}, {1}, {2}", e.Message, e.TargetSite, e);
  2780. }
  2781. timeLeft -= ODE_STEPSIZE;
  2782. }
  2783. if (CollectStats)
  2784. tempTick = Util.EnvironmentTickCount();
  2785. foreach (OdeCharacter actor in _characters)
  2786. {
  2787. if (actor.bad)
  2788. m_log.ErrorFormat("[ODE SCENE]: BAD Actor {0} in _characters list was not removed?", actor.m_uuid);
  2789. actor.UpdatePositionAndVelocity(defects);
  2790. }
  2791. if (defects.Count != 0)
  2792. {
  2793. foreach (OdeCharacter actor in defects)
  2794. {
  2795. m_log.ErrorFormat(
  2796. "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2} due to defect found when updating position and velocity",
  2797. actor.Name, actor.LocalID, PhysicsSceneName);
  2798. RemoveCharacter(actor);
  2799. actor.DestroyOdeStructures();
  2800. }
  2801. defects.Clear();
  2802. }
  2803. if (CollectStats)
  2804. {
  2805. tempTick2 = Util.EnvironmentTickCount();
  2806. m_stats[ODEAvatarUpdateFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2807. tempTick = tempTick2;
  2808. }
  2809. //if (timeStep < 0.2f)
  2810. foreach (OdePrim prim in _activeprims)
  2811. {
  2812. if (prim.IsPhysical && (d.BodyIsEnabled(prim.Body) || !prim._zeroFlag))
  2813. {
  2814. prim.UpdatePositionAndVelocity();
  2815. if (SupportsNINJAJoints)
  2816. SimulateActorPendingJoints(prim);
  2817. }
  2818. }
  2819. if (CollectStats)
  2820. m_stats[ODEPrimUpdateFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick);
  2821. //DumpJointInfo();
  2822. // Finished with all sim stepping. If requested, dump world state to file for debugging.
  2823. // TODO: This call to the export function is already inside lock (OdeLock) - but is an extra lock needed?
  2824. // TODO: This overwrites all dump files in-place. Should this be a growing logfile, or separate snapshots?
  2825. if (physics_logging && (physics_logging_interval > 0) && (framecount % physics_logging_interval == 0))
  2826. {
  2827. string fname = "state-" + world.ToString() + ".DIF"; // give each physics world a separate filename
  2828. string prefix = "world" + world.ToString(); // prefix for variable names in exported .DIF file
  2829. if (physics_logging_append_existing_logfile)
  2830. {
  2831. string header = "-------------- START OF PHYSICS FRAME " + framecount.ToString() + " --------------";
  2832. TextWriter fwriter = File.AppendText(fname);
  2833. fwriter.WriteLine(header);
  2834. fwriter.Close();
  2835. }
  2836. d.WorldExportDIF(world, fname, physics_logging_append_existing_logfile, prefix);
  2837. }
  2838. latertickcount = Util.EnvironmentTickCountSubtract(tickCountFrameRun);
  2839. // OpenSimulator above does 10 fps. 10 fps = means that the main thread loop and physics
  2840. // has a max of 100 ms to run theoretically.
  2841. // If the main loop stalls, it calls Simulate later which makes the tick count ms larger.
  2842. // If Physics stalls, it takes longer which makes the tick count ms larger.
  2843. if (latertickcount < 100)
  2844. {
  2845. m_timeDilation = 1.0f;
  2846. }
  2847. else
  2848. {
  2849. m_timeDilation = 100f / latertickcount;
  2850. //m_timeDilation = Math.Min((Math.Max(100 - (Util.EnvironmentTickCount() - tickCountFrameRun), 1) / 100f), 1.0f);
  2851. }
  2852. tickCountFrameRun = Util.EnvironmentTickCount();
  2853. if (CollectStats)
  2854. m_stats[ODETotalFrameMsStatName] += Util.EnvironmentTickCountSubtract(startFrameTick);
  2855. }
  2856. return fps;
  2857. }
  2858. /// <summary>
  2859. /// Simulate pending NINJA joints.
  2860. /// </summary>
  2861. /// <remarks>
  2862. /// Called by the main Simulate() loop if NINJA joints are active. Should not be called from anywhere else.
  2863. /// </remarks>
  2864. private void SimulatePendingNINJAJoints()
  2865. {
  2866. // Create pending joints, if possible
  2867. // joints can only be processed after ALL bodies are processed (and exist in ODE), since creating
  2868. // a joint requires specifying the body id of both involved bodies
  2869. if (pendingJoints.Count > 0)
  2870. {
  2871. List<PhysicsJoint> successfullyProcessedPendingJoints = new List<PhysicsJoint>();
  2872. //DoJointErrorMessage(joints_connecting_actor, "taint: " + pendingJoints.Count + " pending joints");
  2873. foreach (PhysicsJoint joint in pendingJoints)
  2874. {
  2875. //DoJointErrorMessage(joint, "taint: time to create joint with parms: " + joint.RawParams);
  2876. string[] jointParams = joint.RawParams.Split(" ".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries);
  2877. List<IntPtr> jointBodies = new List<IntPtr>();
  2878. bool allJointBodiesAreReady = true;
  2879. foreach (string jointParam in jointParams)
  2880. {
  2881. if (jointParam == "NULL")
  2882. {
  2883. //DoJointErrorMessage(joint, "attaching NULL joint to world");
  2884. jointBodies.Add(IntPtr.Zero);
  2885. }
  2886. else
  2887. {
  2888. //DoJointErrorMessage(joint, "looking for prim name: " + jointParam);
  2889. bool foundPrim = false;
  2890. lock (_prims)
  2891. {
  2892. foreach (OdePrim prim in _prims) // FIXME: inefficient
  2893. {
  2894. if (prim.SOPName == jointParam)
  2895. {
  2896. //DoJointErrorMessage(joint, "found for prim name: " + jointParam);
  2897. if (prim.IsPhysical && prim.Body != IntPtr.Zero)
  2898. {
  2899. jointBodies.Add(prim.Body);
  2900. foundPrim = true;
  2901. break;
  2902. }
  2903. else
  2904. {
  2905. DoJointErrorMessage(joint, "prim name " + jointParam +
  2906. " exists but is not (yet) physical; deferring joint creation. " +
  2907. "IsPhysical property is " + prim.IsPhysical +
  2908. " and body is " + prim.Body);
  2909. foundPrim = false;
  2910. break;
  2911. }
  2912. }
  2913. }
  2914. }
  2915. if (foundPrim)
  2916. {
  2917. // all is fine
  2918. }
  2919. else
  2920. {
  2921. allJointBodiesAreReady = false;
  2922. break;
  2923. }
  2924. }
  2925. }
  2926. if (allJointBodiesAreReady)
  2927. {
  2928. //DoJointErrorMessage(joint, "allJointBodiesAreReady for " + joint.ObjectNameInScene + " with parms " + joint.RawParams);
  2929. if (jointBodies[0] == jointBodies[1])
  2930. {
  2931. DoJointErrorMessage(joint, "ERROR: joint cannot be created; the joint bodies are the same, body1==body2. Raw body is " + jointBodies[0] + ". raw parms: " + joint.RawParams);
  2932. }
  2933. else
  2934. {
  2935. switch (joint.Type)
  2936. {
  2937. case PhysicsJointType.Ball:
  2938. {
  2939. IntPtr odeJoint;
  2940. //DoJointErrorMessage(joint, "ODE creating ball joint ");
  2941. odeJoint = d.JointCreateBall(world, IntPtr.Zero);
  2942. //DoJointErrorMessage(joint, "ODE attaching ball joint: " + odeJoint + " with b1:" + jointBodies[0] + " b2:" + jointBodies[1]);
  2943. d.JointAttach(odeJoint, jointBodies[0], jointBodies[1]);
  2944. //DoJointErrorMessage(joint, "ODE setting ball anchor: " + odeJoint + " to vec:" + joint.Position);
  2945. d.JointSetBallAnchor(odeJoint,
  2946. joint.Position.X,
  2947. joint.Position.Y,
  2948. joint.Position.Z);
  2949. //DoJointErrorMessage(joint, "ODE joint setting OK");
  2950. //DoJointErrorMessage(joint, "The ball joint's bodies are here: b0: ");
  2951. //DoJointErrorMessage(joint, "" + (jointBodies[0] != IntPtr.Zero ? "" + d.BodyGetPosition(jointBodies[0]) : "fixed environment"));
  2952. //DoJointErrorMessage(joint, "The ball joint's bodies are here: b1: ");
  2953. //DoJointErrorMessage(joint, "" + (jointBodies[1] != IntPtr.Zero ? "" + d.BodyGetPosition(jointBodies[1]) : "fixed environment"));
  2954. if (joint is OdePhysicsJoint)
  2955. {
  2956. ((OdePhysicsJoint)joint).jointID = odeJoint;
  2957. }
  2958. else
  2959. {
  2960. DoJointErrorMessage(joint, "WARNING: non-ode joint in ODE!");
  2961. }
  2962. }
  2963. break;
  2964. case PhysicsJointType.Hinge:
  2965. {
  2966. IntPtr odeJoint;
  2967. //DoJointErrorMessage(joint, "ODE creating hinge joint ");
  2968. odeJoint = d.JointCreateHinge(world, IntPtr.Zero);
  2969. //DoJointErrorMessage(joint, "ODE attaching hinge joint: " + odeJoint + " with b1:" + jointBodies[0] + " b2:" + jointBodies[1]);
  2970. d.JointAttach(odeJoint, jointBodies[0], jointBodies[1]);
  2971. //DoJointErrorMessage(joint, "ODE setting hinge anchor: " + odeJoint + " to vec:" + joint.Position);
  2972. d.JointSetHingeAnchor(odeJoint,
  2973. joint.Position.X,
  2974. joint.Position.Y,
  2975. joint.Position.Z);
  2976. // We use the orientation of the x-axis of the joint's coordinate frame
  2977. // as the axis for the hinge.
  2978. // Therefore, we must get the joint's coordinate frame based on the
  2979. // joint.Rotation field, which originates from the orientation of the
  2980. // joint's proxy object in the scene.
  2981. // The joint's coordinate frame is defined as the transformation matrix
  2982. // that converts a vector from joint-local coordinates into world coordinates.
  2983. // World coordinates are defined as the XYZ coordinate system of the sim,
  2984. // as shown in the top status-bar of the viewer.
  2985. // Once we have the joint's coordinate frame, we extract its X axis (AtAxis)
  2986. // and use that as the hinge axis.
  2987. //joint.Rotation.Normalize();
  2988. Matrix4 proxyFrame = Matrix4.CreateFromQuaternion(joint.Rotation);
  2989. // Now extract the X axis of the joint's coordinate frame.
  2990. // Do not try to use proxyFrame.AtAxis or you will become mired in the
  2991. // tar pit of transposed, inverted, and generally messed-up orientations.
  2992. // (In other words, Matrix4.AtAxis() is borked.)
  2993. // Vector3 jointAxis = proxyFrame.AtAxis; <--- this path leadeth to madness
  2994. // Instead, compute the X axis of the coordinate frame by transforming
  2995. // the (1,0,0) vector. At least that works.
  2996. //m_log.Debug("PHY: making axis: complete matrix is " + proxyFrame);
  2997. Vector3 jointAxis = Vector3.Transform(Vector3.UnitX, proxyFrame);
  2998. //m_log.Debug("PHY: making axis: hinge joint axis is " + jointAxis);
  2999. //DoJointErrorMessage(joint, "ODE setting hinge axis: " + odeJoint + " to vec:" + jointAxis);
  3000. d.JointSetHingeAxis(odeJoint,
  3001. jointAxis.X,
  3002. jointAxis.Y,
  3003. jointAxis.Z);
  3004. //d.JointSetHingeParam(odeJoint, (int)dParam.CFM, 0.1f);
  3005. if (joint is OdePhysicsJoint)
  3006. {
  3007. ((OdePhysicsJoint)joint).jointID = odeJoint;
  3008. }
  3009. else
  3010. {
  3011. DoJointErrorMessage(joint, "WARNING: non-ode joint in ODE!");
  3012. }
  3013. }
  3014. break;
  3015. }
  3016. successfullyProcessedPendingJoints.Add(joint);
  3017. }
  3018. }
  3019. else
  3020. {
  3021. DoJointErrorMessage(joint, "joint could not yet be created; still pending");
  3022. }
  3023. }
  3024. foreach (PhysicsJoint successfullyProcessedJoint in successfullyProcessedPendingJoints)
  3025. {
  3026. //DoJointErrorMessage(successfullyProcessedJoint, "finalizing succesfully procsssed joint " + successfullyProcessedJoint.ObjectNameInScene + " parms " + successfullyProcessedJoint.RawParams);
  3027. //DoJointErrorMessage(successfullyProcessedJoint, "removing from pending");
  3028. InternalRemovePendingJoint(successfullyProcessedJoint);
  3029. //DoJointErrorMessage(successfullyProcessedJoint, "adding to active");
  3030. InternalAddActiveJoint(successfullyProcessedJoint);
  3031. //DoJointErrorMessage(successfullyProcessedJoint, "done");
  3032. }
  3033. }
  3034. }
  3035. /// <summary>
  3036. /// Simulate the joint proxies of a NINJA actor.
  3037. /// </summary>
  3038. /// <remarks>
  3039. /// Called as part of the Simulate() loop if NINJA physics is active. Must only be called from there.
  3040. /// </remarks>
  3041. /// <param name="actor"></param>
  3042. private void SimulateActorPendingJoints(OdePrim actor)
  3043. {
  3044. // If an actor moved, move its joint proxy objects as well.
  3045. // There seems to be an event PhysicsActor.OnPositionUpdate that could be used
  3046. // for this purpose but it is never called! So we just do the joint
  3047. // movement code here.
  3048. if (actor.SOPName != null &&
  3049. joints_connecting_actor.ContainsKey(actor.SOPName) &&
  3050. joints_connecting_actor[actor.SOPName] != null &&
  3051. joints_connecting_actor[actor.SOPName].Count > 0)
  3052. {
  3053. foreach (PhysicsJoint affectedJoint in joints_connecting_actor[actor.SOPName])
  3054. {
  3055. if (affectedJoint.IsInPhysicsEngine)
  3056. {
  3057. DoJointMoved(affectedJoint);
  3058. }
  3059. else
  3060. {
  3061. DoJointErrorMessage(affectedJoint, "a body connected to a joint was moved, but the joint doesn't exist yet! this will lead to joint error. joint was: " + affectedJoint.ObjectNameInScene + " parms:" + affectedJoint.RawParams);
  3062. }
  3063. }
  3064. }
  3065. }
  3066. public override void GetResults()
  3067. {
  3068. }
  3069. public override bool IsThreaded
  3070. {
  3071. // for now we won't be multithreaded
  3072. get { return false; }
  3073. }
  3074. #region ODE Specific Terrain Fixes
  3075. private float[] ResizeTerrain512NearestNeighbour(float[] heightMap)
  3076. {
  3077. float[] returnarr = new float[262144];
  3078. float[,] resultarr = new float[(int)WorldExtents.X, (int)WorldExtents.Y];
  3079. // Filling out the array into its multi-dimensional components
  3080. for (int y = 0; y < WorldExtents.Y; y++)
  3081. {
  3082. for (int x = 0; x < WorldExtents.X; x++)
  3083. {
  3084. resultarr[y, x] = heightMap[y * (int)WorldExtents.Y + x];
  3085. }
  3086. }
  3087. // Resize using Nearest Neighbour
  3088. // This particular way is quick but it only works on a multiple of the original
  3089. // The idea behind this method can be described with the following diagrams
  3090. // second pass and third pass happen in the same loop really.. just separated
  3091. // them to show what this does.
  3092. // First Pass
  3093. // ResultArr:
  3094. // 1,1,1,1,1,1
  3095. // 1,1,1,1,1,1
  3096. // 1,1,1,1,1,1
  3097. // 1,1,1,1,1,1
  3098. // 1,1,1,1,1,1
  3099. // 1,1,1,1,1,1
  3100. // Second Pass
  3101. // ResultArr2:
  3102. // 1,,1,,1,,1,,1,,1,
  3103. // ,,,,,,,,,,
  3104. // 1,,1,,1,,1,,1,,1,
  3105. // ,,,,,,,,,,
  3106. // 1,,1,,1,,1,,1,,1,
  3107. // ,,,,,,,,,,
  3108. // 1,,1,,1,,1,,1,,1,
  3109. // ,,,,,,,,,,
  3110. // 1,,1,,1,,1,,1,,1,
  3111. // ,,,,,,,,,,
  3112. // 1,,1,,1,,1,,1,,1,
  3113. // Third pass fills in the blanks
  3114. // ResultArr2:
  3115. // 1,1,1,1,1,1,1,1,1,1,1,1
  3116. // 1,1,1,1,1,1,1,1,1,1,1,1
  3117. // 1,1,1,1,1,1,1,1,1,1,1,1
  3118. // 1,1,1,1,1,1,1,1,1,1,1,1
  3119. // 1,1,1,1,1,1,1,1,1,1,1,1
  3120. // 1,1,1,1,1,1,1,1,1,1,1,1
  3121. // 1,1,1,1,1,1,1,1,1,1,1,1
  3122. // 1,1,1,1,1,1,1,1,1,1,1,1
  3123. // 1,1,1,1,1,1,1,1,1,1,1,1
  3124. // 1,1,1,1,1,1,1,1,1,1,1,1
  3125. // 1,1,1,1,1,1,1,1,1,1,1,1
  3126. // X,Y = .
  3127. // X+1,y = ^
  3128. // X,Y+1 = *
  3129. // X+1,Y+1 = #
  3130. // Filling in like this;
  3131. // .*
  3132. // ^#
  3133. // 1st .
  3134. // 2nd *
  3135. // 3rd ^
  3136. // 4th #
  3137. // on single loop.
  3138. float[,] resultarr2 = new float[512, 512];
  3139. for (int y = 0; y < WorldExtents.Y; y++)
  3140. {
  3141. for (int x = 0; x < WorldExtents.X; x++)
  3142. {
  3143. resultarr2[y * 2, x * 2] = resultarr[y, x];
  3144. if (y < WorldExtents.Y)
  3145. {
  3146. resultarr2[(y * 2) + 1, x * 2] = resultarr[y, x];
  3147. }
  3148. if (x < WorldExtents.X)
  3149. {
  3150. resultarr2[y * 2, (x * 2) + 1] = resultarr[y, x];
  3151. }
  3152. if (x < WorldExtents.X && y < WorldExtents.Y)
  3153. {
  3154. resultarr2[(y * 2) + 1, (x * 2) + 1] = resultarr[y, x];
  3155. }
  3156. }
  3157. }
  3158. //Flatten out the array
  3159. int i = 0;
  3160. for (int y = 0; y < 512; y++)
  3161. {
  3162. for (int x = 0; x < 512; x++)
  3163. {
  3164. if (resultarr2[y, x] <= 0)
  3165. returnarr[i] = 0.0000001f;
  3166. else
  3167. returnarr[i] = resultarr2[y, x];
  3168. i++;
  3169. }
  3170. }
  3171. return returnarr;
  3172. }
  3173. private float[] ResizeTerrain512Interpolation(float[] heightMap)
  3174. {
  3175. float[] returnarr = new float[262144];
  3176. float[,] resultarr = new float[512,512];
  3177. // Filling out the array into its multi-dimensional components
  3178. for (int y = 0; y < 256; y++)
  3179. {
  3180. for (int x = 0; x < 256; x++)
  3181. {
  3182. resultarr[y, x] = heightMap[y * 256 + x];
  3183. }
  3184. }
  3185. // Resize using interpolation
  3186. // This particular way is quick but it only works on a multiple of the original
  3187. // The idea behind this method can be described with the following diagrams
  3188. // second pass and third pass happen in the same loop really.. just separated
  3189. // them to show what this does.
  3190. // First Pass
  3191. // ResultArr:
  3192. // 1,1,1,1,1,1
  3193. // 1,1,1,1,1,1
  3194. // 1,1,1,1,1,1
  3195. // 1,1,1,1,1,1
  3196. // 1,1,1,1,1,1
  3197. // 1,1,1,1,1,1
  3198. // Second Pass
  3199. // ResultArr2:
  3200. // 1,,1,,1,,1,,1,,1,
  3201. // ,,,,,,,,,,
  3202. // 1,,1,,1,,1,,1,,1,
  3203. // ,,,,,,,,,,
  3204. // 1,,1,,1,,1,,1,,1,
  3205. // ,,,,,,,,,,
  3206. // 1,,1,,1,,1,,1,,1,
  3207. // ,,,,,,,,,,
  3208. // 1,,1,,1,,1,,1,,1,
  3209. // ,,,,,,,,,,
  3210. // 1,,1,,1,,1,,1,,1,
  3211. // Third pass fills in the blanks
  3212. // ResultArr2:
  3213. // 1,1,1,1,1,1,1,1,1,1,1,1
  3214. // 1,1,1,1,1,1,1,1,1,1,1,1
  3215. // 1,1,1,1,1,1,1,1,1,1,1,1
  3216. // 1,1,1,1,1,1,1,1,1,1,1,1
  3217. // 1,1,1,1,1,1,1,1,1,1,1,1
  3218. // 1,1,1,1,1,1,1,1,1,1,1,1
  3219. // 1,1,1,1,1,1,1,1,1,1,1,1
  3220. // 1,1,1,1,1,1,1,1,1,1,1,1
  3221. // 1,1,1,1,1,1,1,1,1,1,1,1
  3222. // 1,1,1,1,1,1,1,1,1,1,1,1
  3223. // 1,1,1,1,1,1,1,1,1,1,1,1
  3224. // X,Y = .
  3225. // X+1,y = ^
  3226. // X,Y+1 = *
  3227. // X+1,Y+1 = #
  3228. // Filling in like this;
  3229. // .*
  3230. // ^#
  3231. // 1st .
  3232. // 2nd *
  3233. // 3rd ^
  3234. // 4th #
  3235. // on single loop.
  3236. float[,] resultarr2 = new float[512,512];
  3237. for (int y = 0; y < (int)Constants.RegionSize; y++)
  3238. {
  3239. for (int x = 0; x < (int)Constants.RegionSize; x++)
  3240. {
  3241. resultarr2[y*2, x*2] = resultarr[y, x];
  3242. if (y < (int)Constants.RegionSize)
  3243. {
  3244. if (y + 1 < (int)Constants.RegionSize)
  3245. {
  3246. if (x + 1 < (int)Constants.RegionSize)
  3247. {
  3248. resultarr2[(y*2) + 1, x*2] = ((resultarr[y, x] + resultarr[y + 1, x] +
  3249. resultarr[y, x + 1] + resultarr[y + 1, x + 1])/4);
  3250. }
  3251. else
  3252. {
  3253. resultarr2[(y*2) + 1, x*2] = ((resultarr[y, x] + resultarr[y + 1, x])/2);
  3254. }
  3255. }
  3256. else
  3257. {
  3258. resultarr2[(y*2) + 1, x*2] = resultarr[y, x];
  3259. }
  3260. }
  3261. if (x < (int)Constants.RegionSize)
  3262. {
  3263. if (x + 1 < (int)Constants.RegionSize)
  3264. {
  3265. if (y + 1 < (int)Constants.RegionSize)
  3266. {
  3267. resultarr2[y*2, (x*2) + 1] = ((resultarr[y, x] + resultarr[y + 1, x] +
  3268. resultarr[y, x + 1] + resultarr[y + 1, x + 1])/4);
  3269. }
  3270. else
  3271. {
  3272. resultarr2[y*2, (x*2) + 1] = ((resultarr[y, x] + resultarr[y, x + 1])/2);
  3273. }
  3274. }
  3275. else
  3276. {
  3277. resultarr2[y*2, (x*2) + 1] = resultarr[y, x];
  3278. }
  3279. }
  3280. if (x < (int)Constants.RegionSize && y < (int)Constants.RegionSize)
  3281. {
  3282. if ((x + 1 < (int)Constants.RegionSize) && (y + 1 < (int)Constants.RegionSize))
  3283. {
  3284. resultarr2[(y*2) + 1, (x*2) + 1] = ((resultarr[y, x] + resultarr[y + 1, x] +
  3285. resultarr[y, x + 1] + resultarr[y + 1, x + 1])/4);
  3286. }
  3287. else
  3288. {
  3289. resultarr2[(y*2) + 1, (x*2) + 1] = resultarr[y, x];
  3290. }
  3291. }
  3292. }
  3293. }
  3294. //Flatten out the array
  3295. int i = 0;
  3296. for (int y = 0; y < 512; y++)
  3297. {
  3298. for (int x = 0; x < 512; x++)
  3299. {
  3300. if (Single.IsNaN(resultarr2[y, x]) || Single.IsInfinity(resultarr2[y, x]))
  3301. {
  3302. m_log.Warn("[ODE SCENE]: Non finite heightfield element detected. Setting it to 0");
  3303. resultarr2[y, x] = 0;
  3304. }
  3305. returnarr[i] = resultarr2[y, x];
  3306. i++;
  3307. }
  3308. }
  3309. return returnarr;
  3310. }
  3311. #endregion
  3312. public override void SetTerrain(float[] heightMap)
  3313. {
  3314. if (m_worldOffset != Vector3.Zero && m_parentScene != null)
  3315. {
  3316. if (m_parentScene is OdeScene)
  3317. {
  3318. ((OdeScene)m_parentScene).SetTerrain(heightMap, m_worldOffset);
  3319. }
  3320. }
  3321. else
  3322. {
  3323. SetTerrain(heightMap, m_worldOffset);
  3324. }
  3325. }
  3326. private void SetTerrain(float[] heightMap, Vector3 pOffset)
  3327. {
  3328. int startTime = Util.EnvironmentTickCount();
  3329. m_log.DebugFormat("[ODE SCENE]: Setting terrain for {0} with offset {1}", PhysicsSceneName, pOffset);
  3330. // this._heightmap[i] = (double)heightMap[i];
  3331. // dbm (danx0r) -- creating a buffer zone of one extra sample all around
  3332. //_origheightmap = heightMap;
  3333. float[] _heightmap;
  3334. // zero out a heightmap array float array (single dimension [flattened]))
  3335. //if ((int)Constants.RegionSize == 256)
  3336. // _heightmap = new float[514 * 514];
  3337. //else
  3338. _heightmap = new float[(((int)Constants.RegionSize + 2) * ((int)Constants.RegionSize + 2))];
  3339. uint heightmapWidth = Constants.RegionSize + 1;
  3340. uint heightmapHeight = Constants.RegionSize + 1;
  3341. uint heightmapWidthSamples;
  3342. uint heightmapHeightSamples;
  3343. //if (((int)Constants.RegionSize) == 256)
  3344. //{
  3345. // heightmapWidthSamples = 2 * (uint)Constants.RegionSize + 2;
  3346. // heightmapHeightSamples = 2 * (uint)Constants.RegionSize + 2;
  3347. // heightmapWidth++;
  3348. // heightmapHeight++;
  3349. //}
  3350. //else
  3351. //{
  3352. heightmapWidthSamples = (uint)Constants.RegionSize + 1;
  3353. heightmapHeightSamples = (uint)Constants.RegionSize + 1;
  3354. //}
  3355. const float scale = 1.0f;
  3356. const float offset = 0.0f;
  3357. const float thickness = 0.2f;
  3358. const int wrap = 0;
  3359. int regionsize = (int) Constants.RegionSize + 2;
  3360. //Double resolution
  3361. //if (((int)Constants.RegionSize) == 256)
  3362. // heightMap = ResizeTerrain512Interpolation(heightMap);
  3363. // if (((int)Constants.RegionSize) == 256 && (int)Constants.RegionSize == 256)
  3364. // regionsize = 512;
  3365. float hfmin = 2000;
  3366. float hfmax = -2000;
  3367. for (int x = 0; x < heightmapWidthSamples; x++)
  3368. {
  3369. for (int y = 0; y < heightmapHeightSamples; y++)
  3370. {
  3371. int xx = Util.Clip(x - 1, 0, regionsize - 1);
  3372. int yy = Util.Clip(y - 1, 0, regionsize - 1);
  3373. float val= heightMap[yy * (int)Constants.RegionSize + xx];
  3374. _heightmap[x * ((int)Constants.RegionSize + 2) + y] = val;
  3375. hfmin = (val < hfmin) ? val : hfmin;
  3376. hfmax = (val > hfmax) ? val : hfmax;
  3377. }
  3378. }
  3379. lock (OdeLock)
  3380. {
  3381. IntPtr GroundGeom = IntPtr.Zero;
  3382. if (RegionTerrain.TryGetValue(pOffset, out GroundGeom))
  3383. {
  3384. RegionTerrain.Remove(pOffset);
  3385. if (GroundGeom != IntPtr.Zero)
  3386. {
  3387. if (TerrainHeightFieldHeights.ContainsKey(GroundGeom))
  3388. {
  3389. TerrainHeightFieldHeights.Remove(GroundGeom);
  3390. }
  3391. d.SpaceRemove(space, GroundGeom);
  3392. d.GeomDestroy(GroundGeom);
  3393. }
  3394. }
  3395. IntPtr HeightmapData = d.GeomHeightfieldDataCreate();
  3396. d.GeomHeightfieldDataBuildSingle(HeightmapData, _heightmap, 0, heightmapWidth + 1, heightmapHeight + 1,
  3397. (int)heightmapWidthSamples + 1, (int)heightmapHeightSamples + 1, scale,
  3398. offset, thickness, wrap);
  3399. d.GeomHeightfieldDataSetBounds(HeightmapData, hfmin - 1, hfmax + 1);
  3400. GroundGeom = d.CreateHeightfield(space, HeightmapData, 1);
  3401. if (GroundGeom != IntPtr.Zero)
  3402. {
  3403. d.GeomSetCategoryBits(GroundGeom, (int)(CollisionCategories.Land));
  3404. d.GeomSetCollideBits(GroundGeom, (int)(CollisionCategories.Space));
  3405. }
  3406. geom_name_map[GroundGeom] = "Terrain";
  3407. d.Matrix3 R = new d.Matrix3();
  3408. Quaternion q1 = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), 1.5707f);
  3409. Quaternion q2 = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), 1.5707f);
  3410. //Axiom.Math.Quaternion q3 = Axiom.Math.Quaternion.FromAngleAxis(3.14f, new Axiom.Math.Vector3(0, 0, 1));
  3411. q1 = q1 * q2;
  3412. //q1 = q1 * q3;
  3413. Vector3 v3;
  3414. float angle;
  3415. q1.GetAxisAngle(out v3, out angle);
  3416. d.RFromAxisAndAngle(out R, v3.X, v3.Y, v3.Z, angle);
  3417. d.GeomSetRotation(GroundGeom, ref R);
  3418. d.GeomSetPosition(GroundGeom, (pOffset.X + ((int)Constants.RegionSize * 0.5f)), (pOffset.Y + ((int)Constants.RegionSize * 0.5f)), 0);
  3419. IntPtr testGround = IntPtr.Zero;
  3420. if (RegionTerrain.TryGetValue(pOffset, out testGround))
  3421. {
  3422. RegionTerrain.Remove(pOffset);
  3423. }
  3424. RegionTerrain.Add(pOffset, GroundGeom, GroundGeom);
  3425. TerrainHeightFieldHeights.Add(GroundGeom,_heightmap);
  3426. }
  3427. m_log.DebugFormat(
  3428. "[ODE SCENE]: Setting terrain for {0} took {1}ms", PhysicsSceneName, Util.EnvironmentTickCountSubtract(startTime));
  3429. }
  3430. public override void DeleteTerrain()
  3431. {
  3432. }
  3433. internal float GetWaterLevel()
  3434. {
  3435. return waterlevel;
  3436. }
  3437. public override bool SupportsCombining()
  3438. {
  3439. return true;
  3440. }
  3441. // public override void UnCombine(PhysicsScene pScene)
  3442. // {
  3443. // IntPtr localGround = IntPtr.Zero;
  3444. //// float[] localHeightfield;
  3445. // bool proceed = false;
  3446. // List<IntPtr> geomDestroyList = new List<IntPtr>();
  3447. //
  3448. // lock (OdeLock)
  3449. // {
  3450. // if (RegionTerrain.TryGetValue(Vector3.Zero, out localGround))
  3451. // {
  3452. // foreach (IntPtr geom in TerrainHeightFieldHeights.Keys)
  3453. // {
  3454. // if (geom == localGround)
  3455. // {
  3456. //// localHeightfield = TerrainHeightFieldHeights[geom];
  3457. // proceed = true;
  3458. // }
  3459. // else
  3460. // {
  3461. // geomDestroyList.Add(geom);
  3462. // }
  3463. // }
  3464. //
  3465. // if (proceed)
  3466. // {
  3467. // m_worldOffset = Vector3.Zero;
  3468. // WorldExtents = new Vector2((int)Constants.RegionSize, (int)Constants.RegionSize);
  3469. // m_parentScene = null;
  3470. //
  3471. // foreach (IntPtr g in geomDestroyList)
  3472. // {
  3473. // // removingHeightField needs to be done or the garbage collector will
  3474. // // collect the terrain data before we tell ODE to destroy it causing
  3475. // // memory corruption
  3476. // if (TerrainHeightFieldHeights.ContainsKey(g))
  3477. // {
  3478. //// float[] removingHeightField = TerrainHeightFieldHeights[g];
  3479. // TerrainHeightFieldHeights.Remove(g);
  3480. //
  3481. // if (RegionTerrain.ContainsKey(g))
  3482. // {
  3483. // RegionTerrain.Remove(g);
  3484. // }
  3485. //
  3486. // d.GeomDestroy(g);
  3487. // //removingHeightField = new float[0];
  3488. // }
  3489. // }
  3490. //
  3491. // }
  3492. // else
  3493. // {
  3494. // m_log.Warn("[PHYSICS]: Couldn't proceed with UnCombine. Region has inconsistant data.");
  3495. // }
  3496. // }
  3497. // }
  3498. // }
  3499. public override void SetWaterLevel(float baseheight)
  3500. {
  3501. waterlevel = baseheight;
  3502. randomizeWater(waterlevel);
  3503. }
  3504. private void randomizeWater(float baseheight)
  3505. {
  3506. const uint heightmapWidth = m_regionWidth + 2;
  3507. const uint heightmapHeight = m_regionHeight + 2;
  3508. const uint heightmapWidthSamples = m_regionWidth + 2;
  3509. const uint heightmapHeightSamples = m_regionHeight + 2;
  3510. const float scale = 1.0f;
  3511. const float offset = 0.0f;
  3512. const float thickness = 2.9f;
  3513. const int wrap = 0;
  3514. for (int i = 0; i < (258 * 258); i++)
  3515. {
  3516. _watermap[i] = (baseheight-0.1f) + ((float)fluidRandomizer.Next(1,9) / 10f);
  3517. // m_log.Info((baseheight - 0.1f) + ((float)fluidRandomizer.Next(1, 9) / 10f));
  3518. }
  3519. lock (OdeLock)
  3520. {
  3521. if (WaterGeom != IntPtr.Zero)
  3522. {
  3523. d.SpaceRemove(space, WaterGeom);
  3524. }
  3525. IntPtr HeightmapData = d.GeomHeightfieldDataCreate();
  3526. d.GeomHeightfieldDataBuildSingle(HeightmapData, _watermap, 0, heightmapWidth, heightmapHeight,
  3527. (int)heightmapWidthSamples, (int)heightmapHeightSamples, scale,
  3528. offset, thickness, wrap);
  3529. d.GeomHeightfieldDataSetBounds(HeightmapData, m_regionWidth, m_regionHeight);
  3530. WaterGeom = d.CreateHeightfield(space, HeightmapData, 1);
  3531. if (WaterGeom != IntPtr.Zero)
  3532. {
  3533. d.GeomSetCategoryBits(WaterGeom, (int)(CollisionCategories.Water));
  3534. d.GeomSetCollideBits(WaterGeom, (int)(CollisionCategories.Space));
  3535. }
  3536. geom_name_map[WaterGeom] = "Water";
  3537. d.Matrix3 R = new d.Matrix3();
  3538. Quaternion q1 = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), 1.5707f);
  3539. Quaternion q2 = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), 1.5707f);
  3540. //Axiom.Math.Quaternion q3 = Axiom.Math.Quaternion.FromAngleAxis(3.14f, new Axiom.Math.Vector3(0, 0, 1));
  3541. q1 = q1 * q2;
  3542. //q1 = q1 * q3;
  3543. Vector3 v3;
  3544. float angle;
  3545. q1.GetAxisAngle(out v3, out angle);
  3546. d.RFromAxisAndAngle(out R, v3.X, v3.Y, v3.Z, angle);
  3547. d.GeomSetRotation(WaterGeom, ref R);
  3548. d.GeomSetPosition(WaterGeom, 128, 128, 0);
  3549. }
  3550. }
  3551. public override void Dispose()
  3552. {
  3553. _worldInitialized = false;
  3554. m_rayCastManager.Dispose();
  3555. m_rayCastManager = null;
  3556. lock (OdeLock)
  3557. {
  3558. lock (_prims)
  3559. {
  3560. foreach (OdePrim prm in _prims)
  3561. {
  3562. RemovePrim(prm);
  3563. }
  3564. }
  3565. //foreach (OdeCharacter act in _characters)
  3566. //{
  3567. //RemoveAvatar(act);
  3568. //}
  3569. d.WorldDestroy(world);
  3570. //d.CloseODE();
  3571. }
  3572. }
  3573. public override Dictionary<uint, float> GetTopColliders()
  3574. {
  3575. Dictionary<uint, float> topColliders;
  3576. lock (_prims)
  3577. {
  3578. List<OdePrim> orderedPrims = new List<OdePrim>(_prims);
  3579. orderedPrims.OrderByDescending(p => p.CollisionScore);
  3580. topColliders = orderedPrims.Take(25).ToDictionary(p => p.LocalID, p => p.CollisionScore);
  3581. foreach (OdePrim p in _prims)
  3582. p.CollisionScore = 0;
  3583. }
  3584. return topColliders;
  3585. }
  3586. public override bool SupportsRayCast()
  3587. {
  3588. return true;
  3589. }
  3590. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod)
  3591. {
  3592. if (retMethod != null)
  3593. {
  3594. m_rayCastManager.QueueRequest(position, direction, length, retMethod);
  3595. }
  3596. }
  3597. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayCallback retMethod)
  3598. {
  3599. if (retMethod != null)
  3600. {
  3601. m_rayCastManager.QueueRequest(position, direction, length, Count, retMethod);
  3602. }
  3603. }
  3604. public override List<ContactResult> RaycastWorld(Vector3 position, Vector3 direction, float length, int Count)
  3605. {
  3606. ContactResult[] ourResults = null;
  3607. RayCallback retMethod = delegate(List<ContactResult> results)
  3608. {
  3609. ourResults = new ContactResult[results.Count];
  3610. results.CopyTo(ourResults, 0);
  3611. };
  3612. int waitTime = 0;
  3613. m_rayCastManager.QueueRequest(position, direction, length, Count, retMethod);
  3614. while (ourResults == null && waitTime < 1000)
  3615. {
  3616. Thread.Sleep(1);
  3617. waitTime++;
  3618. }
  3619. if (ourResults == null)
  3620. return new List<ContactResult> ();
  3621. return new List<ContactResult>(ourResults);
  3622. }
  3623. #if USE_DRAWSTUFF
  3624. // Keyboard callback
  3625. public void command(int cmd)
  3626. {
  3627. IntPtr geom;
  3628. d.Mass mass;
  3629. d.Vector3 sides = new d.Vector3(d.RandReal() * 0.5f + 0.1f, d.RandReal() * 0.5f + 0.1f, d.RandReal() * 0.5f + 0.1f);
  3630. Char ch = Char.ToLower((Char)cmd);
  3631. switch ((Char)ch)
  3632. {
  3633. case 'w':
  3634. try
  3635. {
  3636. Vector3 rotate = (new Vector3(1, 0, 0) * Quaternion.CreateFromEulers(hpr.Z * Utils.DEG_TO_RAD, hpr.Y * Utils.DEG_TO_RAD, hpr.X * Utils.DEG_TO_RAD));
  3637. xyz.X += rotate.X; xyz.Y += rotate.Y; xyz.Z += rotate.Z;
  3638. ds.SetViewpoint(ref xyz, ref hpr);
  3639. }
  3640. catch (ArgumentException)
  3641. { hpr.X = 0; }
  3642. break;
  3643. case 'a':
  3644. hpr.X++;
  3645. ds.SetViewpoint(ref xyz, ref hpr);
  3646. break;
  3647. case 's':
  3648. try
  3649. {
  3650. Vector3 rotate2 = (new Vector3(-1, 0, 0) * Quaternion.CreateFromEulers(hpr.Z * Utils.DEG_TO_RAD, hpr.Y * Utils.DEG_TO_RAD, hpr.X * Utils.DEG_TO_RAD));
  3651. xyz.X += rotate2.X; xyz.Y += rotate2.Y; xyz.Z += rotate2.Z;
  3652. ds.SetViewpoint(ref xyz, ref hpr);
  3653. }
  3654. catch (ArgumentException)
  3655. { hpr.X = 0; }
  3656. break;
  3657. case 'd':
  3658. hpr.X--;
  3659. ds.SetViewpoint(ref xyz, ref hpr);
  3660. break;
  3661. case 'r':
  3662. xyz.Z++;
  3663. ds.SetViewpoint(ref xyz, ref hpr);
  3664. break;
  3665. case 'f':
  3666. xyz.Z--;
  3667. ds.SetViewpoint(ref xyz, ref hpr);
  3668. break;
  3669. case 'e':
  3670. xyz.Y++;
  3671. ds.SetViewpoint(ref xyz, ref hpr);
  3672. break;
  3673. case 'q':
  3674. xyz.Y--;
  3675. ds.SetViewpoint(ref xyz, ref hpr);
  3676. break;
  3677. }
  3678. }
  3679. public void step(int pause)
  3680. {
  3681. ds.SetColor(1.0f, 1.0f, 0.0f);
  3682. ds.SetTexture(ds.Texture.Wood);
  3683. lock (_prims)
  3684. {
  3685. foreach (OdePrim prm in _prims)
  3686. {
  3687. //IntPtr body = d.GeomGetBody(prm.prim_geom);
  3688. if (prm.prim_geom != IntPtr.Zero)
  3689. {
  3690. d.Vector3 pos;
  3691. d.GeomCopyPosition(prm.prim_geom, out pos);
  3692. //d.BodyCopyPosition(body, out pos);
  3693. d.Matrix3 R;
  3694. d.GeomCopyRotation(prm.prim_geom, out R);
  3695. //d.BodyCopyRotation(body, out R);
  3696. d.Vector3 sides = new d.Vector3();
  3697. sides.X = prm.Size.X;
  3698. sides.Y = prm.Size.Y;
  3699. sides.Z = prm.Size.Z;
  3700. ds.DrawBox(ref pos, ref R, ref sides);
  3701. }
  3702. }
  3703. }
  3704. ds.SetColor(1.0f, 0.0f, 0.0f);
  3705. foreach (OdeCharacter chr in _characters)
  3706. {
  3707. if (chr.Shell != IntPtr.Zero)
  3708. {
  3709. IntPtr body = d.GeomGetBody(chr.Shell);
  3710. d.Vector3 pos;
  3711. d.GeomCopyPosition(chr.Shell, out pos);
  3712. //d.BodyCopyPosition(body, out pos);
  3713. d.Matrix3 R;
  3714. d.GeomCopyRotation(chr.Shell, out R);
  3715. //d.BodyCopyRotation(body, out R);
  3716. ds.DrawCapsule(ref pos, ref R, chr.Size.Z, 0.35f);
  3717. d.Vector3 sides = new d.Vector3();
  3718. sides.X = 0.5f;
  3719. sides.Y = 0.5f;
  3720. sides.Z = 0.5f;
  3721. ds.DrawBox(ref pos, ref R, ref sides);
  3722. }
  3723. }
  3724. }
  3725. public void start(int unused)
  3726. {
  3727. ds.SetViewpoint(ref xyz, ref hpr);
  3728. }
  3729. #endif
  3730. public override Dictionary<string, float> GetStats()
  3731. {
  3732. if (!CollectStats)
  3733. return null;
  3734. Dictionary<string, float> returnStats;
  3735. lock (OdeLock)
  3736. {
  3737. returnStats = new Dictionary<string, float>(m_stats);
  3738. // FIXME: This is a SUPER DUMB HACK until we can establish stats that aren't subject to a division by
  3739. // 3 from the SimStatsReporter.
  3740. returnStats[ODETotalAvatarsStatName] = _characters.Count * 3;
  3741. returnStats[ODETotalPrimsStatName] = _prims.Count * 3;
  3742. returnStats[ODEActivePrimsStatName] = _activeprims.Count * 3;
  3743. InitializeExtraStats();
  3744. }
  3745. returnStats[ODEOtherCollisionFrameMsStatName]
  3746. = returnStats[ODEOtherCollisionFrameMsStatName]
  3747. - returnStats[ODENativeSpaceCollisionFrameMsStatName]
  3748. - returnStats[ODENativeGeomCollisionFrameMsStatName];
  3749. return returnStats;
  3750. }
  3751. private void InitializeExtraStats()
  3752. {
  3753. m_stats[ODETotalFrameMsStatName] = 0;
  3754. m_stats[ODEAvatarTaintMsStatName] = 0;
  3755. m_stats[ODEPrimTaintMsStatName] = 0;
  3756. m_stats[ODEAvatarForcesFrameMsStatName] = 0;
  3757. m_stats[ODEPrimForcesFrameMsStatName] = 0;
  3758. m_stats[ODERaycastingFrameMsStatName] = 0;
  3759. m_stats[ODENativeStepFrameMsStatName] = 0;
  3760. m_stats[ODENativeSpaceCollisionFrameMsStatName] = 0;
  3761. m_stats[ODENativeGeomCollisionFrameMsStatName] = 0;
  3762. m_stats[ODEOtherCollisionFrameMsStatName] = 0;
  3763. m_stats[ODECollisionNotificationFrameMsStatName] = 0;
  3764. m_stats[ODEAvatarContactsStatsName] = 0;
  3765. m_stats[ODEPrimContactsStatName] = 0;
  3766. m_stats[ODEAvatarUpdateFrameMsStatName] = 0;
  3767. m_stats[ODEPrimUpdateFrameMsStatName] = 0;
  3768. }
  3769. }
  3770. }