OdePlugin.cs 161 KB

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