OdeScene.cs 182 KB

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