BSScene.cs 63 KB

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