OdeScene.cs 167 KB

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