ODEScene.cs 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824
  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. // Revision 2011/12/13 by Ubit Umarov
  28. //#define SPAM
  29. using System;
  30. using System.Collections.Generic;
  31. using System.Linq;
  32. using System.Reflection;
  33. using System.Runtime.InteropServices;
  34. using System.Threading;
  35. using System.IO;
  36. using System.Diagnostics;
  37. using log4net;
  38. using Nini.Config;
  39. using Mono.Addins;
  40. using OdeAPI;
  41. using OpenSim.Framework;
  42. using OpenSim.Region.Framework.Scenes;
  43. using OpenSim.Region.Framework.Interfaces;
  44. using OpenSim.Region.PhysicsModules.SharedBase;
  45. using OpenMetaverse;
  46. namespace OpenSim.Region.PhysicsModule.ubOde
  47. {
  48. // colision flags of things others can colide with
  49. // rays, sensors, probes removed since can't be colided with
  50. // The top space where things are placed provided further selection
  51. // ie physical are in active space nonphysical in static
  52. // this should be exclusive as possible
  53. [Flags]
  54. public enum CollisionCategories : uint
  55. {
  56. Disabled = 0,
  57. //by 'things' types
  58. Space = 0x01,
  59. Geom = 0x02, // aka prim/part
  60. Character = 0x04,
  61. Land = 0x08,
  62. Water = 0x010,
  63. // by state
  64. Phantom = 0x01000,
  65. VolumeDtc = 0x02000,
  66. Selected = 0x04000,
  67. NoShape = 0x08000,
  68. All = 0xffffffff
  69. }
  70. /// <summary>
  71. /// Material type for a primitive
  72. /// </summary>
  73. public enum Material : int
  74. {
  75. /// <summary></summary>
  76. Stone = 0,
  77. /// <summary></summary>
  78. Metal = 1,
  79. /// <summary></summary>
  80. Glass = 2,
  81. /// <summary></summary>
  82. Wood = 3,
  83. /// <summary></summary>
  84. Flesh = 4,
  85. /// <summary></summary>
  86. Plastic = 5,
  87. /// <summary></summary>
  88. Rubber = 6,
  89. light = 7 // compatibility with old viewers
  90. }
  91. public enum changes : int
  92. {
  93. Add = 0, // arg null. finishs the prim creation. should be used internally only ( to remove later ?)
  94. Remove,
  95. Link, // arg AuroraODEPrim new parent prim or null to delink. Makes the prim part of a object with prim parent as root
  96. // or removes from a object if arg is null
  97. DeLink,
  98. Position, // arg Vector3 new position in world coords. Changes prim position. Prim must know if it is root or child
  99. Orientation, // arg Quaternion new orientation in world coords. Changes prim position. Prim must know it it is root or child
  100. PosOffset, // not in use
  101. // arg Vector3 new position in local coords. Changes prim position in object
  102. OriOffset, // not in use
  103. // arg Vector3 new position in local coords. Changes prim position in object
  104. Velocity,
  105. TargetVelocity,
  106. AngVelocity,
  107. Acceleration,
  108. Force,
  109. Torque,
  110. Momentum,
  111. AddForce,
  112. AddAngForce,
  113. AngLock,
  114. Buoyancy,
  115. PIDTarget,
  116. PIDTau,
  117. PIDActive,
  118. PIDHoverHeight,
  119. PIDHoverType,
  120. PIDHoverTau,
  121. PIDHoverActive,
  122. Size,
  123. AvatarSize,
  124. Shape,
  125. PhysRepData,
  126. AddPhysRep,
  127. CollidesWater,
  128. VolumeDtc,
  129. Physical,
  130. Phantom,
  131. Selected,
  132. disabled,
  133. building,
  134. VehicleType,
  135. VehicleFloatParam,
  136. VehicleVectorParam,
  137. VehicleRotationParam,
  138. VehicleFlags,
  139. SetVehicle,
  140. SetInertia,
  141. Null //keep this last used do dim the methods array. does nothing but pulsing the prim
  142. }
  143. public struct ODEchangeitem
  144. {
  145. public PhysicsActor actor;
  146. public OdeCharacter character;
  147. public changes what;
  148. public Object arg;
  149. }
  150. public class ODEScene : PhysicsScene
  151. {
  152. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  153. public bool m_OSOdeLib = false;
  154. public Scene m_frameWorkScene = null;
  155. // private int threadid = 0;
  156. // const d.ContactFlags comumContactFlags = d.ContactFlags.SoftERP | d.ContactFlags.SoftCFM |d.ContactFlags.Approx1 | d.ContactFlags.Bounce;
  157. const d.ContactFlags comumContactFlags = d.ContactFlags.Bounce | d.ContactFlags.Approx1 | d.ContactFlags.Slip1 | d.ContactFlags.Slip2;
  158. const float comumContactERP = 0.75f;
  159. const float comumContactCFM = 0.0001f;
  160. const float comumContactSLIP = 0f;
  161. float frictionMovementMult = 0.8f;
  162. float TerrainBounce = 0.001f;
  163. float TerrainFriction = 0.3f;
  164. public float AvatarFriction = 0;// 0.9f * 0.5f;
  165. // this netx dimensions are only relevant for terrain partition (mega regions)
  166. // WorldExtents below has the simulation dimensions
  167. // they should be identical except on mega regions
  168. private uint m_regionWidth = Constants.RegionSize;
  169. private uint m_regionHeight = Constants.RegionSize;
  170. public float ODE_STEPSIZE = 0.020f;
  171. public float HalfOdeStep = 0.01f;
  172. public int odetimestepMS = 20; // rounded
  173. private float metersInSpace = 25.6f;
  174. private float m_timeDilation = 1.0f;
  175. private double m_lastframe;
  176. private double m_lastMeshExpire;
  177. public float gravityx = 0f;
  178. public float gravityy = 0f;
  179. public float gravityz = -9.8f;
  180. private float waterlevel = 0f;
  181. private int framecount = 0;
  182. private float avDensity = 80f;
  183. private float avMovementDivisorWalk = 1.3f;
  184. private float avMovementDivisorRun = 0.8f;
  185. private float minimumGroundFlightOffset = 3f;
  186. public float maximumMassObject = 10000.01f;
  187. public float geomDefaultDensity = 10.0f;
  188. public float maximumAngularVelocity = 12.0f; // default 12rad/s
  189. public float maxAngVelocitySQ = 144f; // squared value
  190. public float bodyPIDD = 35f;
  191. public float bodyPIDG = 25;
  192. public int bodyFramesAutoDisable = 5;
  193. private d.NearCallback nearCallback;
  194. private Dictionary<uint,OdePrim> _prims = new Dictionary<uint,OdePrim>();
  195. private HashSet<OdeCharacter> _characters = new HashSet<OdeCharacter>();
  196. private HashSet<OdePrim> _activeprims = new HashSet<OdePrim>();
  197. private HashSet<OdePrim> _activegroups = new HashSet<OdePrim>();
  198. public OpenSim.Framework.LocklessQueue<ODEchangeitem> ChangesQueue = new OpenSim.Framework.LocklessQueue<ODEchangeitem>();
  199. /// <summary>
  200. /// A list of actors that should receive collision events.
  201. /// </summary>
  202. private List<PhysicsActor> _collisionEventPrim = new List<PhysicsActor>();
  203. private List<PhysicsActor> _collisionEventPrimRemove = new List<PhysicsActor>();
  204. private HashSet<OdeCharacter> _badCharacter = new HashSet<OdeCharacter>();
  205. public Dictionary<IntPtr, PhysicsActor> actor_name_map = new Dictionary<IntPtr, PhysicsActor>();
  206. private float contactsurfacelayer = 0.002f;
  207. private int contactsPerCollision = 80;
  208. internal IntPtr ContactgeomsArray = IntPtr.Zero;
  209. private IntPtr GlobalContactsArray = IntPtr.Zero;
  210. private d.Contact SharedTmpcontact = new d.Contact();
  211. const int maxContactsbeforedeath = 6000;
  212. private volatile int m_global_contactcount = 0;
  213. private IntPtr contactgroup;
  214. public ContactData[] m_materialContactsData = new ContactData[8];
  215. private IntPtr TerrainGeom;
  216. private float[] TerrainHeightFieldHeight;
  217. private GCHandle TerrainHeightFieldHeightsHandler = new GCHandle();
  218. private int m_physicsiterations = 15;
  219. private const float m_SkipFramesAtms = 0.40f; // Drop frames gracefully at a 400 ms lag
  220. // private PhysicsActor PANull = new NullPhysicsActor();
  221. private float step_time = 0.0f;
  222. public IntPtr world;
  223. // split the spaces acording to contents type
  224. // ActiveSpace contains characters and active prims
  225. // StaticSpace contains land and other that is mostly static in enviroment
  226. // this can contain subspaces, like the grid in staticspace
  227. // as now space only contains this 2 top spaces
  228. public IntPtr TopSpace; // the global space
  229. public IntPtr ActiveSpace; // space for active prims
  230. public IntPtr CharsSpace; // space for active prims
  231. public IntPtr StaticSpace; // space for the static things around
  232. public IntPtr GroundSpace; // space for ground
  233. // some speedup variables
  234. private int spaceGridMaxX;
  235. private int spaceGridMaxY;
  236. private float spacesPerMeterX;
  237. private float spacesPerMeterY;
  238. // split static geometry collision into a grid as before
  239. private IntPtr[,] staticPrimspace;
  240. private IntPtr[] staticPrimspaceOffRegion;
  241. public Object OdeLock;
  242. public static Object SimulationLock;
  243. public IMesher mesher;
  244. public IConfigSource m_config;
  245. public bool physics_logging = false;
  246. public int physics_logging_interval = 0;
  247. public bool physics_logging_append_existing_logfile = false;
  248. public Vector2 WorldExtents = new Vector2((int)Constants.RegionSize, (int)Constants.RegionSize);
  249. private ODERayCastRequestManager m_rayCastManager;
  250. public ODEMeshWorker m_meshWorker;
  251. /* maybe needed if ode uses tls
  252. private void checkThread()
  253. {
  254. int th = Thread.CurrentThread.ManagedThreadId;
  255. if(th != threadid)
  256. {
  257. threadid = th;
  258. d.AllocateODEDataForThread(~0U);
  259. }
  260. }
  261. */
  262. IConfig physicsconfig = null;
  263. public ODEScene(Scene pscene, IConfigSource psourceconfig, string pname, string pversion, bool pOSOdeLib)
  264. {
  265. OdeLock = new Object();
  266. EngineType = pname;
  267. PhysicsSceneName = EngineType + "/" + pscene.RegionInfo.RegionName;
  268. EngineName = pname + " " + pversion;
  269. m_config = psourceconfig;
  270. m_OSOdeLib = pOSOdeLib;
  271. // m_OSOdeLib = false; //debug
  272. m_frameWorkScene = pscene;
  273. m_frameWorkScene.RegisterModuleInterface<PhysicsScene>(this);
  274. Initialization();
  275. base.Initialise(m_frameWorkScene.PhysicsRequestAsset,
  276. (m_frameWorkScene.Heightmap != null ? m_frameWorkScene.Heightmap.GetFloatsSerialised() : new float[m_frameWorkScene.RegionInfo.RegionSizeX * m_frameWorkScene.RegionInfo.RegionSizeY]),
  277. (float)m_frameWorkScene.RegionInfo.RegionSettings.WaterHeight);
  278. }
  279. public void RegionLoaded()
  280. {
  281. mesher = m_frameWorkScene.RequestModuleInterface<IMesher>();
  282. if (mesher == null)
  283. {
  284. m_log.ErrorFormat("[ubOde] No mesher. module disabled");
  285. return;
  286. }
  287. m_meshWorker = new ODEMeshWorker(this, m_log, mesher, physicsconfig);
  288. m_frameWorkScene.PhysicsEnabled = true;
  289. }
  290. /// <summary>
  291. /// Initiailizes the scene
  292. /// Sets many properties that ODE requires to be stable
  293. /// These settings need to be tweaked 'exactly' right or weird stuff happens.
  294. /// </summary>
  295. private void Initialization()
  296. {
  297. d.AllocateODEDataForThread(~0U);
  298. SimulationLock = new Object();
  299. nearCallback = near;
  300. m_rayCastManager = new ODERayCastRequestManager(this);
  301. WorldExtents.X = m_frameWorkScene.RegionInfo.RegionSizeX;
  302. m_regionWidth = (uint)WorldExtents.X;
  303. WorldExtents.Y = m_frameWorkScene.RegionInfo.RegionSizeY;
  304. m_regionHeight = (uint)WorldExtents.Y;
  305. lock (OdeLock)
  306. {
  307. // Create the world and the first space
  308. try
  309. {
  310. world = d.WorldCreate();
  311. TopSpace = d.HashSpaceCreate(IntPtr.Zero);
  312. // now the major subspaces
  313. ActiveSpace = d.HashSpaceCreate(TopSpace);
  314. CharsSpace = d.HashSpaceCreate(TopSpace);
  315. StaticSpace = d.HashSpaceCreate(TopSpace);
  316. GroundSpace = d.HashSpaceCreate(TopSpace);
  317. }
  318. catch
  319. {
  320. // i must RtC#FM
  321. // i did!
  322. }
  323. d.HashSpaceSetLevels(TopSpace, -5, 12);
  324. d.HashSpaceSetLevels(ActiveSpace, -5, 10);
  325. d.HashSpaceSetLevels(CharsSpace, -4, 3);
  326. d.HashSpaceSetLevels(StaticSpace, -5, 12);
  327. d.HashSpaceSetLevels(GroundSpace, 0, 8);
  328. // demote to second level
  329. d.SpaceSetSublevel(ActiveSpace, 1);
  330. d.SpaceSetSublevel(CharsSpace, 1);
  331. d.SpaceSetSublevel(StaticSpace, 1);
  332. d.SpaceSetSublevel(GroundSpace, 1);
  333. d.GeomSetCategoryBits(ActiveSpace, (uint)(CollisionCategories.Space |
  334. CollisionCategories.Geom |
  335. CollisionCategories.Character |
  336. CollisionCategories.Phantom |
  337. CollisionCategories.VolumeDtc
  338. ));
  339. d.GeomSetCollideBits(ActiveSpace, (uint)(CollisionCategories.Space |
  340. CollisionCategories.Geom |
  341. CollisionCategories.Character |
  342. CollisionCategories.Phantom |
  343. CollisionCategories.VolumeDtc
  344. ));
  345. d.GeomSetCategoryBits(CharsSpace, (uint)(CollisionCategories.Space |
  346. CollisionCategories.Geom |
  347. CollisionCategories.Character |
  348. CollisionCategories.Phantom |
  349. CollisionCategories.VolumeDtc
  350. ));
  351. d.GeomSetCollideBits(CharsSpace, 0);
  352. d.GeomSetCategoryBits(StaticSpace, (uint)(CollisionCategories.Space |
  353. CollisionCategories.Geom |
  354. // CollisionCategories.Land |
  355. // CollisionCategories.Water |
  356. CollisionCategories.Phantom |
  357. CollisionCategories.VolumeDtc
  358. ));
  359. d.GeomSetCollideBits(StaticSpace, 0);
  360. d.GeomSetCategoryBits(GroundSpace, (uint)(CollisionCategories.Land));
  361. d.GeomSetCollideBits(GroundSpace, 0);
  362. contactgroup = d.JointGroupCreate(maxContactsbeforedeath + 1);
  363. //contactgroup
  364. d.WorldSetAutoDisableFlag(world, false);
  365. }
  366. // checkThread();
  367. // Defaults
  368. int contactsPerCollision = 80;
  369. physicsconfig = null;
  370. if (m_config != null)
  371. {
  372. physicsconfig = m_config.Configs["ODEPhysicsSettings"];
  373. if (physicsconfig != null)
  374. {
  375. gravityx = physicsconfig.GetFloat("world_gravityx", gravityx);
  376. gravityy = physicsconfig.GetFloat("world_gravityy", gravityy);
  377. gravityz = physicsconfig.GetFloat("world_gravityz", gravityz);
  378. metersInSpace = physicsconfig.GetFloat("meters_in_small_space", metersInSpace);
  379. // contactsurfacelayer = physicsconfig.GetFloat("world_contact_surface_layer", contactsurfacelayer);
  380. ODE_STEPSIZE = physicsconfig.GetFloat("world_stepsize", ODE_STEPSIZE);
  381. avDensity = physicsconfig.GetFloat("av_density", avDensity);
  382. avMovementDivisorWalk = physicsconfig.GetFloat("av_movement_divisor_walk", avMovementDivisorWalk);
  383. avMovementDivisorRun = physicsconfig.GetFloat("av_movement_divisor_run", avMovementDivisorRun);
  384. contactsPerCollision = physicsconfig.GetInt("contacts_per_collision", contactsPerCollision);
  385. geomDefaultDensity = physicsconfig.GetFloat("geometry_default_density", geomDefaultDensity);
  386. // bodyFramesAutoDisable = physicsconfig.GetInt("body_frames_auto_disable", bodyFramesAutoDisable);
  387. physics_logging = physicsconfig.GetBoolean("physics_logging", false);
  388. physics_logging_interval = physicsconfig.GetInt("physics_logging_interval", 0);
  389. physics_logging_append_existing_logfile = physicsconfig.GetBoolean("physics_logging_append_existing_logfile", false);
  390. minimumGroundFlightOffset = physicsconfig.GetFloat("minimum_ground_flight_offset", minimumGroundFlightOffset);
  391. maximumMassObject = physicsconfig.GetFloat("maximum_mass_object", maximumMassObject);
  392. avDensity *= 3f / 80f; // scale other engines density option to this
  393. }
  394. }
  395. float heartbeat = 1/m_frameWorkScene.FrameTime;
  396. maximumAngularVelocity = 0.49f * heartbeat *(float)Math.PI;
  397. maxAngVelocitySQ = maximumAngularVelocity * maximumAngularVelocity;
  398. d.WorldSetCFM(world, comumContactCFM);
  399. d.WorldSetERP(world, comumContactERP);
  400. d.WorldSetGravity(world, gravityx, gravityy, gravityz);
  401. d.WorldSetLinearDamping(world, 0.001f);
  402. d.WorldSetAngularDamping(world, 0.002f);
  403. d.WorldSetAngularDampingThreshold(world, 0f);
  404. d.WorldSetLinearDampingThreshold(world, 0f);
  405. d.WorldSetMaxAngularSpeed(world, maximumAngularVelocity);
  406. d.WorldSetQuickStepNumIterations(world, m_physicsiterations);
  407. d.WorldSetContactSurfaceLayer(world, contactsurfacelayer);
  408. d.WorldSetContactMaxCorrectingVel(world, 60.0f);
  409. HalfOdeStep = ODE_STEPSIZE * 0.5f;
  410. odetimestepMS = (int)(1000.0f * ODE_STEPSIZE + 0.5f);
  411. ContactgeomsArray = Marshal.AllocHGlobal(contactsPerCollision * d.ContactGeom.unmanagedSizeOf);
  412. GlobalContactsArray = Marshal.AllocHGlobal((maxContactsbeforedeath + 100) * d.Contact.unmanagedSizeOf);
  413. SharedTmpcontact.geom.g1 = IntPtr.Zero;
  414. SharedTmpcontact.geom.g2 = IntPtr.Zero;
  415. SharedTmpcontact.geom.side1 = -1;
  416. SharedTmpcontact.geom.side2 = -1;
  417. SharedTmpcontact.surface.mode = comumContactFlags;
  418. SharedTmpcontact.surface.mu = 0;
  419. SharedTmpcontact.surface.bounce = 0;
  420. SharedTmpcontact.surface.bounce_vel = 1.5f;
  421. SharedTmpcontact.surface.soft_cfm = comumContactCFM;
  422. SharedTmpcontact.surface.soft_erp = comumContactERP;
  423. SharedTmpcontact.surface.slip1 = comumContactSLIP;
  424. SharedTmpcontact.surface.slip2 = comumContactSLIP;
  425. m_materialContactsData[(int)Material.Stone].mu = 0.8f;
  426. m_materialContactsData[(int)Material.Stone].bounce = 0.4f;
  427. m_materialContactsData[(int)Material.Metal].mu = 0.3f;
  428. m_materialContactsData[(int)Material.Metal].bounce = 0.4f;
  429. m_materialContactsData[(int)Material.Glass].mu = 0.2f;
  430. m_materialContactsData[(int)Material.Glass].bounce = 0.7f;
  431. m_materialContactsData[(int)Material.Wood].mu = 0.6f;
  432. m_materialContactsData[(int)Material.Wood].bounce = 0.5f;
  433. m_materialContactsData[(int)Material.Flesh].mu = 0.9f;
  434. m_materialContactsData[(int)Material.Flesh].bounce = 0.3f;
  435. m_materialContactsData[(int)Material.Plastic].mu = 0.4f;
  436. m_materialContactsData[(int)Material.Plastic].bounce = 0.7f;
  437. m_materialContactsData[(int)Material.Rubber].mu = 0.9f;
  438. m_materialContactsData[(int)Material.Rubber].bounce = 0.95f;
  439. m_materialContactsData[(int)Material.light].mu = 0.0f;
  440. m_materialContactsData[(int)Material.light].bounce = 0.0f;
  441. spacesPerMeterX = 1.0f / metersInSpace;
  442. spacesPerMeterY = spacesPerMeterX;
  443. spaceGridMaxX = (int)(WorldExtents.X * spacesPerMeterX);
  444. spaceGridMaxY = (int)(WorldExtents.Y * spacesPerMeterY);
  445. if (spaceGridMaxX > 24)
  446. {
  447. spaceGridMaxX = 24;
  448. spacesPerMeterX = spaceGridMaxX / WorldExtents.X;
  449. }
  450. if (spaceGridMaxY > 24)
  451. {
  452. spaceGridMaxY = 24;
  453. spacesPerMeterY = spaceGridMaxY / WorldExtents.Y;
  454. }
  455. staticPrimspace = new IntPtr[spaceGridMaxX, spaceGridMaxY];
  456. // create all spaces now
  457. int i, j;
  458. IntPtr newspace;
  459. for (i = 0; i < spaceGridMaxX; i++)
  460. for (j = 0; j < spaceGridMaxY; j++)
  461. {
  462. newspace = d.HashSpaceCreate(StaticSpace);
  463. d.GeomSetCategoryBits(newspace, (int)CollisionCategories.Space);
  464. waitForSpaceUnlock(newspace);
  465. d.SpaceSetSublevel(newspace, 2);
  466. d.HashSpaceSetLevels(newspace, -2, 8);
  467. d.GeomSetCategoryBits(newspace, (uint)(CollisionCategories.Space |
  468. CollisionCategories.Geom |
  469. CollisionCategories.Land |
  470. CollisionCategories.Water |
  471. CollisionCategories.Phantom |
  472. CollisionCategories.VolumeDtc
  473. ));
  474. d.GeomSetCollideBits(newspace, 0);
  475. staticPrimspace[i, j] = newspace;
  476. }
  477. // let this now be index limit
  478. spaceGridMaxX--;
  479. spaceGridMaxY--;
  480. // create 4 off world spaces (x<0,x>max,y<0,y>max)
  481. staticPrimspaceOffRegion = new IntPtr[4];
  482. for (i = 0; i < 4; i++)
  483. {
  484. newspace = d.HashSpaceCreate(StaticSpace);
  485. d.GeomSetCategoryBits(newspace, (int)CollisionCategories.Space);
  486. waitForSpaceUnlock(newspace);
  487. d.SpaceSetSublevel(newspace, 2);
  488. d.HashSpaceSetLevels(newspace, -2, 8);
  489. d.GeomSetCategoryBits(newspace, (uint)(CollisionCategories.Space |
  490. CollisionCategories.Geom |
  491. CollisionCategories.Land |
  492. CollisionCategories.Water |
  493. CollisionCategories.Phantom |
  494. CollisionCategories.VolumeDtc
  495. ));
  496. d.GeomSetCollideBits(newspace, 0);
  497. staticPrimspaceOffRegion[i] = newspace;
  498. }
  499. m_lastframe = Util.GetTimeStamp();
  500. m_lastMeshExpire = m_lastframe;
  501. step_time = -1;
  502. }
  503. internal void waitForSpaceUnlock(IntPtr space)
  504. {
  505. //if (space != IntPtr.Zero)
  506. //while (d.SpaceLockQuery(space)) { } // Wait and do nothing
  507. }
  508. #region Collision Detection
  509. // sets a global contact for a joint for contactgeom , and base contact description)
  510. private IntPtr CreateContacJoint(ref d.ContactGeom contactGeom,bool smooth)
  511. {
  512. if (m_global_contactcount >= maxContactsbeforedeath)
  513. return IntPtr.Zero;
  514. m_global_contactcount++;
  515. if(smooth)
  516. SharedTmpcontact.geom.depth = contactGeom.depth * 0.05f;
  517. else
  518. SharedTmpcontact.geom.depth = contactGeom.depth;
  519. SharedTmpcontact.geom.pos = contactGeom.pos;
  520. SharedTmpcontact.geom.normal = contactGeom.normal;
  521. IntPtr contact = new IntPtr(GlobalContactsArray.ToInt64() + (Int64)(m_global_contactcount * d.Contact.unmanagedSizeOf));
  522. Marshal.StructureToPtr(SharedTmpcontact, contact, true);
  523. return d.JointCreateContactPtr(world, contactgroup, contact);
  524. }
  525. private bool GetCurContactGeom(int index, ref d.ContactGeom newcontactgeom)
  526. {
  527. if (ContactgeomsArray == IntPtr.Zero || index >= contactsPerCollision)
  528. return false;
  529. IntPtr contactptr = new IntPtr(ContactgeomsArray.ToInt64() + (Int64)(index * d.ContactGeom.unmanagedSizeOf));
  530. newcontactgeom = (d.ContactGeom)Marshal.PtrToStructure(contactptr, typeof(d.ContactGeom));
  531. return true;
  532. }
  533. /// <summary>
  534. /// This is our near callback. A geometry is near a body
  535. /// </summary>
  536. /// <param name="space">The space that contains the geoms. Remember, spaces are also geoms</param>
  537. /// <param name="g1">a geometry or space</param>
  538. /// <param name="g2">another geometry or space</param>
  539. ///
  540. private void near(IntPtr space, IntPtr g1, IntPtr g2)
  541. {
  542. // no lock here! It's invoked from within Simulate(), which is thread-locked
  543. if (m_global_contactcount >= maxContactsbeforedeath)
  544. return;
  545. // Test if we're colliding a geom with a space.
  546. // If so we have to drill down into the space recursively
  547. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  548. return;
  549. if (d.GeomIsSpace(g1) || d.GeomIsSpace(g2))
  550. {
  551. // We'll be calling near recursivly if one
  552. // of them is a space to find all of the
  553. // contact points in the space
  554. try
  555. {
  556. d.SpaceCollide2(g1, g2, IntPtr.Zero, nearCallback);
  557. }
  558. catch (AccessViolationException)
  559. {
  560. m_log.Warn("[PHYSICS]: Unable to collide test a space");
  561. return;
  562. }
  563. //here one should check collisions of geoms inside a space
  564. // but on each space we only should have geoms that not colide amoung each other
  565. // so we don't dig inside spaces
  566. return;
  567. }
  568. // get geom bodies to check if we already a joint contact
  569. // guess this shouldn't happen now
  570. IntPtr b1 = d.GeomGetBody(g1);
  571. IntPtr b2 = d.GeomGetBody(g2);
  572. // d.GeomClassID id = d.GeomGetClass(g1);
  573. // Figure out how many contact points we have
  574. int count = 0;
  575. try
  576. {
  577. // Colliding Geom To Geom
  578. // This portion of the function 'was' blatantly ripped off from BoxStack.cs
  579. if (g1 == g2)
  580. return; // Can't collide with yourself
  581. // if (b1 != IntPtr.Zero && b2 != IntPtr.Zero && d.AreConnectedExcluding(b1, b2, d.JointType.Contact))
  582. // return;
  583. /*
  584. // debug
  585. PhysicsActor dp2;
  586. if (d.GeomGetClass(g1) == d.GeomClassID.HeightfieldClass)
  587. {
  588. d.AABB aabb;
  589. d.GeomGetAABB(g2, out aabb);
  590. float x = aabb.MaxX - aabb.MinX;
  591. float y = aabb.MaxY - aabb.MinY;
  592. float z = aabb.MaxZ - aabb.MinZ;
  593. if (x > 60.0f || y > 60.0f || z > 60.0f)
  594. {
  595. if (!actor_name_map.TryGetValue(g2, out dp2))
  596. m_log.WarnFormat("[PHYSICS]: failed actor mapping for geom 2");
  597. else
  598. m_log.WarnFormat("[PHYSICS]: land versus large prim geo {0},size {1}, AABBsize <{2},{3},{4}>, at {5} ori {6},({7})",
  599. dp2.Name, dp2.Size, x, y, z,
  600. dp2.Position.ToString(),
  601. dp2.Orientation.ToString(),
  602. dp2.Orientation.Length());
  603. return;
  604. }
  605. }
  606. //
  607. */
  608. if (d.GeomGetCategoryBits(g1) == (uint)CollisionCategories.VolumeDtc ||
  609. d.GeomGetCategoryBits(g2) == (uint)CollisionCategories.VolumeDtc)
  610. {
  611. int cflags;
  612. unchecked
  613. {
  614. cflags = (int)(1 | d.CONTACTS_UNIMPORTANT);
  615. }
  616. count = d.CollidePtr(g1, g2, cflags, ContactgeomsArray, d.ContactGeom.unmanagedSizeOf);
  617. }
  618. else
  619. count = d.CollidePtr(g1, g2, (contactsPerCollision & 0xffff), ContactgeomsArray, d.ContactGeom.unmanagedSizeOf);
  620. }
  621. catch (SEHException)
  622. {
  623. 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.");
  624. // ode.drelease(world);
  625. base.TriggerPhysicsBasedRestart();
  626. }
  627. catch (Exception e)
  628. {
  629. m_log.WarnFormat("[PHYSICS]: Unable to collide test an object: {0}", e.Message);
  630. return;
  631. }
  632. // contacts done
  633. if (count == 0)
  634. return;
  635. // try get physical actors
  636. PhysicsActor p1;
  637. PhysicsActor p2;
  638. if (!actor_name_map.TryGetValue(g1, out p1))
  639. {
  640. m_log.WarnFormat("[PHYSICS]: failed actor mapping for geom 1");
  641. return;
  642. }
  643. if (!actor_name_map.TryGetValue(g2, out p2))
  644. {
  645. m_log.WarnFormat("[PHYSICS]: failed actor mapping for geom 2");
  646. return;
  647. }
  648. // get first contact
  649. d.ContactGeom curContact = new d.ContactGeom();
  650. if (!GetCurContactGeom(0, ref curContact))
  651. return;
  652. ContactPoint maxDepthContact = new ContactPoint();
  653. // do volume detection case
  654. if ((p1.IsVolumeDtc || p2.IsVolumeDtc))
  655. {
  656. maxDepthContact = new ContactPoint(
  657. new Vector3(curContact.pos.X, curContact.pos.Y, curContact.pos.Z),
  658. new Vector3(curContact.normal.X, curContact.normal.Y, curContact.normal.Z),
  659. curContact.depth, false
  660. );
  661. collision_accounting_events(p1, p2, maxDepthContact);
  662. return;
  663. }
  664. // big messy collision analises
  665. float mu = 0;
  666. float bounce = 0;
  667. // bool IgnoreNegSides = false;
  668. ContactData contactdata1 = new ContactData(0, 0, false);
  669. ContactData contactdata2 = new ContactData(0, 0, false);
  670. bool dop1ava = false;
  671. bool dop2ava = false;
  672. bool ignore = false;
  673. bool smoothMesh = false;
  674. switch (p1.PhysicsActorType)
  675. {
  676. case (int)ActorTypes.Agent:
  677. {
  678. dop1ava = true;
  679. switch (p2.PhysicsActorType)
  680. {
  681. case (int)ActorTypes.Agent:
  682. case (int)ActorTypes.Prim:
  683. break;
  684. default:
  685. ignore = true; // avatar to terrain and water ignored
  686. break;
  687. }
  688. break;
  689. }
  690. case (int)ActorTypes.Prim:
  691. {
  692. switch (p2.PhysicsActorType)
  693. {
  694. case (int)ActorTypes.Agent:
  695. dop2ava = true;
  696. break;
  697. case (int)ActorTypes.Prim:
  698. Vector3 relV = p1.rootVelocity - p2.rootVelocity;
  699. float relVlenSQ = relV.LengthSquared();
  700. if (relVlenSQ > 0.0001f)
  701. {
  702. p1.CollidingObj = true;
  703. p2.CollidingObj = true;
  704. }
  705. p1.getContactData(ref contactdata1);
  706. p2.getContactData(ref contactdata2);
  707. bounce = contactdata1.bounce * contactdata2.bounce;
  708. mu = (float)Math.Sqrt(contactdata1.mu * contactdata2.mu);
  709. if (relVlenSQ > 0.01f)
  710. mu *= frictionMovementMult;
  711. if(d.GeomGetClass(g2) == d.GeomClassID.TriMeshClass &&
  712. d.GeomGetClass(g1) == d.GeomClassID.TriMeshClass)
  713. smoothMesh = true;
  714. break;
  715. case (int)ActorTypes.Ground:
  716. p1.getContactData(ref contactdata1);
  717. bounce = contactdata1.bounce * TerrainBounce;
  718. mu = (float)Math.Sqrt(contactdata1.mu * TerrainFriction);
  719. Vector3 v1 = p1.rootVelocity;
  720. if (Math.Abs(v1.X) > 0.1f || Math.Abs(v1.Y) > 0.1f)
  721. mu *= frictionMovementMult;
  722. p1.CollidingGround = true;
  723. if(d.GeomGetClass(g1) == d.GeomClassID.TriMeshClass)
  724. smoothMesh = true;
  725. break;
  726. case (int)ActorTypes.Water:
  727. default:
  728. ignore = true;
  729. break;
  730. }
  731. }
  732. break;
  733. case (int)ActorTypes.Ground:
  734. if (p2.PhysicsActorType == (int)ActorTypes.Prim)
  735. {
  736. p2.CollidingGround = true;
  737. p2.getContactData(ref contactdata2);
  738. bounce = contactdata2.bounce * TerrainBounce;
  739. mu = (float)Math.Sqrt(contactdata2.mu * TerrainFriction);
  740. // if (curContact.side1 > 0) // should be 2 ?
  741. // IgnoreNegSides = true;
  742. Vector3 v2 = p2.rootVelocity;
  743. if (Math.Abs(v2.X) > 0.1f || Math.Abs(v2.Y) > 0.1f)
  744. mu *= frictionMovementMult;
  745. if(d.GeomGetClass(g2) == d.GeomClassID.TriMeshClass)
  746. smoothMesh = true;
  747. }
  748. else
  749. ignore = true;
  750. break;
  751. case (int)ActorTypes.Water:
  752. default:
  753. break;
  754. }
  755. if (ignore)
  756. return;
  757. IntPtr Joint;
  758. bool FeetCollision = false;
  759. int ncontacts = 0;
  760. int i = 0;
  761. maxDepthContact = new ContactPoint();
  762. maxDepthContact.PenetrationDepth = float.MinValue;
  763. ContactPoint minDepthContact = new ContactPoint();
  764. minDepthContact.PenetrationDepth = float.MaxValue;
  765. SharedTmpcontact.geom.depth = 0;
  766. SharedTmpcontact.surface.mu = mu;
  767. SharedTmpcontact.surface.bounce = bounce;
  768. d.ContactGeom altContact = new d.ContactGeom();
  769. bool useAltcontact;
  770. bool noskip;
  771. if(dop1ava || dop2ava)
  772. smoothMesh = false;
  773. while (true)
  774. {
  775. noskip = true;
  776. useAltcontact = false;
  777. if (dop1ava)
  778. {
  779. if ((((OdeCharacter)p1).Collide(g1, g2, false, ref curContact, ref altContact , ref useAltcontact, ref FeetCollision)))
  780. {
  781. if (p2.PhysicsActorType == (int)ActorTypes.Agent)
  782. {
  783. p1.CollidingObj = true;
  784. p2.CollidingObj = true;
  785. }
  786. else if (p2.rootVelocity.LengthSquared() > 0.0f)
  787. p2.CollidingObj = true;
  788. }
  789. else
  790. noskip = false;
  791. }
  792. else if (dop2ava)
  793. {
  794. if ((((OdeCharacter)p2).Collide(g2, g1, true, ref curContact, ref altContact , ref useAltcontact, ref FeetCollision)))
  795. {
  796. if (p1.PhysicsActorType == (int)ActorTypes.Agent)
  797. {
  798. p1.CollidingObj = true;
  799. p2.CollidingObj = true;
  800. }
  801. else if (p1.rootVelocity.LengthSquared() > 0.0f)
  802. p1.CollidingObj = true;
  803. }
  804. else
  805. noskip = false;
  806. }
  807. if (noskip)
  808. {
  809. if(useAltcontact)
  810. Joint = CreateContacJoint(ref altContact,smoothMesh);
  811. else
  812. Joint = CreateContacJoint(ref curContact,smoothMesh);
  813. if (Joint == IntPtr.Zero)
  814. break;
  815. d.JointAttach(Joint, b1, b2);
  816. ncontacts++;
  817. if (curContact.depth > maxDepthContact.PenetrationDepth)
  818. {
  819. maxDepthContact.Position.X = curContact.pos.X;
  820. maxDepthContact.Position.Y = curContact.pos.Y;
  821. maxDepthContact.Position.Z = curContact.pos.Z;
  822. maxDepthContact.PenetrationDepth = curContact.depth;
  823. maxDepthContact.CharacterFeet = FeetCollision;
  824. }
  825. if (curContact.depth < minDepthContact.PenetrationDepth)
  826. {
  827. minDepthContact.PenetrationDepth = curContact.depth;
  828. minDepthContact.SurfaceNormal.X = curContact.normal.X;
  829. minDepthContact.SurfaceNormal.Y = curContact.normal.Y;
  830. minDepthContact.SurfaceNormal.Z = curContact.normal.Z;
  831. }
  832. }
  833. if (++i >= count)
  834. break;
  835. if (!GetCurContactGeom(i, ref curContact))
  836. break;
  837. }
  838. if (ncontacts > 0)
  839. {
  840. maxDepthContact.SurfaceNormal.X = minDepthContact.SurfaceNormal.X;
  841. maxDepthContact.SurfaceNormal.Y = minDepthContact.SurfaceNormal.Y;
  842. maxDepthContact.SurfaceNormal.Z = minDepthContact.SurfaceNormal.Z;
  843. collision_accounting_events(p1, p2, maxDepthContact);
  844. }
  845. }
  846. private void collision_accounting_events(PhysicsActor p1, PhysicsActor p2, ContactPoint contact)
  847. {
  848. uint obj2LocalID = 0;
  849. // update actors collision score
  850. if (p1.CollisionScore < float.MaxValue)
  851. p1.CollisionScore += 1.0f;
  852. if (p2.CollisionScore < float.MaxValue)
  853. p2.CollisionScore += 1.0f;
  854. bool p1events = p1.SubscribedEvents();
  855. bool p2events = p2.SubscribedEvents();
  856. if (p1.IsVolumeDtc)
  857. p2events = false;
  858. if (p2.IsVolumeDtc)
  859. p1events = false;
  860. if (!p2events && !p1events)
  861. return;
  862. Vector3 vel = Vector3.Zero;
  863. if (p2 != null && p2.IsPhysical)
  864. vel = p2.rootVelocity;
  865. if (p1 != null && p1.IsPhysical)
  866. vel -= p1.rootVelocity;
  867. contact.RelativeSpeed = Vector3.Dot(vel, contact.SurfaceNormal);
  868. switch ((ActorTypes)p1.PhysicsActorType)
  869. {
  870. case ActorTypes.Agent:
  871. case ActorTypes.Prim:
  872. {
  873. switch ((ActorTypes)p2.PhysicsActorType)
  874. {
  875. case ActorTypes.Agent:
  876. case ActorTypes.Prim:
  877. if (p2events)
  878. {
  879. //AddCollisionEventReporting(p2);
  880. p2.AddCollisionEvent(p1.ParentActor.LocalID, contact);
  881. }
  882. else if(p1.IsVolumeDtc)
  883. p2.AddVDTCCollisionEvent(p1.ParentActor.LocalID, contact);
  884. obj2LocalID = p2.ParentActor.LocalID;
  885. break;
  886. case ActorTypes.Ground:
  887. case ActorTypes.Unknown:
  888. default:
  889. obj2LocalID = 0;
  890. break;
  891. }
  892. if (p1events)
  893. {
  894. contact.SurfaceNormal = -contact.SurfaceNormal;
  895. contact.RelativeSpeed = -contact.RelativeSpeed;
  896. //AddCollisionEventReporting(p1);
  897. p1.AddCollisionEvent(obj2LocalID, contact);
  898. }
  899. else if(p2.IsVolumeDtc)
  900. {
  901. contact.SurfaceNormal = -contact.SurfaceNormal;
  902. contact.RelativeSpeed = -contact.RelativeSpeed;
  903. //AddCollisionEventReporting(p1);
  904. p1.AddVDTCCollisionEvent(obj2LocalID, contact);
  905. }
  906. break;
  907. }
  908. case ActorTypes.Ground:
  909. case ActorTypes.Unknown:
  910. default:
  911. {
  912. if (p2events && !p2.IsVolumeDtc)
  913. {
  914. //AddCollisionEventReporting(p2);
  915. p2.AddCollisionEvent(0, contact);
  916. }
  917. break;
  918. }
  919. }
  920. }
  921. /// <summary>
  922. /// This is our collision testing routine in ODE
  923. /// </summary>
  924. /// <param name="timeStep"></param>
  925. private void collision_optimized()
  926. {
  927. lock (_characters)
  928. {
  929. try
  930. {
  931. foreach (OdeCharacter chr in _characters)
  932. {
  933. if (chr == null)
  934. continue;
  935. chr.IsColliding = false;
  936. // chr.CollidingGround = false; not done here
  937. chr.CollidingObj = false;
  938. if(chr.Body == IntPtr.Zero || chr.collider == IntPtr.Zero )
  939. continue;
  940. // do colisions with static space
  941. d.SpaceCollide2(chr.collider, StaticSpace, IntPtr.Zero, nearCallback);
  942. // no coll with gnd
  943. }
  944. // chars with chars
  945. d.SpaceCollide(CharsSpace, IntPtr.Zero, nearCallback);
  946. }
  947. catch (AccessViolationException)
  948. {
  949. m_log.Warn("[PHYSICS]: Unable to collide Character to static space");
  950. }
  951. }
  952. lock (_activeprims)
  953. {
  954. foreach (OdePrim aprim in _activeprims)
  955. {
  956. aprim.CollisionScore = 0;
  957. aprim.IsColliding = false;
  958. if(!aprim.m_outbounds && d.BodyIsEnabled(aprim.Body))
  959. aprim.clearSleeperCollisions();
  960. }
  961. }
  962. lock (_activegroups)
  963. {
  964. try
  965. {
  966. foreach (OdePrim aprim in _activegroups)
  967. {
  968. if(!aprim.m_outbounds && d.BodyIsEnabled(aprim.Body) &&
  969. aprim.collide_geom != IntPtr.Zero)
  970. {
  971. d.SpaceCollide2(StaticSpace, aprim.collide_geom, IntPtr.Zero, nearCallback);
  972. d.SpaceCollide2(GroundSpace, aprim.collide_geom, IntPtr.Zero, nearCallback);
  973. }
  974. }
  975. }
  976. catch (Exception e)
  977. {
  978. m_log.Warn("[PHYSICS]: Unable to collide Active to Static: " + e.Message);
  979. }
  980. }
  981. // colide active amoung them
  982. try
  983. {
  984. d.SpaceCollide(ActiveSpace, IntPtr.Zero, nearCallback);
  985. }
  986. catch (Exception e)
  987. {
  988. m_log.Warn("[PHYSICS]: Unable to collide in Active: " + e.Message);
  989. }
  990. // and with chars
  991. try
  992. {
  993. d.SpaceCollide2(CharsSpace,ActiveSpace, IntPtr.Zero, nearCallback);
  994. }
  995. catch (Exception e)
  996. {
  997. m_log.Warn("[PHYSICS]: Unable to collide Active to Character: " + e.Message);
  998. }
  999. }
  1000. #endregion
  1001. /// <summary>
  1002. /// Add actor to the list that should receive collision events in the simulate loop.
  1003. /// </summary>
  1004. /// <param name="obj"></param>
  1005. public void AddCollisionEventReporting(PhysicsActor obj)
  1006. {
  1007. if (!_collisionEventPrim.Contains(obj))
  1008. _collisionEventPrim.Add(obj);
  1009. }
  1010. /// <summary>
  1011. /// Remove actor from the list that should receive collision events in the simulate loop.
  1012. /// </summary>
  1013. /// <param name="obj"></param>
  1014. public void RemoveCollisionEventReporting(PhysicsActor obj)
  1015. {
  1016. lock(_collisionEventPrimRemove)
  1017. {
  1018. if (_collisionEventPrim.Contains(obj) && !_collisionEventPrimRemove.Contains(obj))
  1019. _collisionEventPrimRemove.Add(obj);
  1020. }
  1021. }
  1022. public override float TimeDilation
  1023. {
  1024. get { return m_timeDilation; }
  1025. }
  1026. public override bool SupportsNINJAJoints
  1027. {
  1028. get { return false; }
  1029. }
  1030. #region Add/Remove Entities
  1031. public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 velocity, Vector3 size, bool isFlying)
  1032. {
  1033. return null;
  1034. }
  1035. public override PhysicsActor AddAvatar(uint localID, string avName, Vector3 position, Vector3 size, float feetOffset, bool isFlying)
  1036. {
  1037. OdeCharacter newAv = new OdeCharacter(localID, avName, this, position,
  1038. size, feetOffset, avDensity, avMovementDivisorWalk, avMovementDivisorRun);
  1039. newAv.Flying = isFlying;
  1040. newAv.MinimumGroundFlightOffset = minimumGroundFlightOffset;
  1041. return newAv;
  1042. }
  1043. public void AddCharacter(OdeCharacter chr)
  1044. {
  1045. lock (_characters)
  1046. {
  1047. if (!_characters.Contains(chr))
  1048. {
  1049. _characters.Add(chr);
  1050. if (chr.bad)
  1051. m_log.DebugFormat("[PHYSICS] Added BAD actor {0} to characters list", chr.m_uuid);
  1052. }
  1053. }
  1054. }
  1055. public void RemoveCharacter(OdeCharacter chr)
  1056. {
  1057. lock (_characters)
  1058. {
  1059. if (_characters.Contains(chr))
  1060. {
  1061. _characters.Remove(chr);
  1062. }
  1063. }
  1064. }
  1065. public void BadCharacter(OdeCharacter chr)
  1066. {
  1067. lock (_badCharacter)
  1068. {
  1069. if (!_badCharacter.Contains(chr))
  1070. _badCharacter.Add(chr);
  1071. }
  1072. }
  1073. public override void RemoveAvatar(PhysicsActor actor)
  1074. {
  1075. //m_log.Debug("[PHYSICS]:ODELOCK");
  1076. lock (OdeLock)
  1077. {
  1078. d.AllocateODEDataForThread(0);
  1079. ((OdeCharacter) actor).Destroy();
  1080. }
  1081. }
  1082. public void addActivePrim(OdePrim activatePrim)
  1083. {
  1084. // adds active prim..
  1085. lock (_activeprims)
  1086. {
  1087. if (!_activeprims.Contains(activatePrim))
  1088. _activeprims.Add(activatePrim);
  1089. }
  1090. }
  1091. public void addActiveGroups(OdePrim activatePrim)
  1092. {
  1093. lock (_activegroups)
  1094. {
  1095. if (!_activegroups.Contains(activatePrim))
  1096. _activegroups.Add(activatePrim);
  1097. }
  1098. }
  1099. private PhysicsActor AddPrim(String name, Vector3 position, Vector3 size, Quaternion rotation,
  1100. PrimitiveBaseShape pbs, bool isphysical, bool isPhantom, byte shapeType, uint localID)
  1101. {
  1102. OdePrim newPrim;
  1103. lock (OdeLock)
  1104. {
  1105. newPrim = new OdePrim(name, this, position, size, rotation, pbs, isphysical, isPhantom, shapeType, localID);
  1106. }
  1107. return newPrim;
  1108. }
  1109. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  1110. Vector3 size, Quaternion rotation, bool isPhysical, bool isPhantom, uint localid)
  1111. {
  1112. return AddPrim(primName, position, size, rotation, pbs, isPhysical, isPhantom, 0 , localid);
  1113. }
  1114. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  1115. Vector3 size, Quaternion rotation, bool isPhysical, uint localid)
  1116. {
  1117. return AddPrim(primName, position, size, rotation, pbs, isPhysical,false, 0, localid);
  1118. }
  1119. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  1120. Vector3 size, Quaternion rotation, bool isPhysical, bool isPhantom, byte shapeType, uint localid)
  1121. {
  1122. return AddPrim(primName, position, size, rotation, pbs, isPhysical,isPhantom, shapeType, localid);
  1123. }
  1124. public void remActivePrim(OdePrim deactivatePrim)
  1125. {
  1126. lock (_activeprims)
  1127. {
  1128. _activeprims.Remove(deactivatePrim);
  1129. }
  1130. }
  1131. public void remActiveGroup(OdePrim deactivatePrim)
  1132. {
  1133. lock (_activegroups)
  1134. {
  1135. _activegroups.Remove(deactivatePrim);
  1136. }
  1137. }
  1138. public override void RemovePrim(PhysicsActor prim)
  1139. {
  1140. // As with all ODE physics operations, we don't remove the prim immediately but signal that it should be
  1141. // removed in the next physics simulate pass.
  1142. if (prim is OdePrim)
  1143. {
  1144. // lock (OdeLock)
  1145. {
  1146. OdePrim p = (OdePrim)prim;
  1147. p.setPrimForRemoval();
  1148. }
  1149. }
  1150. }
  1151. public void RemovePrimThreadLocked(OdePrim prim)
  1152. {
  1153. //Console.WriteLine("RemovePrimThreadLocked " + prim.m_primName);
  1154. lock (prim)
  1155. {
  1156. // RemoveCollisionEventReporting(prim);
  1157. lock (_prims)
  1158. _prims.Remove(prim.LocalID);
  1159. }
  1160. }
  1161. public void addToPrims(OdePrim prim)
  1162. {
  1163. lock (_prims)
  1164. _prims[prim.LocalID] = prim;
  1165. }
  1166. public OdePrim getPrim(uint id)
  1167. {
  1168. lock (_prims)
  1169. {
  1170. if(_prims.ContainsKey(id))
  1171. return _prims[id];
  1172. else
  1173. return null;
  1174. }
  1175. }
  1176. public bool havePrim(OdePrim prm)
  1177. {
  1178. lock (_prims)
  1179. return _prims.ContainsKey(prm.LocalID);
  1180. }
  1181. public void changePrimID(OdePrim prim,uint oldID)
  1182. {
  1183. lock (_prims)
  1184. {
  1185. if(_prims.ContainsKey(oldID))
  1186. _prims.Remove(oldID);
  1187. _prims[prim.LocalID] = prim;
  1188. }
  1189. }
  1190. public bool haveActor(PhysicsActor actor)
  1191. {
  1192. if (actor is OdePrim)
  1193. {
  1194. lock (_prims)
  1195. return _prims.ContainsKey(((OdePrim)actor).LocalID);
  1196. }
  1197. else if (actor is OdeCharacter)
  1198. {
  1199. lock (_characters)
  1200. return _characters.Contains((OdeCharacter)actor);
  1201. }
  1202. return false;
  1203. }
  1204. #endregion
  1205. #region Space Separation Calculation
  1206. /// <summary>
  1207. /// Called when a static prim moves or becomes static
  1208. /// Places the prim in a space one the static sub-spaces grid
  1209. /// </summary>
  1210. /// <param name="geom">the pointer to the geom that moved</param>
  1211. /// <param name="pos">the position that the geom moved to</param>
  1212. /// <param name="currentspace">a pointer to the space it was in before it was moved.</param>
  1213. /// <returns>a pointer to the new space it's in</returns>
  1214. public IntPtr MoveGeomToStaticSpace(IntPtr geom, Vector3 pos, IntPtr currentspace)
  1215. {
  1216. // moves a prim into another static sub-space or from another space into a static sub-space
  1217. // Called ODEPrim so
  1218. // it's already in locked space.
  1219. if (geom == IntPtr.Zero) // shouldn't happen
  1220. return IntPtr.Zero;
  1221. // get the static sub-space for current position
  1222. IntPtr newspace = calculateSpaceForGeom(pos);
  1223. if (newspace == currentspace) // if we are there all done
  1224. return newspace;
  1225. // else remove it from its current space
  1226. if (currentspace != IntPtr.Zero && d.SpaceQuery(currentspace, geom))
  1227. {
  1228. if (d.GeomIsSpace(currentspace))
  1229. {
  1230. waitForSpaceUnlock(currentspace);
  1231. d.SpaceRemove(currentspace, geom);
  1232. if (d.SpaceGetSublevel(currentspace) > 2 && d.SpaceGetNumGeoms(currentspace) == 0)
  1233. {
  1234. d.SpaceDestroy(currentspace);
  1235. }
  1236. }
  1237. else
  1238. {
  1239. m_log.Info("[Physics]: Invalid or empty Space passed to 'MoveGeomToStaticSpace':" + currentspace +
  1240. " Geom:" + geom);
  1241. }
  1242. }
  1243. else // odd currentspace is null or doesn't contain the geom? lets try the geom ideia of current space
  1244. {
  1245. currentspace = d.GeomGetSpace(geom);
  1246. if (currentspace != IntPtr.Zero)
  1247. {
  1248. if (d.GeomIsSpace(currentspace))
  1249. {
  1250. waitForSpaceUnlock(currentspace);
  1251. d.SpaceRemove(currentspace, geom);
  1252. if (d.SpaceGetSublevel(currentspace) > 2 && d.SpaceGetNumGeoms(currentspace) == 0)
  1253. {
  1254. d.SpaceDestroy(currentspace);
  1255. }
  1256. }
  1257. }
  1258. }
  1259. // put the geom in the newspace
  1260. waitForSpaceUnlock(newspace);
  1261. d.SpaceAdd(newspace, geom);
  1262. // let caller know this newspace
  1263. return newspace;
  1264. }
  1265. /// <summary>
  1266. /// Calculates the space the prim should be in by its position
  1267. /// </summary>
  1268. /// <param name="pos"></param>
  1269. /// <returns>a pointer to the space. This could be a new space or reused space.</returns>
  1270. public IntPtr calculateSpaceForGeom(Vector3 pos)
  1271. {
  1272. int x, y;
  1273. if (pos.X < 0)
  1274. return staticPrimspaceOffRegion[0];
  1275. if (pos.Y < 0)
  1276. return staticPrimspaceOffRegion[2];
  1277. x = (int)(pos.X * spacesPerMeterX);
  1278. if (x > spaceGridMaxX)
  1279. return staticPrimspaceOffRegion[1];
  1280. y = (int)(pos.Y * spacesPerMeterY);
  1281. if (y > spaceGridMaxY)
  1282. return staticPrimspaceOffRegion[3];
  1283. return staticPrimspace[x, y];
  1284. }
  1285. #endregion
  1286. /// <summary>
  1287. /// Called to queue a change to a actor
  1288. /// to use in place of old taint mechanism so changes do have a time sequence
  1289. /// </summary>
  1290. public void AddChange(PhysicsActor actor, changes what, Object arg)
  1291. {
  1292. ODEchangeitem item = new ODEchangeitem();
  1293. item.actor = actor;
  1294. item.what = what;
  1295. item.arg = arg;
  1296. ChangesQueue.Enqueue(item);
  1297. }
  1298. /// <summary>
  1299. /// Called after our prim properties are set Scale, position etc.
  1300. /// We use this event queue like method to keep changes to the physical scene occuring in the threadlocked mutex
  1301. /// This assures us that we have no race conditions
  1302. /// </summary>
  1303. /// <param name="prim"></param>
  1304. public override void AddPhysicsActorTaint(PhysicsActor prim)
  1305. {
  1306. }
  1307. // does all pending changes generated during region load process
  1308. public override void ProcessPreSimulation()
  1309. {
  1310. lock (OdeLock)
  1311. {
  1312. if (world == IntPtr.Zero)
  1313. {
  1314. ChangesQueue.Clear();
  1315. return;
  1316. }
  1317. d.AllocateODEDataForThread(~0U);
  1318. ODEchangeitem item;
  1319. int donechanges = 0;
  1320. if (ChangesQueue.Count > 0)
  1321. {
  1322. m_log.InfoFormat("[ubOde] start processing pending actor operations");
  1323. int tstart = Util.EnvironmentTickCount();
  1324. while (ChangesQueue.Dequeue(out item))
  1325. {
  1326. if (item.actor != null)
  1327. {
  1328. try
  1329. {
  1330. if (item.actor is OdeCharacter)
  1331. ((OdeCharacter)item.actor).DoAChange(item.what, item.arg);
  1332. else if (((OdePrim)item.actor).DoAChange(item.what, item.arg))
  1333. RemovePrimThreadLocked((OdePrim)item.actor);
  1334. }
  1335. catch
  1336. {
  1337. m_log.WarnFormat("[PHYSICS]: Operation failed for a actor {0} {1}",
  1338. item.actor.Name, item.what.ToString());
  1339. }
  1340. }
  1341. donechanges++;
  1342. }
  1343. int time = Util.EnvironmentTickCountSubtract(tstart);
  1344. m_log.InfoFormat("[ubOde] finished {0} operations in {1}ms", donechanges, time);
  1345. }
  1346. m_log.InfoFormat("[ubOde] {0} prim actors loaded",_prims.Count);
  1347. }
  1348. m_lastframe = Util.GetTimeStamp() + 0.5;
  1349. step_time = -0.5f;
  1350. }
  1351. /// <summary>
  1352. /// This is our main simulate loop
  1353. /// It's thread locked by a Mutex in the scene.
  1354. /// It holds Collisions, it instructs ODE to step through the physical reactions
  1355. /// It moves the objects around in memory
  1356. /// It calls the methods that report back to the object owners.. (scenepresence, SceneObjectGroup)
  1357. /// </summary>
  1358. /// <param name="timeStep"></param>
  1359. /// <returns></returns>
  1360. public override float Simulate(float reqTimeStep)
  1361. {
  1362. double now = Util.GetTimeStamp();
  1363. double timeStep = now - m_lastframe;
  1364. m_lastframe = now;
  1365. // acumulate time so we can reduce error
  1366. step_time += (float)timeStep;
  1367. if (step_time < HalfOdeStep)
  1368. return 0;
  1369. if (framecount < 0)
  1370. framecount = 0;
  1371. framecount++;
  1372. // checkThread();
  1373. int nodeframes = 0;
  1374. float fps = 0;
  1375. lock (SimulationLock)
  1376. lock(OdeLock)
  1377. {
  1378. if (world == IntPtr.Zero)
  1379. {
  1380. ChangesQueue.Clear();
  1381. return 0;
  1382. }
  1383. ODEchangeitem item;
  1384. // d.WorldSetQuickStepNumIterations(world, curphysiteractions);
  1385. double loopstartMS = Util.GetTimeStampMS();
  1386. double looptimeMS = 0;
  1387. double changestimeMS = 0;
  1388. double maxChangestime = (int)(reqTimeStep * 500f); // half the time
  1389. double maxLoopTime = (int)(reqTimeStep * 1200f); // 1.2 the time
  1390. // double collisionTime = 0;
  1391. // double qstepTIme = 0;
  1392. // double tmpTime = 0;
  1393. d.AllocateODEDataForThread(~0U);
  1394. if (ChangesQueue.Count > 0)
  1395. {
  1396. while (ChangesQueue.Dequeue(out item))
  1397. {
  1398. if (item.actor != null)
  1399. {
  1400. try
  1401. {
  1402. if (item.actor is OdeCharacter)
  1403. ((OdeCharacter)item.actor).DoAChange(item.what, item.arg);
  1404. else if (((OdePrim)item.actor).DoAChange(item.what, item.arg))
  1405. RemovePrimThreadLocked((OdePrim)item.actor);
  1406. }
  1407. catch
  1408. {
  1409. m_log.WarnFormat("[PHYSICS]: doChange failed for a actor {0} {1}",
  1410. item.actor.Name, item.what.ToString());
  1411. }
  1412. }
  1413. changestimeMS = Util.GetTimeStampMS() - loopstartMS;
  1414. if (changestimeMS > maxChangestime)
  1415. break;
  1416. }
  1417. }
  1418. // do simulation taking at most 150ms total time including changes
  1419. while (step_time > HalfOdeStep)
  1420. {
  1421. try
  1422. {
  1423. // clear pointer/counter to contacts to pass into joints
  1424. m_global_contactcount = 0;
  1425. // Move characters
  1426. lock (_characters)
  1427. {
  1428. List<OdeCharacter> defects = new List<OdeCharacter>();
  1429. foreach (OdeCharacter actor in _characters)
  1430. {
  1431. if (actor != null)
  1432. actor.Move(defects);
  1433. }
  1434. if (defects.Count != 0)
  1435. {
  1436. foreach (OdeCharacter defect in defects)
  1437. {
  1438. RemoveCharacter(defect);
  1439. }
  1440. defects.Clear();
  1441. }
  1442. }
  1443. // Move other active objects
  1444. lock (_activegroups)
  1445. {
  1446. foreach (OdePrim aprim in _activegroups)
  1447. {
  1448. aprim.Move();
  1449. }
  1450. }
  1451. m_rayCastManager.ProcessQueuedRequests();
  1452. // tmpTime = Util.GetTimeStampMS();
  1453. collision_optimized();
  1454. // collisionTime += Util.GetTimeStampMS() - tmpTime;
  1455. lock(_collisionEventPrimRemove)
  1456. {
  1457. foreach (PhysicsActor obj in _collisionEventPrimRemove)
  1458. _collisionEventPrim.Remove(obj);
  1459. _collisionEventPrimRemove.Clear();
  1460. }
  1461. List<OdePrim> sleepers = new List<OdePrim>();
  1462. foreach (PhysicsActor obj in _collisionEventPrim)
  1463. {
  1464. if (obj == null)
  1465. continue;
  1466. switch ((ActorTypes)obj.PhysicsActorType)
  1467. {
  1468. case ActorTypes.Agent:
  1469. OdeCharacter cobj = (OdeCharacter)obj;
  1470. cobj.SendCollisions((int)(odetimestepMS));
  1471. break;
  1472. case ActorTypes.Prim:
  1473. OdePrim pobj = (OdePrim)obj;
  1474. if (!pobj.m_outbounds)
  1475. {
  1476. pobj.SendCollisions((int)(odetimestepMS));
  1477. if(pobj.Body != IntPtr.Zero && !pobj.m_isSelected &&
  1478. !pobj.m_disabled && !pobj.m_building &&
  1479. !d.BodyIsEnabled(pobj.Body))
  1480. sleepers.Add(pobj);
  1481. }
  1482. break;
  1483. }
  1484. }
  1485. foreach(OdePrim prm in sleepers)
  1486. prm.SleeperAddCollisionEvents();
  1487. sleepers.Clear();
  1488. // do a ode simulation step
  1489. // tmpTime = Util.GetTimeStampMS();
  1490. d.WorldQuickStep(world, ODE_STEPSIZE);
  1491. d.JointGroupEmpty(contactgroup);
  1492. // qstepTIme += Util.GetTimeStampMS() - tmpTime;
  1493. // update managed ideia of physical data and do updates to core
  1494. /*
  1495. lock (_characters)
  1496. {
  1497. foreach (OdeCharacter actor in _characters)
  1498. {
  1499. if (actor != null)
  1500. {
  1501. if (actor.bad)
  1502. m_log.WarnFormat("[PHYSICS]: BAD Actor {0} in _characters list was not removed?", actor.m_uuid);
  1503. actor.UpdatePositionAndVelocity();
  1504. }
  1505. }
  1506. }
  1507. */
  1508. lock (_activegroups)
  1509. {
  1510. {
  1511. foreach (OdePrim actor in _activegroups)
  1512. {
  1513. if (actor.IsPhysical)
  1514. {
  1515. actor.UpdatePositionAndVelocity(framecount);
  1516. }
  1517. }
  1518. }
  1519. }
  1520. }
  1521. catch (Exception e)
  1522. {
  1523. m_log.ErrorFormat("[PHYSICS]: {0}, {1}, {2}", e.Message, e.TargetSite, e);
  1524. // ode.dunlock(world);
  1525. }
  1526. step_time -= ODE_STEPSIZE;
  1527. nodeframes++;
  1528. looptimeMS = Util.GetTimeStampMS() - loopstartMS;
  1529. if (looptimeMS > maxLoopTime)
  1530. break;
  1531. }
  1532. lock (_badCharacter)
  1533. {
  1534. if (_badCharacter.Count > 0)
  1535. {
  1536. foreach (OdeCharacter chr in _badCharacter)
  1537. {
  1538. RemoveCharacter(chr);
  1539. }
  1540. _badCharacter.Clear();
  1541. }
  1542. }
  1543. // information block for in debug breakpoint only
  1544. /*
  1545. int ntopactivegeoms = d.SpaceGetNumGeoms(ActiveSpace);
  1546. int ntopstaticgeoms = d.SpaceGetNumGeoms(StaticSpace);
  1547. int ngroundgeoms = d.SpaceGetNumGeoms(GroundSpace);
  1548. int nactivegeoms = 0;
  1549. int nactivespaces = 0;
  1550. int nstaticgeoms = 0;
  1551. int nstaticspaces = 0;
  1552. IntPtr sp;
  1553. for (int i = 0; i < ntopactivegeoms; i++)
  1554. {
  1555. sp = d.SpaceGetGeom(ActiveSpace, i);
  1556. if (d.GeomIsSpace(sp))
  1557. {
  1558. nactivespaces++;
  1559. nactivegeoms += d.SpaceGetNumGeoms(sp);
  1560. }
  1561. else
  1562. nactivegeoms++;
  1563. }
  1564. for (int i = 0; i < ntopstaticgeoms; i++)
  1565. {
  1566. sp = d.SpaceGetGeom(StaticSpace, i);
  1567. if (d.GeomIsSpace(sp))
  1568. {
  1569. nstaticspaces++;
  1570. nstaticgeoms += d.SpaceGetNumGeoms(sp);
  1571. }
  1572. else
  1573. nstaticgeoms++;
  1574. }
  1575. int ntopgeoms = d.SpaceGetNumGeoms(TopSpace);
  1576. int totgeoms = nstaticgeoms + nactivegeoms + ngroundgeoms + 1; // one ray
  1577. int nbodies = d.NTotalBodies;
  1578. int ngeoms = d.NTotalGeoms;
  1579. */
  1580. /*
  1581. looptimeMS /= nodeframes;
  1582. if(looptimeMS > 0.080)
  1583. {
  1584. collisionTime /= nodeframes;
  1585. qstepTIme /= nodeframes;
  1586. }
  1587. */
  1588. // Finished with all sim stepping. If requested, dump world state to file for debugging.
  1589. // TODO: This call to the export function is already inside lock (OdeLock) - but is an extra lock needed?
  1590. // TODO: This overwrites all dump files in-place. Should this be a growing logfile, or separate snapshots?
  1591. if (physics_logging && (physics_logging_interval > 0) && (framecount % physics_logging_interval == 0))
  1592. {
  1593. string fname = "state-" + world.ToString() + ".DIF"; // give each physics world a separate filename
  1594. string prefix = "world" + world.ToString(); // prefix for variable names in exported .DIF file
  1595. if (physics_logging_append_existing_logfile)
  1596. {
  1597. string header = "-------------- START OF PHYSICS FRAME " + framecount.ToString() + " --------------";
  1598. TextWriter fwriter = File.AppendText(fname);
  1599. fwriter.WriteLine(header);
  1600. fwriter.Close();
  1601. }
  1602. d.WorldExportDIF(world, fname, physics_logging_append_existing_logfile, prefix);
  1603. }
  1604. fps = (float)nodeframes * ODE_STEPSIZE / reqTimeStep;
  1605. if(step_time < HalfOdeStep)
  1606. m_timeDilation = 1.0f;
  1607. else if (step_time > m_SkipFramesAtms)
  1608. {
  1609. // if we lag too much skip frames
  1610. m_timeDilation = 0.0f;
  1611. step_time = 0;
  1612. m_lastframe = Util.GetTimeStamp(); // skip also the time lost
  1613. }
  1614. else
  1615. {
  1616. m_timeDilation = ODE_STEPSIZE / step_time;
  1617. if (m_timeDilation > 1)
  1618. m_timeDilation = 1;
  1619. }
  1620. if (m_timeDilation == 1 && now - m_lastMeshExpire > 30)
  1621. {
  1622. mesher.ExpireReleaseMeshs();
  1623. m_lastMeshExpire = now;
  1624. }
  1625. }
  1626. return fps;
  1627. }
  1628. /// <summary>
  1629. public override void GetResults()
  1630. {
  1631. }
  1632. public override bool IsThreaded
  1633. {
  1634. // for now we won't be multithreaded
  1635. get { return (false); }
  1636. }
  1637. public float GetTerrainHeightAtXY(float x, float y)
  1638. {
  1639. if (TerrainGeom == IntPtr.Zero)
  1640. return 0f;
  1641. if (TerrainHeightFieldHeight == null || TerrainHeightFieldHeight.Length == 0)
  1642. return 0f;
  1643. // TerrainHeightField for ODE as offset 1m
  1644. x += 1f;
  1645. y += 1f;
  1646. // make position fit into array
  1647. if (x < 0)
  1648. x = 0;
  1649. if (y < 0)
  1650. y = 0;
  1651. // integer indexs
  1652. int ix;
  1653. int iy;
  1654. // interpolators offset
  1655. float dx;
  1656. float dy;
  1657. int regsizeX = (int)m_regionWidth + 3; // map size see setterrain number of samples
  1658. int regsizeY = (int)m_regionHeight + 3; // map size see setterrain number of samples
  1659. int regsize = regsizeX;
  1660. if (m_OSOdeLib)
  1661. {
  1662. if (x < regsizeX - 1)
  1663. {
  1664. ix = (int)x;
  1665. dx = x - (float)ix;
  1666. }
  1667. else // out world use external height
  1668. {
  1669. ix = regsizeX - 2;
  1670. dx = 0;
  1671. }
  1672. if (y < regsizeY - 1)
  1673. {
  1674. iy = (int)y;
  1675. dy = y - (float)iy;
  1676. }
  1677. else
  1678. {
  1679. iy = regsizeY - 2;
  1680. dy = 0;
  1681. }
  1682. }
  1683. else
  1684. {
  1685. // we still have square fixed size regions
  1686. // also flip x and y because of how map is done for ODE fliped axis
  1687. // so ix,iy,dx and dy are inter exchanged
  1688. regsize = regsizeY;
  1689. if (x < regsizeX - 1)
  1690. {
  1691. iy = (int)x;
  1692. dy = x - (float)iy;
  1693. }
  1694. else // out world use external height
  1695. {
  1696. iy = regsizeX - 2;
  1697. dy = 0;
  1698. }
  1699. if (y < regsizeY - 1)
  1700. {
  1701. ix = (int)y;
  1702. dx = y - (float)ix;
  1703. }
  1704. else
  1705. {
  1706. ix = regsizeY - 2;
  1707. dx = 0;
  1708. }
  1709. }
  1710. float h0;
  1711. float h1;
  1712. float h2;
  1713. iy *= regsize;
  1714. iy += ix; // all indexes have iy + ix
  1715. float[] heights = TerrainHeightFieldHeight;
  1716. /*
  1717. if ((dx + dy) <= 1.0f)
  1718. {
  1719. h0 = ((float)heights[iy]); // 0,0 vertice
  1720. h1 = (((float)heights[iy + 1]) - h0) * dx; // 1,0 vertice minus 0,0
  1721. h2 = (((float)heights[iy + regsize]) - h0) * dy; // 0,1 vertice minus 0,0
  1722. }
  1723. else
  1724. {
  1725. h0 = ((float)heights[iy + regsize + 1]); // 1,1 vertice
  1726. h1 = (((float)heights[iy + 1]) - h0) * (1 - dy); // 1,1 vertice minus 1,0
  1727. h2 = (((float)heights[iy + regsize]) - h0) * (1 - dx); // 1,1 vertice minus 0,1
  1728. }
  1729. */
  1730. h0 = ((float)heights[iy]); // 0,0 vertice
  1731. if (dy>dx)
  1732. {
  1733. iy += regsize;
  1734. h2 = (float)heights[iy]; // 0,1 vertice
  1735. h1 = (h2 - h0) * dy; // 0,1 vertice minus 0,0
  1736. h2 = ((float)heights[iy + 1] - h2) * dx; // 1,1 vertice minus 0,1
  1737. }
  1738. else
  1739. {
  1740. iy++;
  1741. h2 = (float)heights[iy]; // vertice 1,0
  1742. h1 = (h2 - h0) * dx; // 1,0 vertice minus 0,0
  1743. h2 = (((float)heights[iy + regsize]) - h2) * dy; // 1,1 vertice minus 1,0
  1744. }
  1745. return h0 + h1 + h2;
  1746. }
  1747. public Vector3 GetTerrainNormalAtXY(float x, float y)
  1748. {
  1749. Vector3 norm = new Vector3(0, 0, 1);
  1750. if (TerrainGeom == IntPtr.Zero)
  1751. return norm;
  1752. if (TerrainHeightFieldHeight == null || TerrainHeightFieldHeight.Length == 0)
  1753. return norm;
  1754. // TerrainHeightField for ODE as offset 1m
  1755. x += 1f;
  1756. y += 1f;
  1757. // make position fit into array
  1758. if (x < 0)
  1759. x = 0;
  1760. if (y < 0)
  1761. y = 0;
  1762. // integer indexs
  1763. int ix;
  1764. int iy;
  1765. // interpolators offset
  1766. float dx;
  1767. float dy;
  1768. int regsizeX = (int)m_regionWidth + 3; // map size see setterrain number of samples
  1769. int regsizeY = (int)m_regionHeight + 3; // map size see setterrain number of samples
  1770. int regsize = regsizeX;
  1771. int xstep = 1;
  1772. int ystep = regsizeX;
  1773. bool firstTri = false;
  1774. if (m_OSOdeLib)
  1775. {
  1776. if (x < regsizeX - 1)
  1777. {
  1778. ix = (int)x;
  1779. dx = x - (float)ix;
  1780. }
  1781. else // out world use external height
  1782. {
  1783. ix = regsizeX - 2;
  1784. dx = 0;
  1785. }
  1786. if (y < regsizeY - 1)
  1787. {
  1788. iy = (int)y;
  1789. dy = y - (float)iy;
  1790. }
  1791. else
  1792. {
  1793. iy = regsizeY - 2;
  1794. dy = 0;
  1795. }
  1796. firstTri = dy > dx;
  1797. }
  1798. else
  1799. {
  1800. xstep = regsizeY;
  1801. ystep = 1;
  1802. regsize = regsizeY;
  1803. // we still have square fixed size regions
  1804. // also flip x and y because of how map is done for ODE fliped axis
  1805. // so ix,iy,dx and dy are inter exchanged
  1806. if (x < regsizeX - 1)
  1807. {
  1808. iy = (int)x;
  1809. dy = x - (float)iy;
  1810. }
  1811. else // out world use external height
  1812. {
  1813. iy = regsizeX - 2;
  1814. dy = 0;
  1815. }
  1816. if (y < regsizeY - 1)
  1817. {
  1818. ix = (int)y;
  1819. dx = y - (float)ix;
  1820. }
  1821. else
  1822. {
  1823. ix = regsizeY - 2;
  1824. dx = 0;
  1825. }
  1826. firstTri = dx > dy;
  1827. }
  1828. float h0;
  1829. float h1;
  1830. float h2;
  1831. iy *= regsize;
  1832. iy += ix; // all indexes have iy + ix
  1833. float[] heights = TerrainHeightFieldHeight;
  1834. if (firstTri)
  1835. {
  1836. h1 = ((float)heights[iy]); // 0,0 vertice
  1837. iy += ystep;
  1838. h0 = (float)heights[iy]; // 0,1
  1839. h2 = (float)heights[iy+xstep]; // 1,1 vertice
  1840. norm.X = h0 - h2;
  1841. norm.Y = h1 - h0;
  1842. }
  1843. else
  1844. {
  1845. h2 = ((float)heights[iy]); // 0,0 vertice
  1846. iy += xstep;
  1847. h0 = ((float)heights[iy]); // 1,0 vertice
  1848. h1 = (float)heights[iy+ystep]; // vertice 1,1
  1849. norm.X = h2 - h0;
  1850. norm.Y = h0 - h1;
  1851. }
  1852. norm.Z = 1;
  1853. norm.Normalize();
  1854. return norm;
  1855. }
  1856. public override void SetTerrain(float[] heightMap)
  1857. {
  1858. if (m_OSOdeLib)
  1859. OSSetTerrain(heightMap);
  1860. else
  1861. OriSetTerrain(heightMap);
  1862. }
  1863. public void OriSetTerrain(float[] heightMap)
  1864. {
  1865. // assumes 1m size grid and constante size square regions
  1866. // needs to know about sims around in future
  1867. float[] _heightmap;
  1868. uint regionsizeX = m_regionWidth;
  1869. uint regionsizeY = m_regionHeight;
  1870. // map is rotated
  1871. uint heightmapWidth = regionsizeY + 2;
  1872. uint heightmapHeight = regionsizeX + 2;
  1873. uint heightmapWidthSamples = heightmapWidth + 1;
  1874. uint heightmapHeightSamples = heightmapHeight + 1;
  1875. _heightmap = new float[heightmapWidthSamples * heightmapHeightSamples];
  1876. const float scale = 1.0f;
  1877. const float offset = 0.0f;
  1878. const float thickness = 10f;
  1879. const int wrap = 0;
  1880. float hfmin = float.MaxValue;
  1881. float hfmax = float.MinValue;
  1882. float val;
  1883. uint xx;
  1884. uint yy;
  1885. uint maxXX = regionsizeX - 1;
  1886. uint maxYY = regionsizeY - 1;
  1887. // flipping map adding one margin all around so things don't fall in edges
  1888. uint xt = 0;
  1889. xx = 0;
  1890. for (uint x = 0; x < heightmapWidthSamples; x++)
  1891. {
  1892. if (x > 1 && xx < maxXX)
  1893. xx++;
  1894. yy = 0;
  1895. for (uint y = 0; y < heightmapHeightSamples; y++)
  1896. {
  1897. if (y > 1 && y < maxYY)
  1898. yy += regionsizeX;
  1899. val = heightMap[yy + xx];
  1900. if (val < 0.0f)
  1901. val = 0.0f; // no neg terrain as in chode
  1902. _heightmap[xt + y] = val;
  1903. if (hfmin > val)
  1904. hfmin = val;
  1905. if (hfmax < val)
  1906. hfmax = val;
  1907. }
  1908. xt += heightmapHeightSamples;
  1909. }
  1910. lock (OdeLock)
  1911. {
  1912. d.AllocateODEDataForThread(~0U);
  1913. if (TerrainGeom != IntPtr.Zero)
  1914. {
  1915. actor_name_map.Remove(TerrainGeom);
  1916. d.GeomDestroy(TerrainGeom);
  1917. }
  1918. if (TerrainHeightFieldHeightsHandler.IsAllocated)
  1919. TerrainHeightFieldHeightsHandler.Free();
  1920. IntPtr HeightmapData = d.GeomHeightfieldDataCreate();
  1921. TerrainHeightFieldHeightsHandler = GCHandle.Alloc(_heightmap, GCHandleType.Pinned);
  1922. d.GeomHeightfieldDataBuildSingle(HeightmapData, TerrainHeightFieldHeightsHandler.AddrOfPinnedObject(), 0,
  1923. heightmapHeight, heightmapWidth ,
  1924. (int)heightmapHeightSamples, (int)heightmapWidthSamples, scale,
  1925. offset, thickness, wrap);
  1926. d.GeomHeightfieldDataSetBounds(HeightmapData, hfmin - 1, hfmax + 1);
  1927. TerrainGeom = d.CreateHeightfield(GroundSpace, HeightmapData, 1);
  1928. if (TerrainGeom != IntPtr.Zero)
  1929. {
  1930. d.GeomSetCategoryBits(TerrainGeom, (uint)(CollisionCategories.Land));
  1931. d.GeomSetCollideBits(TerrainGeom, 0);
  1932. PhysicsActor pa = new NullPhysicsActor();
  1933. pa.Name = "Terrain";
  1934. pa.PhysicsActorType = (int)ActorTypes.Ground;
  1935. actor_name_map[TerrainGeom] = pa;
  1936. // geom_name_map[GroundGeom] = "Terrain";
  1937. d.Quaternion q = new d.Quaternion();
  1938. q.X = 0.5f;
  1939. q.Y = 0.5f;
  1940. q.Z = 0.5f;
  1941. q.W = 0.5f;
  1942. d.GeomSetQuaternion(TerrainGeom, ref q);
  1943. d.GeomSetPosition(TerrainGeom, m_regionWidth * 0.5f, m_regionHeight * 0.5f, 0.0f);
  1944. TerrainHeightFieldHeight = _heightmap;
  1945. }
  1946. else
  1947. TerrainHeightFieldHeightsHandler.Free();
  1948. }
  1949. }
  1950. public void OSSetTerrain(float[] heightMap)
  1951. {
  1952. // assumes 1m size grid and constante size square regions
  1953. // needs to know about sims around in future
  1954. float[] _heightmap;
  1955. uint regionsizeX = m_regionWidth;
  1956. uint regionsizeY = m_regionHeight;
  1957. uint heightmapWidth = regionsizeX + 2;
  1958. uint heightmapHeight = regionsizeY + 2;
  1959. uint heightmapWidthSamples = heightmapWidth + 1;
  1960. uint heightmapHeightSamples = heightmapHeight + 1;
  1961. _heightmap = new float[heightmapWidthSamples * heightmapHeightSamples];
  1962. float hfmin = float.MaxValue;
  1963. // float hfmax = float.MinValue;
  1964. float val;
  1965. uint maxXX = regionsizeX - 1;
  1966. uint maxYY = regionsizeY - 1;
  1967. // adding one margin all around so things don't fall in edges
  1968. uint xx;
  1969. uint yy = 0;
  1970. uint yt = 0;
  1971. for (uint y = 0; y < heightmapHeightSamples; y++)
  1972. {
  1973. if (y > 1 && y < maxYY)
  1974. yy += regionsizeX;
  1975. xx = 0;
  1976. for (uint x = 0; x < heightmapWidthSamples; x++)
  1977. {
  1978. if (x > 1 && x < maxXX)
  1979. xx++;
  1980. val = heightMap[yy + xx];
  1981. if (val < 0.0f)
  1982. val = 0.0f; // no neg terrain as in chode
  1983. _heightmap[yt + x] = val;
  1984. if (hfmin > val)
  1985. hfmin = val;
  1986. // if (hfmax < val)
  1987. // hfmax = val;
  1988. }
  1989. yt += heightmapWidthSamples;
  1990. }
  1991. lock (OdeLock)
  1992. {
  1993. if (TerrainGeom != IntPtr.Zero)
  1994. {
  1995. actor_name_map.Remove(TerrainGeom);
  1996. d.GeomDestroy(TerrainGeom);
  1997. }
  1998. if (TerrainHeightFieldHeightsHandler.IsAllocated)
  1999. TerrainHeightFieldHeightsHandler.Free();
  2000. TerrainHeightFieldHeight = null;
  2001. IntPtr HeightmapData = d.GeomOSTerrainDataCreate();
  2002. const int wrap = 0;
  2003. float thickness = hfmin;
  2004. if (thickness < 0)
  2005. thickness = 1;
  2006. TerrainHeightFieldHeightsHandler = GCHandle.Alloc(_heightmap, GCHandleType.Pinned);
  2007. d.GeomOSTerrainDataBuild(HeightmapData, TerrainHeightFieldHeightsHandler.AddrOfPinnedObject(), 0, 1.0f,
  2008. (int)heightmapWidthSamples, (int)heightmapHeightSamples,
  2009. thickness, wrap);
  2010. // d.GeomOSTerrainDataSetBounds(HeightmapData, hfmin - 1, hfmax + 1);
  2011. TerrainGeom = d.CreateOSTerrain(GroundSpace, HeightmapData, 1);
  2012. if (TerrainGeom != IntPtr.Zero)
  2013. {
  2014. d.GeomSetCategoryBits(TerrainGeom, (uint)(CollisionCategories.Land));
  2015. d.GeomSetCollideBits(TerrainGeom, 0);
  2016. PhysicsActor pa = new NullPhysicsActor();
  2017. pa.Name = "Terrain";
  2018. pa.PhysicsActorType = (int)ActorTypes.Ground;
  2019. actor_name_map[TerrainGeom] = pa;
  2020. // geom_name_map[GroundGeom] = "Terrain";
  2021. d.GeomSetPosition(TerrainGeom, m_regionWidth * 0.5f, m_regionHeight * 0.5f, 0.0f);
  2022. TerrainHeightFieldHeight = _heightmap;
  2023. }
  2024. else
  2025. TerrainHeightFieldHeightsHandler.Free();
  2026. }
  2027. }
  2028. public override void DeleteTerrain()
  2029. {
  2030. }
  2031. public float GetWaterLevel()
  2032. {
  2033. return waterlevel;
  2034. }
  2035. public override void SetWaterLevel(float baseheight)
  2036. {
  2037. waterlevel = baseheight;
  2038. }
  2039. public override void Dispose()
  2040. {
  2041. lock (OdeLock)
  2042. {
  2043. if (world == IntPtr.Zero)
  2044. return;
  2045. d.AllocateODEDataForThread(~0U);
  2046. if (m_meshWorker != null)
  2047. m_meshWorker.Stop();
  2048. if (m_rayCastManager != null)
  2049. {
  2050. m_rayCastManager.Dispose();
  2051. m_rayCastManager = null;
  2052. }
  2053. lock (_prims)
  2054. {
  2055. ChangesQueue.Clear();
  2056. foreach (OdePrim prm in _prims.Values)
  2057. {
  2058. prm.DoAChange(changes.Remove, null);
  2059. _collisionEventPrim.Remove(prm);
  2060. }
  2061. _prims.Clear();
  2062. }
  2063. OdeCharacter[] chtorem;
  2064. lock (_characters)
  2065. {
  2066. chtorem = new OdeCharacter[_characters.Count];
  2067. _characters.CopyTo(chtorem);
  2068. }
  2069. ChangesQueue.Clear();
  2070. foreach (OdeCharacter ch in chtorem)
  2071. ch.DoAChange(changes.Remove, null);
  2072. if (TerrainGeom != IntPtr.Zero)
  2073. d.GeomDestroy(TerrainGeom);
  2074. TerrainGeom = IntPtr.Zero;
  2075. if (TerrainHeightFieldHeightsHandler.IsAllocated)
  2076. TerrainHeightFieldHeightsHandler.Free();
  2077. TerrainHeightFieldHeight = null;
  2078. if (ContactgeomsArray != IntPtr.Zero)
  2079. {
  2080. Marshal.FreeHGlobal(ContactgeomsArray);
  2081. ContactgeomsArray = IntPtr.Zero;
  2082. }
  2083. if (GlobalContactsArray != IntPtr.Zero)
  2084. {
  2085. Marshal.FreeHGlobal(GlobalContactsArray);
  2086. GlobalContactsArray = IntPtr.Zero;
  2087. }
  2088. d.WorldDestroy(world);
  2089. world = IntPtr.Zero;
  2090. //d.CloseODE();
  2091. }
  2092. }
  2093. private int compareByCollisionsDesc(OdePrim A, OdePrim B)
  2094. {
  2095. return -A.CollisionScore.CompareTo(B.CollisionScore);
  2096. }
  2097. public override Dictionary<uint, float> GetTopColliders()
  2098. {
  2099. Dictionary<uint, float> topColliders;
  2100. List<OdePrim> orderedPrims;
  2101. lock (_activeprims)
  2102. orderedPrims = new List<OdePrim>(_activeprims);
  2103. orderedPrims.Sort(compareByCollisionsDesc);
  2104. topColliders = orderedPrims.Take(25).ToDictionary(p => p.LocalID, p => p.CollisionScore);
  2105. return topColliders;
  2106. }
  2107. public override bool SupportsRayCast()
  2108. {
  2109. return true;
  2110. }
  2111. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod)
  2112. {
  2113. if (retMethod != null)
  2114. {
  2115. ODERayRequest req = new ODERayRequest();
  2116. req.actor = null;
  2117. req.callbackMethod = retMethod;
  2118. req.length = length;
  2119. req.Normal = direction;
  2120. req.Origin = position;
  2121. req.Count = 0;
  2122. req.filter = RayFilterFlags.AllPrims;
  2123. m_rayCastManager.QueueRequest(req);
  2124. }
  2125. }
  2126. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayCallback retMethod)
  2127. {
  2128. if (retMethod != null)
  2129. {
  2130. ODERayRequest req = new ODERayRequest();
  2131. req.actor = null;
  2132. req.callbackMethod = retMethod;
  2133. req.length = length;
  2134. req.Normal = direction;
  2135. req.Origin = position;
  2136. req.Count = Count;
  2137. req.filter = RayFilterFlags.AllPrims;
  2138. m_rayCastManager.QueueRequest(req);
  2139. }
  2140. }
  2141. public override List<ContactResult> RaycastWorld(Vector3 position, Vector3 direction, float length, int Count)
  2142. {
  2143. List<ContactResult> ourresults = new List<ContactResult>();
  2144. object SyncObject = new object();
  2145. RayCallback retMethod = delegate(List<ContactResult> results)
  2146. {
  2147. lock (SyncObject)
  2148. {
  2149. ourresults = results;
  2150. Monitor.PulseAll(SyncObject);
  2151. }
  2152. };
  2153. ODERayRequest req = new ODERayRequest();
  2154. req.actor = null;
  2155. req.callbackMethod = retMethod;
  2156. req.length = length;
  2157. req.Normal = direction;
  2158. req.Origin = position;
  2159. req.Count = Count;
  2160. req.filter = RayFilterFlags.AllPrims;
  2161. lock (SyncObject)
  2162. {
  2163. m_rayCastManager.QueueRequest(req);
  2164. if (!Monitor.Wait(SyncObject, 500))
  2165. return null;
  2166. else
  2167. return ourresults;
  2168. }
  2169. }
  2170. public override bool SupportsRaycastWorldFiltered()
  2171. {
  2172. return true;
  2173. }
  2174. public override object RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter)
  2175. {
  2176. object SyncObject = new object();
  2177. List<ContactResult> ourresults = new List<ContactResult>();
  2178. RayCallback retMethod = delegate(List<ContactResult> results)
  2179. {
  2180. lock (SyncObject)
  2181. {
  2182. ourresults = results;
  2183. Monitor.PulseAll(SyncObject);
  2184. }
  2185. };
  2186. ODERayRequest req = new ODERayRequest();
  2187. req.actor = null;
  2188. req.callbackMethod = retMethod;
  2189. req.length = length;
  2190. req.Normal = direction;
  2191. req.Origin = position;
  2192. req.Count = Count;
  2193. req.filter = filter;
  2194. lock (SyncObject)
  2195. {
  2196. m_rayCastManager.QueueRequest(req);
  2197. if (!Monitor.Wait(SyncObject, 500))
  2198. return null;
  2199. else
  2200. return ourresults;
  2201. }
  2202. }
  2203. public override List<ContactResult> RaycastActor(PhysicsActor actor, Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags flags)
  2204. {
  2205. if (actor == null)
  2206. return new List<ContactResult>();
  2207. IntPtr geom;
  2208. if (actor is OdePrim)
  2209. geom = ((OdePrim)actor).prim_geom;
  2210. else if (actor is OdeCharacter)
  2211. geom = ((OdePrim)actor).prim_geom;
  2212. else
  2213. return new List<ContactResult>();
  2214. if (geom == IntPtr.Zero)
  2215. return new List<ContactResult>();
  2216. List<ContactResult> ourResults = null;
  2217. object SyncObject = new object();
  2218. RayCallback retMethod = delegate(List<ContactResult> results)
  2219. {
  2220. lock (SyncObject)
  2221. {
  2222. ourResults = results;
  2223. Monitor.PulseAll(SyncObject);
  2224. }
  2225. };
  2226. ODERayRequest req = new ODERayRequest();
  2227. req.actor = actor;
  2228. req.callbackMethod = retMethod;
  2229. req.length = length;
  2230. req.Normal = direction;
  2231. req.Origin = position;
  2232. req.Count = Count;
  2233. req.filter = flags;
  2234. lock (SyncObject)
  2235. {
  2236. m_rayCastManager.QueueRequest(req);
  2237. if (!Monitor.Wait(SyncObject, 500))
  2238. return new List<ContactResult>();
  2239. }
  2240. if (ourResults == null)
  2241. return new List<ContactResult>();
  2242. return ourResults;
  2243. }
  2244. public override List<ContactResult> BoxProbe(Vector3 position, Vector3 size, Quaternion orientation, int Count, RayFilterFlags flags)
  2245. {
  2246. List<ContactResult> ourResults = null;
  2247. object SyncObject = new object();
  2248. ProbeBoxCallback retMethod = delegate(List<ContactResult> results)
  2249. {
  2250. lock (SyncObject)
  2251. {
  2252. ourResults = results;
  2253. Monitor.PulseAll(SyncObject);
  2254. }
  2255. };
  2256. ODERayRequest req = new ODERayRequest();
  2257. req.actor = null;
  2258. req.callbackMethod = retMethod;
  2259. req.Normal = size;
  2260. req.Origin = position;
  2261. req.orientation = orientation;
  2262. req.Count = Count;
  2263. req.filter = flags;
  2264. lock (SyncObject)
  2265. {
  2266. m_rayCastManager.QueueRequest(req);
  2267. if (!Monitor.Wait(SyncObject, 500))
  2268. return new List<ContactResult>();
  2269. }
  2270. if (ourResults == null)
  2271. return new List<ContactResult>();
  2272. return ourResults;
  2273. }
  2274. public override List<ContactResult> SphereProbe(Vector3 position, float radius, int Count, RayFilterFlags flags)
  2275. {
  2276. List<ContactResult> ourResults = null;
  2277. object SyncObject = new object();
  2278. ProbeSphereCallback retMethod = delegate(List<ContactResult> results)
  2279. {
  2280. ourResults = results;
  2281. Monitor.PulseAll(SyncObject);
  2282. };
  2283. ODERayRequest req = new ODERayRequest();
  2284. req.actor = null;
  2285. req.callbackMethod = retMethod;
  2286. req.length = radius;
  2287. req.Origin = position;
  2288. req.Count = Count;
  2289. req.filter = flags;
  2290. lock (SyncObject)
  2291. {
  2292. m_rayCastManager.QueueRequest(req);
  2293. if (!Monitor.Wait(SyncObject, 500))
  2294. return new List<ContactResult>();
  2295. }
  2296. if (ourResults == null)
  2297. return new List<ContactResult>();
  2298. return ourResults;
  2299. }
  2300. public override List<ContactResult> PlaneProbe(PhysicsActor actor, Vector4 plane, int Count, RayFilterFlags flags)
  2301. {
  2302. IntPtr geom = IntPtr.Zero;;
  2303. if (actor != null)
  2304. {
  2305. if (actor is OdePrim)
  2306. geom = ((OdePrim)actor).prim_geom;
  2307. else if (actor is OdeCharacter)
  2308. geom = ((OdePrim)actor).prim_geom;
  2309. }
  2310. List<ContactResult> ourResults = null;
  2311. object SyncObject = new object();
  2312. ProbePlaneCallback retMethod = delegate(List<ContactResult> results)
  2313. {
  2314. ourResults = results;
  2315. Monitor.PulseAll(SyncObject);
  2316. };
  2317. ODERayRequest req = new ODERayRequest();
  2318. req.actor = null;
  2319. req.callbackMethod = retMethod;
  2320. req.length = plane.W;
  2321. req.Normal.X = plane.X;
  2322. req.Normal.Y = plane.Y;
  2323. req.Normal.Z = plane.Z;
  2324. req.Count = Count;
  2325. req.filter = flags;
  2326. lock (SyncObject)
  2327. {
  2328. m_rayCastManager.QueueRequest(req);
  2329. if (!Monitor.Wait(SyncObject, 500))
  2330. return new List<ContactResult>();
  2331. }
  2332. if (ourResults == null)
  2333. return new List<ContactResult>();
  2334. return ourResults;
  2335. }
  2336. public override int SitAvatar(PhysicsActor actor, Vector3 AbsolutePosition, Vector3 CameraPosition, Vector3 offset, Vector3 AvatarSize, SitAvatarCallback PhysicsSitResponse)
  2337. {
  2338. Util.FireAndForget( delegate
  2339. {
  2340. ODESitAvatar sitAvatar = new ODESitAvatar(this, m_rayCastManager);
  2341. if(sitAvatar != null)
  2342. sitAvatar.Sit(actor, AbsolutePosition, CameraPosition, offset, AvatarSize, PhysicsSitResponse);
  2343. });
  2344. return 1;
  2345. }
  2346. }
  2347. }