BSScene.cs 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  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 copyrightD
  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. using System;
  28. using System.Collections.Generic;
  29. using System.Linq;
  30. using System.Reflection;
  31. using System.Runtime.InteropServices;
  32. using System.Text;
  33. using System.Threading;
  34. using OpenSim.Framework;
  35. using OpenSim.Framework.Monitoring;
  36. using OpenSim.Region.Framework.Scenes;
  37. using OpenSim.Region.Framework.Interfaces;
  38. using OpenSim.Region.PhysicsModules.SharedBase;
  39. using Nini.Config;
  40. using log4net;
  41. using OpenMetaverse;
  42. using Mono.Addins;
  43. namespace OpenSim.Region.PhysicsModule.BulletS
  44. {
  45. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BulletSPhysicsScene")]
  46. public sealed class BSScene : PhysicsScene, IPhysicsParameters, INonSharedRegionModule
  47. {
  48. internal static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  49. internal static readonly string LogHeader = "[BULLETS SCENE]";
  50. private bool m_Enabled = false;
  51. private IConfigSource m_Config;
  52. // The name of the region we're working for.
  53. public string RegionName { get; private set; }
  54. public string BulletSimVersion = "?";
  55. // The handle to the underlying managed or unmanaged version of Bullet being used.
  56. public string BulletEngineName { get; private set; }
  57. public BSAPITemplate PE;
  58. // If the physics engine is running on a separate thread
  59. public Thread m_physicsThread;
  60. public Dictionary<uint, BSPhysObject> PhysObjects;
  61. public BSShapeCollection Shapes;
  62. // Keeping track of the objects with collisions so we can report begin and end of a collision
  63. public HashSet<BSPhysObject> ObjectsWithCollisions = new HashSet<BSPhysObject>();
  64. public HashSet<BSPhysObject> ObjectsWithNoMoreCollisions = new HashSet<BSPhysObject>();
  65. // All the collision processing is protected with this lock object
  66. public Object CollisionLock = new Object();
  67. // Properties are updated here
  68. public Object UpdateLock = new Object();
  69. public HashSet<BSPhysObject> ObjectsWithUpdates = new HashSet<BSPhysObject>();
  70. // Keep track of all the avatars so we can send them a collision event
  71. // every tick so OpenSim will update its animation.
  72. private HashSet<BSPhysObject> AvatarsInScene = new HashSet<BSPhysObject>();
  73. private Object AvatarsInSceneLock = new Object();
  74. // let my minuions use my logger
  75. public ILog Logger { get { return m_log; } }
  76. public IMesher mesher;
  77. public uint WorldID { get; private set; }
  78. public BulletWorld World { get; private set; }
  79. // All the constraints that have been allocated in this instance.
  80. public BSConstraintCollection Constraints { get; private set; }
  81. // Simulation parameters
  82. //internal float m_physicsStepTime; // if running independently, the interval simulated by default
  83. internal int m_maxSubSteps;
  84. internal float m_fixedTimeStep;
  85. internal float m_simulatedTime; // the time simulated previously. Used for physics framerate calc.
  86. internal long m_simulationStep = 0; // The current simulation step.
  87. public long SimulationStep { get { return m_simulationStep; } }
  88. // A number to use for SimulationStep that is probably not any step value
  89. // Used by the collision code (which remembers the step when a collision happens) to remember not any simulation step.
  90. public static long NotASimulationStep = -1234;
  91. internal float LastTimeStep { get; private set; } // The simulation time from the last invocation of Simulate()
  92. internal float NominalFrameRate { get; set; } // Parameterized ideal frame rate that simulation is scaled to
  93. // Physical objects can register for prestep or poststep events
  94. public delegate void PreStepAction(float timeStep);
  95. public delegate void PostStepAction(float timeStep);
  96. public event PreStepAction BeforeStep;
  97. public event PostStepAction AfterStep;
  98. // A value of the time 'now' so all the collision and update routines do not have to get their own
  99. // Set to 'now' just before all the prims and actors are called for collisions and updates
  100. public int SimulationNowTime { get; private set; }
  101. // True if initialized and ready to do simulation steps
  102. private bool m_initialized = false;
  103. // Object locked whenever execution is inside the physics engine
  104. public Object PhysicsEngineLock = new object();
  105. // Flag that is true when the simulator is active and shouldn't be touched
  106. public bool InSimulationTime { get; private set; }
  107. // Pinned memory used to pass step information between managed and unmanaged
  108. internal int m_maxCollisionsPerFrame;
  109. internal CollisionDesc[] m_collisionArray;
  110. internal int m_maxUpdatesPerFrame;
  111. internal EntityProperties[] m_updateArray;
  112. /// <summary>
  113. /// Used to control physics simulation timing if Bullet is running on its own thread.
  114. /// </summary>
  115. private ManualResetEvent m_updateWaitEvent;
  116. public const uint TERRAIN_ID = 0; // OpenSim senses terrain with a localID of zero
  117. public const uint GROUNDPLANE_ID = 1;
  118. public const uint CHILDTERRAIN_ID = 2; // Terrain allocated based on our mega-prim childre start here
  119. public float SimpleWaterLevel { get; set; }
  120. public BSTerrainManager TerrainManager { get; private set; }
  121. public ConfigurationParameters Params
  122. {
  123. get { return UnmanagedParams[0]; }
  124. }
  125. public Vector3 DefaultGravity
  126. {
  127. get { return new Vector3(0f, 0f, Params.gravity); }
  128. }
  129. // Just the Z value of the gravity
  130. public float DefaultGravityZ
  131. {
  132. get { return Params.gravity; }
  133. }
  134. // When functions in the unmanaged code must be called, it is only
  135. // done at a known time just before the simulation step. The taint
  136. // system saves all these function calls and executes them in
  137. // order before the simulation.
  138. public delegate void TaintCallback();
  139. private struct TaintCallbackEntry
  140. {
  141. public String originator;
  142. public String ident;
  143. public TaintCallback callback;
  144. public TaintCallbackEntry(string pIdent, TaintCallback pCallBack)
  145. {
  146. originator = BSScene.DetailLogZero;
  147. ident = pIdent;
  148. callback = pCallBack;
  149. }
  150. public TaintCallbackEntry(string pOrigin, string pIdent, TaintCallback pCallBack)
  151. {
  152. originator = pOrigin;
  153. ident = pIdent;
  154. callback = pCallBack;
  155. }
  156. }
  157. private Object _taintLock = new Object(); // lock for using the next object
  158. private List<TaintCallbackEntry> _taintOperations;
  159. private Dictionary<string, TaintCallbackEntry> _postTaintOperations;
  160. private List<TaintCallbackEntry> _postStepOperations;
  161. // A pointer to an instance if this structure is passed to the C++ code
  162. // Used to pass basic configuration values to the unmanaged code.
  163. internal ConfigurationParameters[] UnmanagedParams;
  164. // Sometimes you just have to log everything.
  165. public LogWriter PhysicsLogging;
  166. private bool m_physicsLoggingEnabled;
  167. private string m_physicsLoggingDir;
  168. private string m_physicsLoggingPrefix;
  169. private int m_physicsLoggingFileMinutes;
  170. private bool m_physicsLoggingDoFlush;
  171. private bool m_physicsPhysicalDumpEnabled;
  172. public int PhysicsMetricDumpFrames { get; set; }
  173. // 'true' of the vehicle code is to log lots of details
  174. public bool VehicleLoggingEnabled { get; private set; }
  175. public bool VehiclePhysicalLoggingEnabled { get; private set; }
  176. #region INonSharedRegionModule
  177. public string Name
  178. {
  179. get { return "BulletSim"; }
  180. }
  181. public string Version
  182. {
  183. get { return "1.0"; }
  184. }
  185. public Type ReplaceableInterface
  186. {
  187. get { return null; }
  188. }
  189. public void Initialise(IConfigSource source)
  190. {
  191. // TODO: Move this out of Startup
  192. IConfig config = source.Configs["Startup"];
  193. if (config != null)
  194. {
  195. string physics = config.GetString("physics", string.Empty);
  196. if (physics == Name)
  197. {
  198. m_Enabled = true;
  199. m_Config = source;
  200. }
  201. }
  202. }
  203. public void Close()
  204. {
  205. }
  206. public void AddRegion(Scene scene)
  207. {
  208. if (!m_Enabled)
  209. return;
  210. EngineType = Name;
  211. RegionName = scene.RegionInfo.RegionName;
  212. PhysicsSceneName = EngineType + "/" + RegionName;
  213. EngineName = Name + " " + Version;
  214. scene.RegisterModuleInterface<PhysicsScene>(this);
  215. Vector3 extent = new Vector3(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY, scene.RegionInfo.RegionSizeZ);
  216. Initialise(m_Config, extent);
  217. base.Initialise(scene.PhysicsRequestAsset,
  218. (scene.Heightmap != null ? scene.Heightmap.GetFloatsSerialised() : new float[scene.RegionInfo.RegionSizeX * scene.RegionInfo.RegionSizeY]),
  219. (float)scene.RegionInfo.RegionSettings.WaterHeight);
  220. }
  221. public void RemoveRegion(Scene scene)
  222. {
  223. if (!m_Enabled)
  224. return;
  225. }
  226. public void RegionLoaded(Scene scene)
  227. {
  228. if (!m_Enabled)
  229. return;
  230. mesher = scene.RequestModuleInterface<IMesher>();
  231. if (mesher == null)
  232. m_log.WarnFormat("{0} No mesher. Things will not work well.", LogHeader);
  233. scene.PhysicsEnabled = true;
  234. }
  235. #endregion
  236. #region Initialization
  237. private void Initialise(IConfigSource config, Vector3 regionExtent)
  238. {
  239. _taintOperations = new List<TaintCallbackEntry>();
  240. _postTaintOperations = new Dictionary<string, TaintCallbackEntry>();
  241. _postStepOperations = new List<TaintCallbackEntry>();
  242. PhysObjects = new Dictionary<uint, BSPhysObject>();
  243. Shapes = new BSShapeCollection(this);
  244. m_simulatedTime = 0f;
  245. LastTimeStep = 0.1f;
  246. // Allocate pinned memory to pass parameters.
  247. UnmanagedParams = new ConfigurationParameters[1];
  248. // Set default values for physics parameters plus any overrides from the ini file
  249. GetInitialParameterValues(config);
  250. // Force some parameters to values depending on other configurations
  251. // Only use heightmap terrain implementation if terrain larger than legacy size
  252. if ((uint)regionExtent.X > Constants.RegionSize || (uint)regionExtent.Y > Constants.RegionSize)
  253. {
  254. m_log.WarnFormat("{0} Forcing terrain implementation to heightmap for large region", LogHeader);
  255. BSParam.TerrainImplementation = (float)BSTerrainPhys.TerrainImplementation.Heightmap;
  256. }
  257. // Get the connection to the physics engine (could be native or one of many DLLs)
  258. PE = SelectUnderlyingBulletEngine(BulletEngineName);
  259. // Enable very detailed logging.
  260. // By creating an empty logger when not logging, the log message invocation code
  261. // can be left in and every call doesn't have to check for null.
  262. if (m_physicsLoggingEnabled)
  263. {
  264. PhysicsLogging = new LogWriter(m_physicsLoggingDir, m_physicsLoggingPrefix, m_physicsLoggingFileMinutes, m_physicsLoggingDoFlush);
  265. PhysicsLogging.ErrorLogger = m_log; // for DEBUG. Let's the logger output its own error messages.
  266. }
  267. else
  268. {
  269. PhysicsLogging = new LogWriter();
  270. }
  271. // Allocate memory for returning of the updates and collisions from the physics engine
  272. m_collisionArray = new CollisionDesc[m_maxCollisionsPerFrame];
  273. m_updateArray = new EntityProperties[m_maxUpdatesPerFrame];
  274. // The bounding box for the simulated world. The origin is 0,0,0 unless we're
  275. // a child in a mega-region.
  276. // Bullet actually doesn't care about the extents of the simulated
  277. // area. It tracks active objects no matter where they are.
  278. Vector3 worldExtent = regionExtent;
  279. World = PE.Initialize(worldExtent, Params, m_maxCollisionsPerFrame, ref m_collisionArray, m_maxUpdatesPerFrame, ref m_updateArray);
  280. Constraints = new BSConstraintCollection(World);
  281. TerrainManager = new BSTerrainManager(this, worldExtent);
  282. TerrainManager.CreateInitialGroundPlaneAndTerrain();
  283. // Put some informational messages into the log file.
  284. m_log.InfoFormat("{0} Linksets implemented with {1}", LogHeader, (BSLinkset.LinksetImplementation)BSParam.LinksetImplementation);
  285. InSimulationTime = false;
  286. m_initialized = true;
  287. // If the physics engine runs on its own thread, start same.
  288. if (BSParam.UseSeparatePhysicsThread)
  289. {
  290. // The physics simulation should happen independently of the heartbeat loop
  291. m_physicsThread = WorkManager.StartThread(
  292. BulletSPluginPhysicsThread,
  293. string.Format("{0} ({1})", BulletEngineName, RegionName));
  294. }
  295. }
  296. // All default parameter values are set here. There should be no values set in the
  297. // variable definitions.
  298. private void GetInitialParameterValues(IConfigSource config)
  299. {
  300. ConfigurationParameters parms = new ConfigurationParameters();
  301. UnmanagedParams[0] = parms;
  302. BSParam.SetParameterDefaultValues(this);
  303. if (config != null)
  304. {
  305. // If there are specifications in the ini file, use those values
  306. IConfig pConfig = config.Configs["BulletSim"];
  307. if (pConfig != null)
  308. {
  309. BSParam.SetParameterConfigurationValues(this, pConfig);
  310. // There are two Bullet implementations to choose from
  311. BulletEngineName = pConfig.GetString("BulletEngine", "BulletUnmanaged");
  312. // Very detailed logging for physics debugging
  313. // TODO: the boolean values can be moved to the normal parameter processing.
  314. m_physicsLoggingEnabled = pConfig.GetBoolean("PhysicsLoggingEnabled", false);
  315. m_physicsLoggingDir = pConfig.GetString("PhysicsLoggingDir", ".");
  316. m_physicsLoggingPrefix = pConfig.GetString("PhysicsLoggingPrefix", "physics-%REGIONNAME%-");
  317. m_physicsLoggingFileMinutes = pConfig.GetInt("PhysicsLoggingFileMinutes", 5);
  318. m_physicsLoggingDoFlush = pConfig.GetBoolean("PhysicsLoggingDoFlush", false);
  319. m_physicsPhysicalDumpEnabled = pConfig.GetBoolean("PhysicsPhysicalDumpEnabled", false);
  320. // Very detailed logging for vehicle debugging
  321. VehicleLoggingEnabled = pConfig.GetBoolean("VehicleLoggingEnabled", false);
  322. VehiclePhysicalLoggingEnabled = pConfig.GetBoolean("VehiclePhysicalLoggingEnabled", false);
  323. // Do any replacements in the parameters
  324. m_physicsLoggingPrefix = m_physicsLoggingPrefix.Replace("%REGIONNAME%", RegionName);
  325. }
  326. else
  327. {
  328. // Nothing in the configuration INI file so assume unmanaged and other defaults.
  329. BulletEngineName = "BulletUnmanaged";
  330. m_physicsLoggingEnabled = false;
  331. VehicleLoggingEnabled = false;
  332. }
  333. // The material characteristics.
  334. BSMaterials.InitializeFromDefaults(Params);
  335. if (pConfig != null)
  336. {
  337. // Let the user add new and interesting material property values.
  338. BSMaterials.InitializefromParameters(pConfig);
  339. }
  340. }
  341. }
  342. // A helper function that handles a true/false parameter and returns the proper float number encoding
  343. float ParamBoolean(IConfig config, string parmName, float deflt)
  344. {
  345. float ret = deflt;
  346. if (config.Contains(parmName))
  347. {
  348. ret = ConfigurationParameters.numericFalse;
  349. if (config.GetBoolean(parmName, false))
  350. {
  351. ret = ConfigurationParameters.numericTrue;
  352. }
  353. }
  354. return ret;
  355. }
  356. // Select the connection to the actual Bullet implementation.
  357. // The main engine selection is the engineName up to the first hypen.
  358. // So "Bullet-2.80-OpenCL-Intel" specifies the 'bullet' class here and the whole name
  359. // is passed to the engine to do its special selection, etc.
  360. private BSAPITemplate SelectUnderlyingBulletEngine(string engineName)
  361. {
  362. // For the moment, do a simple switch statement.
  363. // Someday do fancyness with looking up the interfaces in the assembly.
  364. BSAPITemplate ret = null;
  365. string selectionName = engineName.ToLower();
  366. int hyphenIndex = engineName.IndexOf("-");
  367. if (hyphenIndex > 0)
  368. selectionName = engineName.ToLower().Substring(0, hyphenIndex - 1);
  369. switch (selectionName)
  370. {
  371. case "bullet":
  372. case "bulletunmanaged":
  373. ret = new BSAPIUnman(engineName, this);
  374. break;
  375. case "bulletxna":
  376. ret = new BSAPIXNA(engineName, this);
  377. // Disable some features that are not implemented in BulletXNA
  378. m_log.InfoFormat("{0} Disabling some physics features not implemented by BulletXNA", LogHeader);
  379. m_log.InfoFormat("{0} Disabling ShouldUseBulletHACD", LogHeader);
  380. BSParam.ShouldUseBulletHACD = false;
  381. m_log.InfoFormat("{0} Disabling ShouldUseSingleConvexHullForPrims", LogHeader);
  382. BSParam.ShouldUseSingleConvexHullForPrims = false;
  383. m_log.InfoFormat("{0} Disabling ShouldUseGImpactShapeForPrims", LogHeader);
  384. BSParam.ShouldUseGImpactShapeForPrims = false;
  385. m_log.InfoFormat("{0} Setting terrain implimentation to Heightmap", LogHeader);
  386. BSParam.TerrainImplementation = (float)BSTerrainPhys.TerrainImplementation.Heightmap;
  387. break;
  388. }
  389. if (ret == null)
  390. {
  391. m_log.ErrorFormat("{0} COULD NOT SELECT BULLET ENGINE: '[BulletSim]PhysicsEngine' must be either 'BulletUnmanaged-*' or 'BulletXNA-*'", LogHeader);
  392. }
  393. else
  394. {
  395. m_log.InfoFormat("{0} Selected bullet engine {1} -> {2}/{3}", LogHeader, engineName, ret.BulletEngineName, ret.BulletEngineVersion);
  396. }
  397. return ret;
  398. }
  399. public override void Dispose()
  400. {
  401. // m_log.DebugFormat("{0}: Dispose()", LogHeader);
  402. // make sure no stepping happens while we're deleting stuff
  403. m_initialized = false;
  404. lock (PhysObjects)
  405. {
  406. foreach (KeyValuePair<uint, BSPhysObject> kvp in PhysObjects)
  407. {
  408. kvp.Value.Destroy();
  409. }
  410. PhysObjects.Clear();
  411. }
  412. // Now that the prims are all cleaned up, there should be no constraints left
  413. if (Constraints != null)
  414. {
  415. Constraints.Dispose();
  416. Constraints = null;
  417. }
  418. if (Shapes != null)
  419. {
  420. Shapes.Dispose();
  421. Shapes = null;
  422. }
  423. if (TerrainManager != null)
  424. {
  425. TerrainManager.ReleaseGroundPlaneAndTerrain();
  426. TerrainManager.Dispose();
  427. TerrainManager = null;
  428. }
  429. // Anything left in the unmanaged code should be cleaned out
  430. PE.Shutdown(World);
  431. // Not logging any more
  432. PhysicsLogging.Close();
  433. }
  434. #endregion // Construction and Initialization
  435. #region Prim and Avatar addition and removal
  436. public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 velocity, Vector3 size, bool isFlying)
  437. {
  438. m_log.ErrorFormat("{0}: CALL TO AddAvatar in BSScene. NOT IMPLEMENTED", LogHeader);
  439. return null;
  440. }
  441. public override PhysicsActor AddAvatar(uint localID, string avName, Vector3 position, Vector3 size, float footOffset, bool isFlying)
  442. {
  443. // m_log.DebugFormat("{0}: AddAvatar: {1}", LogHeader, avName);
  444. if (!m_initialized) return null;
  445. BSCharacter actor = new BSCharacter(localID, avName, this, position, Vector3.Zero, size, footOffset, isFlying);
  446. lock (PhysObjects)
  447. PhysObjects.Add(localID, actor);
  448. // TODO: Remove kludge someday.
  449. // We must generate a collision for avatars whether they collide or not.
  450. // This is required by OpenSim to update avatar animations, etc.
  451. lock (AvatarsInSceneLock)
  452. AvatarsInScene.Add(actor);
  453. return actor;
  454. }
  455. public override void RemoveAvatar(PhysicsActor actor)
  456. {
  457. // m_log.DebugFormat("{0}: RemoveAvatar", LogHeader);
  458. if (!m_initialized) return;
  459. BSCharacter bsactor = actor as BSCharacter;
  460. if (bsactor != null)
  461. {
  462. try
  463. {
  464. lock (PhysObjects)
  465. PhysObjects.Remove(bsactor.LocalID);
  466. // Remove kludge someday
  467. lock (AvatarsInSceneLock)
  468. AvatarsInScene.Remove(bsactor);
  469. }
  470. catch (Exception e)
  471. {
  472. m_log.WarnFormat("{0}: Attempt to remove avatar that is not in physics scene: {1}", LogHeader, e);
  473. }
  474. bsactor.Destroy();
  475. // bsactor.dispose();
  476. }
  477. else
  478. {
  479. m_log.ErrorFormat("{0}: Requested to remove avatar that is not a BSCharacter. ID={1}, type={2}",
  480. LogHeader, actor.LocalID, actor.GetType().Name);
  481. }
  482. }
  483. public override void RemovePrim(PhysicsActor prim)
  484. {
  485. if (!m_initialized) return;
  486. BSPhysObject bsprim = prim as BSPhysObject;
  487. if (bsprim != null)
  488. {
  489. DetailLog("{0},RemovePrim,call", bsprim.LocalID);
  490. // m_log.DebugFormat("{0}: RemovePrim. id={1}/{2}", LogHeader, bsprim.Name, bsprim.LocalID);
  491. try
  492. {
  493. lock (PhysObjects) PhysObjects.Remove(bsprim.LocalID);
  494. }
  495. catch (Exception e)
  496. {
  497. m_log.ErrorFormat("{0}: Attempt to remove prim that is not in physics scene: {1}", LogHeader, e);
  498. }
  499. bsprim.Destroy();
  500. // bsprim.dispose();
  501. }
  502. else
  503. {
  504. m_log.ErrorFormat("{0}: Attempt to remove prim that is not a BSPrim type.", LogHeader);
  505. }
  506. }
  507. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  508. Vector3 size, Quaternion rotation, bool isPhysical, uint localID)
  509. {
  510. // m_log.DebugFormat("{0}: AddPrimShape2: {1}", LogHeader, primName);
  511. if (!m_initialized) return null;
  512. // DetailLog("{0},BSScene.AddPrimShape,call", localID);
  513. BSPhysObject prim = new BSPrimLinkable(localID, primName, this, position, size, rotation, pbs, isPhysical);
  514. lock (PhysObjects) PhysObjects.Add(localID, prim);
  515. return prim;
  516. }
  517. // This is a call from the simulator saying that some physical property has been updated.
  518. // The BulletSim driver senses the changing of relevant properties so this taint
  519. // information call is not needed.
  520. public override void AddPhysicsActorTaint(PhysicsActor prim) { }
  521. #endregion // Prim and Avatar addition and removal
  522. #region Simulation
  523. // Call from the simulator to send physics information to the simulator objects.
  524. // This pushes all the collision and property update events into the objects in
  525. // the simulator and, since it is on the heartbeat thread, there is an implicit
  526. // locking of those data structures from other heartbeat events.
  527. // If the physics engine is running on a separate thread, the update information
  528. // will be in the ObjectsWithCollions and ObjectsWithUpdates structures.
  529. public override float Simulate(float timeStep)
  530. {
  531. if (!BSParam.UseSeparatePhysicsThread)
  532. {
  533. DoPhysicsStep(timeStep);
  534. }
  535. return SendUpdatesToSimulator(timeStep);
  536. }
  537. // Call the physics engine to do one 'timeStep' and collect collisions and updates
  538. // into ObjectsWithCollisions and ObjectsWithUpdates data structures.
  539. private void DoPhysicsStep(float timeStep)
  540. {
  541. // prevent simulation until we've been initialized
  542. if (!m_initialized) return;
  543. LastTimeStep = timeStep;
  544. int updatedEntityCount = 0;
  545. int collidersCount = 0;
  546. int beforeTime = Util.EnvironmentTickCount();
  547. int simTime = 0;
  548. int numTaints = 0;
  549. int numSubSteps = 0;
  550. lock (PhysicsEngineLock)
  551. {
  552. InSimulationTime = true;
  553. // update the prim states while we know the physics engine is not busy
  554. numTaints += ProcessTaints();
  555. // Some of the physical objects requre individual, pre-step calls
  556. // (vehicles and avatar movement, in particular)
  557. TriggerPreStepEvent(timeStep);
  558. // the prestep actions might have added taints
  559. numTaints += ProcessTaints();
  560. // The following causes the unmanaged code to output ALL the values found in ALL the objects in the world.
  561. // Only enable this in a limited test world with few objects.
  562. if (m_physicsPhysicalDumpEnabled)
  563. PE.DumpAllInfo(World);
  564. // step the physical world one interval
  565. m_simulationStep++;
  566. try
  567. {
  568. numSubSteps = PE.PhysicsStep(World, timeStep, m_maxSubSteps, m_fixedTimeStep, out updatedEntityCount, out collidersCount);
  569. }
  570. catch (Exception e)
  571. {
  572. m_log.WarnFormat("{0},PhysicsStep Exception: nTaints={1}, substeps={2}, updates={3}, colliders={4}, e={5}",
  573. LogHeader, numTaints, numSubSteps, updatedEntityCount, collidersCount, e);
  574. DetailLog("{0},PhysicsStepException,call, nTaints={1}, substeps={2}, updates={3}, colliders={4}",
  575. DetailLogZero, numTaints, numSubSteps, updatedEntityCount, collidersCount);
  576. updatedEntityCount = 0;
  577. collidersCount = 0;
  578. }
  579. // Make the physics engine dump useful statistics periodically
  580. if (PhysicsMetricDumpFrames != 0 && ((m_simulationStep % PhysicsMetricDumpFrames) == 0))
  581. PE.DumpPhysicsStatistics(World);
  582. InSimulationTime = false;
  583. // Some actors want to know when the simulation step is complete.
  584. TriggerPostStepEvent(timeStep);
  585. // In case there were any parameter updates that happened during the simulation step
  586. numTaints += ProcessTaints();
  587. InSimulationTime = false;
  588. }
  589. // Get a value for 'now' so all the collision and update routines don't have to get their own.
  590. SimulationNowTime = Util.EnvironmentTickCount();
  591. // Send collision information to the colliding objects. The objects decide if the collision
  592. // is 'real' (like linksets don't collide with themselves) and the individual objects
  593. // know if the simulator has subscribed to collisions.
  594. lock (CollisionLock)
  595. {
  596. if (collidersCount > 0)
  597. {
  598. lock (PhysObjects)
  599. {
  600. for (int ii = 0; ii < collidersCount; ii++)
  601. {
  602. uint cA = m_collisionArray[ii].aID;
  603. uint cB = m_collisionArray[ii].bID;
  604. Vector3 point = m_collisionArray[ii].point;
  605. Vector3 normal = m_collisionArray[ii].normal;
  606. float penetration = m_collisionArray[ii].penetration;
  607. SendCollision(cA, cB, point, normal, penetration);
  608. SendCollision(cB, cA, point, -normal, penetration);
  609. }
  610. }
  611. }
  612. }
  613. // If any of the objects had updated properties, tell the managed objects about the update
  614. // and remember that there was a change so it will be passed to the simulator.
  615. lock (UpdateLock)
  616. {
  617. if (updatedEntityCount > 0)
  618. {
  619. lock (PhysObjects)
  620. {
  621. for (int ii = 0; ii < updatedEntityCount; ii++)
  622. {
  623. EntityProperties entprop = m_updateArray[ii];
  624. BSPhysObject pobj;
  625. if (PhysObjects.TryGetValue(entprop.ID, out pobj))
  626. {
  627. if (pobj.IsInitialized)
  628. pobj.UpdateProperties(entprop);
  629. }
  630. }
  631. }
  632. }
  633. }
  634. simTime = Util.EnvironmentTickCountSubtract(beforeTime);
  635. if (PhysicsLogging.Enabled)
  636. {
  637. DetailLog("{0},DoPhysicsStep,complete,frame={1}, nTaints={2}, simTime={3}, substeps={4}, updates={5}, colliders={6}, objWColl={7}",
  638. DetailLogZero, m_simulationStep, numTaints, simTime, numSubSteps,
  639. updatedEntityCount, collidersCount, ObjectsWithCollisions.Count);
  640. }
  641. // The following causes the unmanaged code to output ALL the values found in ALL the objects in the world.
  642. // Only enable this in a limited test world with few objects.
  643. if (m_physicsPhysicalDumpEnabled)
  644. PE.DumpAllInfo(World);
  645. // The physics engine returns the number of milliseconds it simulated this call.
  646. // These are summed and normalized to one second and divided by 1000 to give the reported physics FPS.
  647. // Multiply by a fixed nominal frame rate to give a rate similar to the simulator (usually 55).
  648. // m_simulatedTime += (float)numSubSteps * m_fixedTimeStep * 1000f * NominalFrameRate;
  649. m_simulatedTime += (float)numSubSteps * m_fixedTimeStep;
  650. }
  651. // Called by a BSPhysObject to note that it has changed properties and this information
  652. // should be passed up to the simulator at the proper time.
  653. // Note: this is called by the BSPhysObject from invocation via DoPhysicsStep() above so
  654. // this is is under UpdateLock.
  655. public void PostUpdate(BSPhysObject updatee)
  656. {
  657. lock (UpdateLock)
  658. {
  659. ObjectsWithUpdates.Add(updatee);
  660. }
  661. }
  662. // The simulator thinks it is physics time so return all the collisions and position
  663. // updates that were collected in actual physics simulation.
  664. private float SendUpdatesToSimulator(float timeStep)
  665. {
  666. if (!m_initialized) return 5.0f;
  667. DetailLog("{0},SendUpdatesToSimulator,collisions={1},updates={2},simedTime={3}",
  668. BSScene.DetailLogZero, ObjectsWithCollisions.Count, ObjectsWithUpdates.Count, m_simulatedTime);
  669. // Push the collisions into the simulator.
  670. lock (CollisionLock)
  671. {
  672. if (ObjectsWithCollisions.Count > 0)
  673. {
  674. foreach (BSPhysObject bsp in ObjectsWithCollisions)
  675. if (!bsp.SendCollisions())
  676. {
  677. // If the object is done colliding, see that it's removed from the colliding list
  678. ObjectsWithNoMoreCollisions.Add(bsp);
  679. }
  680. }
  681. // This is a kludge to get avatar movement updates.
  682. // The simulator expects collisions for avatars even if there are have been no collisions.
  683. // The event updates avatar animations and stuff.
  684. // If you fix avatar animation updates, remove this overhead and let normal collision processing happen.
  685. // Note that we get a copy of the list to search because SendCollision() can take a while.
  686. HashSet<BSPhysObject> tempAvatarsInScene;
  687. lock (AvatarsInSceneLock)
  688. {
  689. tempAvatarsInScene = new HashSet<BSPhysObject>(AvatarsInScene);
  690. }
  691. foreach (BSPhysObject actor in tempAvatarsInScene)
  692. {
  693. if (!ObjectsWithCollisions.Contains(actor)) // don't call avatars twice
  694. actor.SendCollisions();
  695. }
  696. tempAvatarsInScene = null;
  697. // Objects that are done colliding are removed from the ObjectsWithCollisions list.
  698. // Not done above because it is inside an iteration of ObjectWithCollisions.
  699. // This complex collision processing is required to create an empty collision
  700. // event call after all real collisions have happened on an object. This allows
  701. // the simulator to generate the 'collision end' event.
  702. if (ObjectsWithNoMoreCollisions.Count > 0)
  703. {
  704. foreach (BSPhysObject po in ObjectsWithNoMoreCollisions)
  705. ObjectsWithCollisions.Remove(po);
  706. ObjectsWithNoMoreCollisions.Clear();
  707. }
  708. }
  709. // Call the simulator for each object that has physics property updates.
  710. HashSet<BSPhysObject> updatedObjects = null;
  711. lock (UpdateLock)
  712. {
  713. if (ObjectsWithUpdates.Count > 0)
  714. {
  715. updatedObjects = ObjectsWithUpdates;
  716. ObjectsWithUpdates = new HashSet<BSPhysObject>();
  717. }
  718. }
  719. if (updatedObjects != null)
  720. {
  721. foreach (BSPhysObject obj in updatedObjects)
  722. {
  723. obj.RequestPhysicsterseUpdate();
  724. }
  725. updatedObjects.Clear();
  726. }
  727. // Return the framerate simulated to give the above returned results.
  728. // (Race condition here but this is just bookkeeping so rare mistakes do not merit a lock).
  729. float simTime = m_simulatedTime / timeStep;
  730. m_simulatedTime = 0f;
  731. return simTime;
  732. }
  733. // Something has collided
  734. private void SendCollision(uint localID, uint collidingWith, Vector3 collidePoint, Vector3 collideNormal, float penetration)
  735. {
  736. if (localID <= TerrainManager.HighestTerrainID)
  737. {
  738. return; // don't send collisions to the terrain
  739. }
  740. BSPhysObject collider;
  741. // NOTE that PhysObjects was locked before the call to SendCollision().
  742. if (!PhysObjects.TryGetValue(localID, out collider))
  743. {
  744. // If the object that is colliding cannot be found, just ignore the collision.
  745. DetailLog("{0},BSScene.SendCollision,colliderNotInObjectList,id={1},with={2}", DetailLogZero, localID, collidingWith);
  746. return;
  747. }
  748. // Note: the terrain is not in the physical object list so 'collidee' can be null when Collide() is called.
  749. BSPhysObject collidee = null;
  750. PhysObjects.TryGetValue(collidingWith, out collidee);
  751. // DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith);
  752. if (collider.IsInitialized)
  753. {
  754. if (collider.Collide(collidee, collidePoint, collideNormal, penetration))
  755. {
  756. // If a collision was 'good', remember to send it to the simulator
  757. lock (CollisionLock)
  758. {
  759. ObjectsWithCollisions.Add(collider);
  760. }
  761. }
  762. }
  763. return;
  764. }
  765. public void BulletSPluginPhysicsThread()
  766. {
  767. m_updateWaitEvent = new ManualResetEvent(false);
  768. while (m_initialized)
  769. {
  770. int beginSimulationRealtimeMS = Util.EnvironmentTickCount();
  771. if (BSParam.Active)
  772. DoPhysicsStep(BSParam.PhysicsTimeStep);
  773. int simulationRealtimeMS = Util.EnvironmentTickCountSubtract(beginSimulationRealtimeMS);
  774. int simulationTimeVsRealtimeDifferenceMS = ((int)(BSParam.PhysicsTimeStep*1000f)) - simulationRealtimeMS;
  775. if (simulationTimeVsRealtimeDifferenceMS > 0)
  776. {
  777. // The simulation of the time interval took less than realtime.
  778. // Do a wait for the rest of realtime.
  779. m_updateWaitEvent.WaitOne(simulationTimeVsRealtimeDifferenceMS);
  780. //Thread.Sleep(simulationTimeVsRealtimeDifferenceMS);
  781. }
  782. else
  783. {
  784. // The simulation took longer than realtime.
  785. // Do some scaling of simulation time.
  786. // TODO.
  787. DetailLog("{0},BulletSPluginPhysicsThread,longerThanRealtime={1}", BSScene.DetailLogZero, simulationTimeVsRealtimeDifferenceMS);
  788. }
  789. Watchdog.UpdateThread();
  790. }
  791. Watchdog.RemoveThread();
  792. }
  793. #endregion // Simulation
  794. #region Terrain
  795. public override void SetTerrain(float[] heightMap) {
  796. TerrainManager.SetTerrain(heightMap);
  797. }
  798. public override void SetWaterLevel(float baseheight)
  799. {
  800. SimpleWaterLevel = baseheight;
  801. }
  802. public override void DeleteTerrain()
  803. {
  804. // m_log.DebugFormat("{0}: DeleteTerrain()", LogHeader);
  805. }
  806. #endregion // Terrain
  807. #region Raycast
  808. public override bool SupportsRayCast()
  809. {
  810. return BSParam.UseBulletRaycast;
  811. }
  812. public override bool SupportsRaycastWorldFiltered()
  813. {
  814. return BSParam.UseBulletRaycast;
  815. }
  816. /// <summary>
  817. /// Queue a raycast against the physics scene.
  818. /// The provided callback method will be called when the raycast is complete
  819. ///
  820. /// Many physics engines don't support collision testing at the same time as
  821. /// manipulating the physics scene, so we queue the request up and callback
  822. /// a custom method when the raycast is complete.
  823. /// This allows physics engines that give an immediate result to callback immediately
  824. /// and ones that don't, to callback when it gets a result back.
  825. /// public delegate void RayCallback(List<ContactResult> list);
  826. ///
  827. /// ODE for example will not allow you to change the scene while collision testing or
  828. /// it asserts, 'opteration not valid for locked space'. This includes adding a ray to the scene.
  829. ///
  830. /// This is named RayCastWorld to not conflict with modrex's Raycast method.
  831. /// </summary>
  832. /// <param name="position">Origin of the ray</param>
  833. /// <param name="direction">Direction of the ray</param>
  834. /// <param name="length">Length of ray in meters</param>
  835. /// <param name="retMethod">Method to call when the raycast is complete</param>
  836. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod)
  837. {
  838. if (retMethod != null)
  839. {
  840. if (BSParam.UseBulletRaycast)
  841. {
  842. Vector3 posFrom = position;
  843. Vector3 posTo = Vector3.Normalize(direction) * length + position;
  844. TaintedObject(DetailLogZero, "BSScene.RaycastWorld1", delegate ()
  845. {
  846. RaycastHit hitInfo = PE.RayTest2(World, posFrom, posTo, 0xffff, 0xffff);
  847. retMethod(true, hitInfo.Point, hitInfo.ID, hitInfo.Fraction, hitInfo.Normal);
  848. });
  849. }
  850. else
  851. {
  852. retMethod(false, Vector3.Zero, 0, 999999999999f, Vector3.Zero);
  853. }
  854. }
  855. }
  856. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, int count, RayCallback retMethod)
  857. {
  858. if (retMethod != null)
  859. {
  860. if (BSParam.UseBulletRaycast)
  861. {
  862. List<ContactResult> hitInfo = RaycastWorld(position, direction, length, count);
  863. retMethod(hitInfo);
  864. }
  865. else
  866. {
  867. retMethod(new List<ContactResult>());
  868. }
  869. }
  870. }
  871. public override List<ContactResult> RaycastWorld(Vector3 position, Vector3 direction, float length, int count)
  872. {
  873. return (List<ContactResult>)RaycastWorld(position, direction, length, count, RayFilterFlags.All);
  874. }
  875. public override object RaycastWorld(Vector3 position, Vector3 direction, float length, int count, RayFilterFlags filter)
  876. {
  877. List<ContactResult> ret = new List<ContactResult>();
  878. if (BSParam.UseBulletRaycast)
  879. {
  880. uint collisionFilter = 0;
  881. uint collisionMask = 0;
  882. if ((filter & RayFilterFlags.land) != 0)
  883. {
  884. collisionFilter |= BulletSimData.CollisionTypeMasks[CollisionType.Terrain].group;
  885. collisionMask |= BulletSimData.CollisionTypeMasks[CollisionType.Terrain].mask;
  886. }
  887. if ((filter & RayFilterFlags.agent) != 0)
  888. {
  889. collisionFilter |= BulletSimData.CollisionTypeMasks[CollisionType.Avatar].group;
  890. collisionMask |= BulletSimData.CollisionTypeMasks[CollisionType.Avatar].mask;
  891. }
  892. if ((filter & RayFilterFlags.nonphysical) != 0)
  893. {
  894. collisionFilter |= BulletSimData.CollisionTypeMasks[CollisionType.Static].group;
  895. collisionMask |= BulletSimData.CollisionTypeMasks[CollisionType.Static].mask;
  896. }
  897. if ((filter & RayFilterFlags.physical) != 0)
  898. {
  899. collisionFilter |= BulletSimData.CollisionTypeMasks[CollisionType.Dynamic].group;
  900. collisionMask |= BulletSimData.CollisionTypeMasks[CollisionType.Dynamic].mask;
  901. }
  902. // if ((filter & RayFilterFlags.phantom) != 0)
  903. // {
  904. // collisionFilter |= BulletSimData.CollisionTypeMasks[CollisionType.VolumeDetect].group;
  905. // collisionMask |= BulletSimData.CollisionTypeMasks[CollisionType.VolumeDetect].mask;
  906. // }
  907. if ((filter & RayFilterFlags.volumedtc) != 0)
  908. {
  909. collisionFilter |= BulletSimData.CollisionTypeMasks[CollisionType.VolumeDetect].group;
  910. collisionMask |= BulletSimData.CollisionTypeMasks[CollisionType.VolumeDetect].mask;
  911. }
  912. DetailLog("{0},RaycastWorld,pos={1},dir={2},len={3},count={4},filter={5},filter={6},mask={7}",
  913. DetailLogZero, position, direction, length, count, filter, collisionFilter, collisionMask);
  914. // NOTE: locking ensures the physics engine is not executing.
  915. // The caller might have to wait for the physics engine to finish.
  916. lock (PhysicsEngineLock)
  917. {
  918. Vector3 posFrom = position;
  919. Vector3 posTo = Vector3.Normalize(direction) * length + position;
  920. DetailLog("{0},RaycastWorld,RayTest2,from={1},to={2}",
  921. DetailLogZero, posFrom, posTo);
  922. RaycastHit hitInfo = PE.RayTest2(World, posFrom, posTo, collisionFilter, collisionMask);
  923. if (hitInfo.hasHit())
  924. {
  925. ContactResult result = new ContactResult();
  926. result.Pos = hitInfo.Point;
  927. result.Normal = hitInfo.Normal;
  928. result.ConsumerID = hitInfo.ID;
  929. result.Depth = hitInfo.Fraction;
  930. ret.Add(result);
  931. DetailLog("{0},RaycastWorld,hit,pos={1},norm={2},depth={3},id={4}",
  932. DetailLogZero, result.Pos, result.Normal, result.Depth, result.ConsumerID);
  933. }
  934. }
  935. }
  936. return ret;
  937. }
  938. #endregion Raycast
  939. public override Dictionary<uint, float> GetTopColliders()
  940. {
  941. Dictionary<uint, float> topColliders;
  942. lock (PhysObjects)
  943. {
  944. foreach (KeyValuePair<uint, BSPhysObject> kvp in PhysObjects)
  945. {
  946. kvp.Value.ComputeCollisionScore();
  947. }
  948. List<BSPhysObject> orderedPrims = new List<BSPhysObject>(PhysObjects.Values);
  949. orderedPrims.OrderByDescending(p => p.CollisionScore);
  950. topColliders = orderedPrims.Take(25).ToDictionary(p => p.LocalID, p => p.CollisionScore);
  951. }
  952. return topColliders;
  953. }
  954. #region Extensions
  955. public override object Extension(string pFunct, params object[] pParams)
  956. {
  957. DetailLog("{0} BSScene.Extension,op={1}", DetailLogZero, pFunct);
  958. return base.Extension(pFunct, pParams);
  959. }
  960. #endregion // Extensions
  961. public static string PrimitiveBaseShapeToString(PrimitiveBaseShape pbs)
  962. {
  963. float pathShearX = pbs.PathShearX < 128 ? (float)pbs.PathShearX * 0.01f : (float)(pbs.PathShearX - 256) * 0.01f;
  964. float pathShearY = pbs.PathShearY < 128 ? (float)pbs.PathShearY * 0.01f : (float)(pbs.PathShearY - 256) * 0.01f;
  965. float pathBegin = (float)pbs.PathBegin * 2.0e-5f;
  966. float pathEnd = 1.0f - (float)pbs.PathEnd * 2.0e-5f;
  967. float pathScaleX = (float)(200 - pbs.PathScaleX) * 0.01f;
  968. float pathScaleY = (float)(200 - pbs.PathScaleY) * 0.01f;
  969. float pathTaperX = pbs.PathTaperX * 0.01f;
  970. float pathTaperY = pbs.PathTaperY * 0.01f;
  971. float profileBegin = (float)pbs.ProfileBegin * 2.0e-5f;
  972. float profileEnd = 1.0f - (float)pbs.ProfileEnd * 2.0e-5f;
  973. float profileHollow = (float)pbs.ProfileHollow * 2.0e-5f;
  974. if (profileHollow > 0.95f)
  975. profileHollow = 0.95f;
  976. StringBuilder buff = new StringBuilder();
  977. buff.Append("shape=");
  978. buff.Append(((ProfileShape)pbs.ProfileShape).ToString());
  979. buff.Append(",");
  980. buff.Append("hollow=");
  981. buff.Append(((HollowShape)pbs.HollowShape).ToString());
  982. buff.Append(",");
  983. buff.Append("pathCurve=");
  984. buff.Append(((Extrusion)pbs.PathCurve).ToString());
  985. buff.Append(",");
  986. buff.Append("profCurve=");
  987. buff.Append(((Extrusion)pbs.ProfileCurve).ToString());
  988. buff.Append(",");
  989. buff.Append("profHollow=");
  990. buff.Append(profileHollow.ToString());
  991. buff.Append(",");
  992. buff.Append("pathBegEnd=");
  993. buff.Append(pathBegin.ToString());
  994. buff.Append("/");
  995. buff.Append(pathEnd.ToString());
  996. buff.Append(",");
  997. buff.Append("profileBegEnd=");
  998. buff.Append(profileBegin.ToString());
  999. buff.Append("/");
  1000. buff.Append(profileEnd.ToString());
  1001. buff.Append(",");
  1002. buff.Append("scaleXY=");
  1003. buff.Append(pathScaleX.ToString());
  1004. buff.Append("/");
  1005. buff.Append(pathScaleY.ToString());
  1006. buff.Append(",");
  1007. buff.Append("shearXY=");
  1008. buff.Append(pathShearX.ToString());
  1009. buff.Append("/");
  1010. buff.Append(pathShearY.ToString());
  1011. buff.Append(",");
  1012. buff.Append("taperXY=");
  1013. buff.Append(pbs.PathTaperX.ToString());
  1014. buff.Append("/");
  1015. buff.Append(pbs.PathTaperY.ToString());
  1016. buff.Append(",");
  1017. buff.Append("skew=");
  1018. buff.Append(pbs.PathSkew.ToString());
  1019. buff.Append(",");
  1020. buff.Append("twist/Beg=");
  1021. buff.Append(pbs.PathTwist.ToString());
  1022. buff.Append("/");
  1023. buff.Append(pbs.PathTwistBegin.ToString());
  1024. return buff.ToString();
  1025. }
  1026. #region Taints
  1027. // The simulation execution order is:
  1028. // Simulate()
  1029. // DoOneTimeTaints
  1030. // TriggerPreStepEvent
  1031. // DoOneTimeTaints
  1032. // Step()
  1033. // ProcessAndSendToSimulatorCollisions
  1034. // ProcessAndSendToSimulatorPropertyUpdates
  1035. // TriggerPostStepEvent
  1036. // Calls to the PhysicsActors can't directly call into the physics engine
  1037. // because it might be busy. We delay changes to a known time.
  1038. // We rely on C#'s closure to save and restore the context for the delegate.
  1039. // NOTE: 'inTaintTime' is no longer used. This entry exists so all the calls don't have to be changed.
  1040. // public void TaintedObject(bool inTaintTime, String pIdent, TaintCallback pCallback)
  1041. // {
  1042. // TaintedObject(BSScene.DetailLogZero, pIdent, pCallback);
  1043. // }
  1044. // NOTE: 'inTaintTime' is no longer used. This entry exists so all the calls don't have to be changed.
  1045. public void TaintedObject(bool inTaintTime, uint pOriginator, String pIdent, TaintCallback pCallback)
  1046. {
  1047. TaintedObject(m_physicsLoggingEnabled ? pOriginator.ToString() : BSScene.DetailLogZero, pIdent, pCallback);
  1048. }
  1049. public void TaintedObject(uint pOriginator, String pIdent, TaintCallback pCallback)
  1050. {
  1051. TaintedObject(m_physicsLoggingEnabled ? pOriginator.ToString() : BSScene.DetailLogZero, pIdent, pCallback);
  1052. }
  1053. // Sometimes a potentially tainted operation can be used in and out of taint time.
  1054. // This routine executes the command immediately if in taint-time otherwise it is queued.
  1055. public void TaintedObject(string pOriginator, string pIdent, TaintCallback pCallback)
  1056. {
  1057. if (!m_initialized) return;
  1058. /* mantis 8397 ??? avoid out of order operations ???
  1059. if (Monitor.TryEnter(PhysicsEngineLock))
  1060. {
  1061. // If we can get exclusive access to the physics engine, just do the operation
  1062. pCallback();
  1063. Monitor.Exit(PhysicsEngineLock);
  1064. }
  1065. else
  1066. {
  1067. */
  1068. // The physics engine is busy, queue the operation
  1069. lock (_taintLock)
  1070. {
  1071. _taintOperations.Add(new TaintCallbackEntry(pOriginator, pIdent, pCallback));
  1072. }
  1073. // }
  1074. }
  1075. private void TriggerPreStepEvent(float timeStep)
  1076. {
  1077. PreStepAction actions = BeforeStep;
  1078. if (actions != null)
  1079. actions(timeStep);
  1080. }
  1081. private void TriggerPostStepEvent(float timeStep)
  1082. {
  1083. PostStepAction actions = AfterStep;
  1084. if (actions != null)
  1085. actions(timeStep);
  1086. }
  1087. // When someone tries to change a property on a BSPrim or BSCharacter, the object queues
  1088. // a callback into itself to do the actual property change. That callback is called
  1089. // here just before the physics engine is called to step the simulation.
  1090. // Returns the number of taints processed
  1091. // NOTE: Called while PhysicsEngineLock is locked
  1092. public int ProcessTaints()
  1093. {
  1094. int ret = 0;
  1095. ret += ProcessRegularTaints();
  1096. ret += ProcessPostTaintTaints();
  1097. return ret;
  1098. }
  1099. // Returns the number of taints processed
  1100. // NOTE: Called while PhysicsEngineLock is locked
  1101. private int ProcessRegularTaints()
  1102. {
  1103. int ret = 0;
  1104. if (m_initialized && _taintOperations.Count > 0) // save allocating new list if there is nothing to process
  1105. {
  1106. // swizzle a new list into the list location so we can process what's there
  1107. List<TaintCallbackEntry> oldList;
  1108. lock (_taintLock)
  1109. {
  1110. oldList = _taintOperations;
  1111. _taintOperations = new List<TaintCallbackEntry>();
  1112. }
  1113. foreach (TaintCallbackEntry tcbe in oldList)
  1114. {
  1115. try
  1116. {
  1117. DetailLog("{0},BSScene.ProcessTaints,doTaint,id={1}", tcbe.originator, tcbe.ident); // DEBUG DEBUG DEBUG
  1118. tcbe.callback();
  1119. ret++;
  1120. }
  1121. catch (Exception e)
  1122. {
  1123. m_log.ErrorFormat("{0}: ProcessTaints: {1}: Exception: {2}", LogHeader, tcbe.ident, e);
  1124. }
  1125. }
  1126. oldList.Clear();
  1127. }
  1128. return ret;
  1129. }
  1130. // Schedule an update to happen after all the regular taints are processed.
  1131. // Note that new requests for the same operation ("ident") for the same object ("ID")
  1132. // will replace any previous operation by the same object.
  1133. public void PostTaintObject(String ident, uint ID, TaintCallback callback)
  1134. {
  1135. string IDAsString = ID.ToString();
  1136. string uniqueIdent = ident + "-" + IDAsString;
  1137. lock (_taintLock)
  1138. {
  1139. _postTaintOperations[uniqueIdent] = new TaintCallbackEntry(IDAsString, uniqueIdent, callback);
  1140. }
  1141. return;
  1142. }
  1143. // Taints that happen after the normal taint processing but before the simulation step.
  1144. // Returns the number of taints processed
  1145. // NOTE: Called while PhysicsEngineLock is locked
  1146. private int ProcessPostTaintTaints()
  1147. {
  1148. int ret = 0;
  1149. if (m_initialized && _postTaintOperations.Count > 0)
  1150. {
  1151. Dictionary<string, TaintCallbackEntry> oldList;
  1152. lock (_taintLock)
  1153. {
  1154. oldList = _postTaintOperations;
  1155. _postTaintOperations = new Dictionary<string, TaintCallbackEntry>();
  1156. }
  1157. foreach (KeyValuePair<string,TaintCallbackEntry> kvp in oldList)
  1158. {
  1159. try
  1160. {
  1161. DetailLog("{0},BSScene.ProcessPostTaintTaints,doTaint,id={1}", DetailLogZero, kvp.Key); // DEBUG DEBUG DEBUG
  1162. kvp.Value.callback();
  1163. ret++;
  1164. }
  1165. catch (Exception e)
  1166. {
  1167. m_log.ErrorFormat("{0}: ProcessPostTaintTaints: {1}: Exception: {2}", LogHeader, kvp.Key, e);
  1168. }
  1169. }
  1170. oldList.Clear();
  1171. }
  1172. return ret;
  1173. }
  1174. #endregion // Taints
  1175. #region IPhysicsParameters
  1176. // Get the list of parameters this physics engine supports
  1177. public PhysParameterEntry[] GetParameterList()
  1178. {
  1179. BSParam.BuildParameterTable();
  1180. return BSParam.SettableParameters;
  1181. }
  1182. // Set parameter on a specific or all instances.
  1183. // Return 'false' if not able to set the parameter.
  1184. // Setting the value in the m_params block will change the value the physics engine
  1185. // will use the next time since it's pinned and shared memory.
  1186. // Some of the values require calling into the physics engine to get the new
  1187. // value activated ('terrainFriction' for instance).
  1188. public bool SetPhysicsParameter(string parm, string val, uint localID)
  1189. {
  1190. bool ret = false;
  1191. BSParam.ParameterDefnBase theParam;
  1192. if (BSParam.TryGetParameter(parm, out theParam))
  1193. {
  1194. // Set the value in the C# code
  1195. theParam.SetValue(this, val);
  1196. // Optionally set the parameter in the unmanaged code
  1197. if (theParam.HasSetOnObject)
  1198. {
  1199. // update all the localIDs specified
  1200. // If the local ID is APPLY_TO_NONE, just change the default value
  1201. // If the localID is APPLY_TO_ALL change the default value and apply the new value to all the lIDs
  1202. // If the localID is a specific object, apply the parameter change to only that object
  1203. List<uint> objectIDs = new List<uint>();
  1204. switch (localID)
  1205. {
  1206. case PhysParameterEntry.APPLY_TO_NONE:
  1207. // This will cause a call into the physical world if some operation is specified (SetOnObject).
  1208. objectIDs.Add(TERRAIN_ID);
  1209. TaintedUpdateParameter(parm, objectIDs, val);
  1210. break;
  1211. case PhysParameterEntry.APPLY_TO_ALL:
  1212. lock (PhysObjects) objectIDs = new List<uint>(PhysObjects.Keys);
  1213. TaintedUpdateParameter(parm, objectIDs, val);
  1214. break;
  1215. default:
  1216. // setting only one localID
  1217. objectIDs.Add(localID);
  1218. TaintedUpdateParameter(parm, objectIDs, val);
  1219. break;
  1220. }
  1221. }
  1222. ret = true;
  1223. }
  1224. return ret;
  1225. }
  1226. // schedule the actual updating of the paramter to when the phys engine is not busy
  1227. private void TaintedUpdateParameter(string parm, List<uint> lIDs, string val)
  1228. {
  1229. string xval = val;
  1230. List<uint> xlIDs = lIDs;
  1231. string xparm = parm;
  1232. TaintedObject(DetailLogZero, "BSScene.UpdateParameterSet", delegate() {
  1233. BSParam.ParameterDefnBase thisParam;
  1234. if (BSParam.TryGetParameter(xparm, out thisParam))
  1235. {
  1236. if (thisParam.HasSetOnObject)
  1237. {
  1238. foreach (uint lID in xlIDs)
  1239. {
  1240. BSPhysObject theObject = null;
  1241. if (PhysObjects.TryGetValue(lID, out theObject))
  1242. thisParam.SetOnObject(this, theObject);
  1243. }
  1244. }
  1245. }
  1246. });
  1247. }
  1248. // Get parameter.
  1249. // Return 'false' if not able to get the parameter.
  1250. public bool GetPhysicsParameter(string parm, out string value)
  1251. {
  1252. string val = String.Empty;
  1253. bool ret = false;
  1254. BSParam.ParameterDefnBase theParam;
  1255. if (BSParam.TryGetParameter(parm, out theParam))
  1256. {
  1257. val = theParam.GetValue(this);
  1258. ret = true;
  1259. }
  1260. value = val;
  1261. return ret;
  1262. }
  1263. #endregion IPhysicsParameters
  1264. // Invoke the detailed logger and output something if it's enabled.
  1265. public void DetailLog(string msg, params Object[] args)
  1266. {
  1267. PhysicsLogging.Write(msg, args);
  1268. }
  1269. // Used to fill in the LocalID when there isn't one. It's the correct number of characters.
  1270. public const string DetailLogZero = "0000000000";
  1271. }
  1272. }