1
0

OdeScene.cs 168 KB

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