OdeScene.cs 183 KB

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