BSScene.cs 56 KB

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