BSScene.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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.Region.Framework;
  36. using OpenSim.Region.CoreModules;
  37. using Logging = OpenSim.Region.CoreModules.Framework.Statistics.Logging;
  38. using OpenSim.Region.Physics.Manager;
  39. using Nini.Config;
  40. using log4net;
  41. using OpenMetaverse;
  42. namespace OpenSim.Region.Physics.BulletSPlugin
  43. {
  44. public sealed class BSScene : PhysicsScene, IPhysicsParameters
  45. {
  46. internal static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  47. internal static readonly string LogHeader = "[BULLETS SCENE]";
  48. // The name of the region we're working for.
  49. public string RegionName { get; private set; }
  50. public string BulletSimVersion = "?";
  51. // The handle to the underlying managed or unmanaged version of Bullet being used.
  52. public string BulletEngineName { get; private set; }
  53. public BSAPITemplate PE;
  54. // If the physics engine is running on a separate thread
  55. public Thread m_physicsThread;
  56. public Dictionary<uint, BSPhysObject> PhysObjects;
  57. public BSShapeCollection Shapes;
  58. // Keeping track of the objects with collisions so we can report begin and end of a collision
  59. public HashSet<BSPhysObject> ObjectsWithCollisions = new HashSet<BSPhysObject>();
  60. public HashSet<BSPhysObject> ObjectsWithNoMoreCollisions = new HashSet<BSPhysObject>();
  61. // All the collision processing is protected with this lock object
  62. public Object CollisionLock = new Object();
  63. // Properties are updated here
  64. public Object UpdateLock = new Object();
  65. public HashSet<BSPhysObject> ObjectsWithUpdates = new HashSet<BSPhysObject>();
  66. // Keep track of all the avatars so we can send them a collision event
  67. // every tick so OpenSim will update its animation.
  68. private HashSet<BSPhysObject> m_avatars = new HashSet<BSPhysObject>();
  69. // let my minuions use my logger
  70. public ILog Logger { get { return m_log; } }
  71. public IMesher mesher;
  72. public uint WorldID { get; private set; }
  73. public BulletWorld World { get; private set; }
  74. // All the constraints that have been allocated in this instance.
  75. public BSConstraintCollection Constraints { get; private set; }
  76. // Simulation parameters
  77. internal float m_physicsStepTime; // if running independently, the interval simulated by default
  78. internal int m_maxSubSteps;
  79. internal float m_fixedTimeStep;
  80. internal float m_simulatedTime; // the time simulated previously. Used for physics framerate calc.
  81. internal long m_simulationStep = 0; // The current simulation step.
  82. public long SimulationStep { get { return m_simulationStep; } }
  83. // A number to use for SimulationStep that is probably not any step value
  84. // Used by the collision code (which remembers the step when a collision happens) to remember not any simulation step.
  85. public static long NotASimulationStep = -1234;
  86. internal float LastTimeStep { get; private set; } // The simulation time from the last invocation of Simulate()
  87. internal float NominalFrameRate { get; set; } // Parameterized ideal frame rate that simulation is scaled to
  88. // Physical objects can register for prestep or poststep events
  89. public delegate void PreStepAction(float timeStep);
  90. public delegate void PostStepAction(float timeStep);
  91. public event PreStepAction BeforeStep;
  92. public event PostStepAction AfterStep;
  93. // A value of the time 'now' so all the collision and update routines do not have to get their own
  94. // Set to 'now' just before all the prims and actors are called for collisions and updates
  95. public int SimulationNowTime { get; private set; }
  96. // True if initialized and ready to do simulation steps
  97. private bool m_initialized = false;
  98. // Flag which is true when processing taints.
  99. // Not guaranteed to be correct all the time (don't depend on this) but good for debugging.
  100. public bool InTaintTime { get; private set; }
  101. // Pinned memory used to pass step information between managed and unmanaged
  102. internal int m_maxCollisionsPerFrame;
  103. internal CollisionDesc[] m_collisionArray;
  104. internal int m_maxUpdatesPerFrame;
  105. internal EntityProperties[] m_updateArray;
  106. public const uint TERRAIN_ID = 0; // OpenSim senses terrain with a localID of zero
  107. public const uint GROUNDPLANE_ID = 1;
  108. public const uint CHILDTERRAIN_ID = 2; // Terrain allocated based on our mega-prim childre start here
  109. public float SimpleWaterLevel { get; set; }
  110. public BSTerrainManager TerrainManager { get; private set; }
  111. public ConfigurationParameters Params
  112. {
  113. get { return UnmanagedParams[0]; }
  114. }
  115. public Vector3 DefaultGravity
  116. {
  117. get { return new Vector3(0f, 0f, Params.gravity); }
  118. }
  119. // Just the Z value of the gravity
  120. public float DefaultGravityZ
  121. {
  122. get { return Params.gravity; }
  123. }
  124. // When functions in the unmanaged code must be called, it is only
  125. // done at a known time just before the simulation step. The taint
  126. // system saves all these function calls and executes them in
  127. // order before the simulation.
  128. public delegate void TaintCallback();
  129. private struct TaintCallbackEntry
  130. {
  131. public String ident;
  132. public TaintCallback callback;
  133. public TaintCallbackEntry(string i, TaintCallback c)
  134. {
  135. ident = i;
  136. callback = c;
  137. }
  138. }
  139. private Object _taintLock = new Object(); // lock for using the next object
  140. private List<TaintCallbackEntry> _taintOperations;
  141. private Dictionary<string, TaintCallbackEntry> _postTaintOperations;
  142. private List<TaintCallbackEntry> _postStepOperations;
  143. // A pointer to an instance if this structure is passed to the C++ code
  144. // Used to pass basic configuration values to the unmanaged code.
  145. internal ConfigurationParameters[] UnmanagedParams;
  146. // Sometimes you just have to log everything.
  147. public Logging.LogWriter PhysicsLogging;
  148. private bool m_physicsLoggingEnabled;
  149. private string m_physicsLoggingDir;
  150. private string m_physicsLoggingPrefix;
  151. private int m_physicsLoggingFileMinutes;
  152. private bool m_physicsLoggingDoFlush;
  153. private bool m_physicsPhysicalDumpEnabled;
  154. public int PhysicsMetricDumpFrames { get; set; }
  155. // 'true' of the vehicle code is to log lots of details
  156. public bool VehicleLoggingEnabled { get; private set; }
  157. public bool VehiclePhysicalLoggingEnabled { get; private set; }
  158. #region Construction and Initialization
  159. public BSScene(string engineType, string identifier)
  160. {
  161. m_initialized = false;
  162. // The name of the region we're working for is passed to us. Keep for identification.
  163. RegionName = identifier;
  164. // Set identifying variables in the PhysicsScene interface.
  165. EngineType = engineType;
  166. Name = EngineType + "/" + RegionName;
  167. }
  168. public override void Initialise(IMesher meshmerizer, IConfigSource config)
  169. {
  170. mesher = meshmerizer;
  171. _taintOperations = new List<TaintCallbackEntry>();
  172. _postTaintOperations = new Dictionary<string, TaintCallbackEntry>();
  173. _postStepOperations = new List<TaintCallbackEntry>();
  174. PhysObjects = new Dictionary<uint, BSPhysObject>();
  175. Shapes = new BSShapeCollection(this);
  176. m_simulatedTime = 0f;
  177. LastTimeStep = 0.1f;
  178. // Allocate pinned memory to pass parameters.
  179. UnmanagedParams = new ConfigurationParameters[1];
  180. // Set default values for physics parameters plus any overrides from the ini file
  181. GetInitialParameterValues(config);
  182. // Get the connection to the physics engine (could be native or one of many DLLs)
  183. PE = SelectUnderlyingBulletEngine(BulletEngineName);
  184. // Enable very detailed logging.
  185. // By creating an empty logger when not logging, the log message invocation code
  186. // can be left in and every call doesn't have to check for null.
  187. if (m_physicsLoggingEnabled)
  188. {
  189. PhysicsLogging = new Logging.LogWriter(m_physicsLoggingDir, m_physicsLoggingPrefix, m_physicsLoggingFileMinutes, m_physicsLoggingDoFlush);
  190. PhysicsLogging.ErrorLogger = m_log; // for DEBUG. Let's the logger output its own error messages.
  191. }
  192. else
  193. {
  194. PhysicsLogging = new Logging.LogWriter();
  195. }
  196. // Allocate memory for returning of the updates and collisions from the physics engine
  197. m_collisionArray = new CollisionDesc[m_maxCollisionsPerFrame];
  198. m_updateArray = new EntityProperties[m_maxUpdatesPerFrame];
  199. // The bounding box for the simulated world. The origin is 0,0,0 unless we're
  200. // a child in a mega-region.
  201. // Bullet actually doesn't care about the extents of the simulated
  202. // area. It tracks active objects no matter where they are.
  203. Vector3 worldExtent = new Vector3(Constants.RegionSize, Constants.RegionSize, Constants.RegionHeight);
  204. World = PE.Initialize(worldExtent, Params, m_maxCollisionsPerFrame, ref m_collisionArray, m_maxUpdatesPerFrame, ref m_updateArray);
  205. Constraints = new BSConstraintCollection(World);
  206. TerrainManager = new BSTerrainManager(this);
  207. TerrainManager.CreateInitialGroundPlaneAndTerrain();
  208. // Put some informational messages into the log file.
  209. m_log.InfoFormat("{0} Linksets implemented with {1}", LogHeader, (BSLinkset.LinksetImplementation)BSParam.LinksetImplementation);
  210. InTaintTime = false;
  211. m_initialized = true;
  212. // If the physics engine runs on its own thread, start same.
  213. if (BSParam.UseSeparatePhysicsThread)
  214. {
  215. // The physics simulation should happen independently of the heartbeat loop
  216. m_physicsThread = new Thread(BulletSPluginPhysicsThread);
  217. m_physicsThread.Name = BulletEngineName;
  218. m_physicsThread.Start();
  219. }
  220. }
  221. // All default parameter values are set here. There should be no values set in the
  222. // variable definitions.
  223. private void GetInitialParameterValues(IConfigSource config)
  224. {
  225. ConfigurationParameters parms = new ConfigurationParameters();
  226. UnmanagedParams[0] = parms;
  227. BSParam.SetParameterDefaultValues(this);
  228. if (config != null)
  229. {
  230. // If there are specifications in the ini file, use those values
  231. IConfig pConfig = config.Configs["BulletSim"];
  232. if (pConfig != null)
  233. {
  234. BSParam.SetParameterConfigurationValues(this, pConfig);
  235. // There are two Bullet implementations to choose from
  236. BulletEngineName = pConfig.GetString("BulletEngine", "BulletUnmanaged");
  237. // Very detailed logging for physics debugging
  238. // TODO: the boolean values can be moved to the normal parameter processing.
  239. m_physicsLoggingEnabled = pConfig.GetBoolean("PhysicsLoggingEnabled", false);
  240. m_physicsLoggingDir = pConfig.GetString("PhysicsLoggingDir", ".");
  241. m_physicsLoggingPrefix = pConfig.GetString("PhysicsLoggingPrefix", "physics-%REGIONNAME%-");
  242. m_physicsLoggingFileMinutes = pConfig.GetInt("PhysicsLoggingFileMinutes", 5);
  243. m_physicsLoggingDoFlush = pConfig.GetBoolean("PhysicsLoggingDoFlush", false);
  244. m_physicsPhysicalDumpEnabled = pConfig.GetBoolean("PhysicsPhysicalDumpEnabled", false);
  245. // Very detailed logging for vehicle debugging
  246. VehicleLoggingEnabled = pConfig.GetBoolean("VehicleLoggingEnabled", false);
  247. VehiclePhysicalLoggingEnabled = pConfig.GetBoolean("VehiclePhysicalLoggingEnabled", false);
  248. // Do any replacements in the parameters
  249. m_physicsLoggingPrefix = m_physicsLoggingPrefix.Replace("%REGIONNAME%", RegionName);
  250. }
  251. else
  252. {
  253. // Nothing in the configuration INI file so assume unmanaged and other defaults.
  254. BulletEngineName = "BulletUnmanaged";
  255. m_physicsLoggingEnabled = false;
  256. VehicleLoggingEnabled = false;
  257. }
  258. // The material characteristics.
  259. BSMaterials.InitializeFromDefaults(Params);
  260. if (pConfig != null)
  261. {
  262. // Let the user add new and interesting material property values.
  263. BSMaterials.InitializefromParameters(pConfig);
  264. }
  265. }
  266. }
  267. // A helper function that handles a true/false parameter and returns the proper float number encoding
  268. float ParamBoolean(IConfig config, string parmName, float deflt)
  269. {
  270. float ret = deflt;
  271. if (config.Contains(parmName))
  272. {
  273. ret = ConfigurationParameters.numericFalse;
  274. if (config.GetBoolean(parmName, false))
  275. {
  276. ret = ConfigurationParameters.numericTrue;
  277. }
  278. }
  279. return ret;
  280. }
  281. // Select the connection to the actual Bullet implementation.
  282. // The main engine selection is the engineName up to the first hypen.
  283. // So "Bullet-2.80-OpenCL-Intel" specifies the 'bullet' class here and the whole name
  284. // is passed to the engine to do its special selection, etc.
  285. private BSAPITemplate SelectUnderlyingBulletEngine(string engineName)
  286. {
  287. // For the moment, do a simple switch statement.
  288. // Someday do fancyness with looking up the interfaces in the assembly.
  289. BSAPITemplate ret = null;
  290. string selectionName = engineName.ToLower();
  291. int hyphenIndex = engineName.IndexOf("-");
  292. if (hyphenIndex > 0)
  293. selectionName = engineName.ToLower().Substring(0, hyphenIndex - 1);
  294. switch (selectionName)
  295. {
  296. case "bullet":
  297. case "bulletunmanaged":
  298. ret = new BSAPIUnman(engineName, this);
  299. break;
  300. case "bulletxna":
  301. ret = new BSAPIXNA(engineName, this);
  302. // Disable some features that are not implemented in BulletXNA
  303. m_log.InfoFormat("{0} Disabling some physics features not implemented by BulletXNA", LogHeader);
  304. m_log.InfoFormat("{0} Disabling ShouldUseBulletHACD", LogHeader);
  305. BSParam.ShouldUseBulletHACD = false;
  306. m_log.InfoFormat("{0} Disabling ShouldUseSingleConvexHullForPrims", LogHeader);
  307. BSParam.ShouldUseSingleConvexHullForPrims = false;
  308. m_log.InfoFormat("{0} Disabling ShouldUseGImpactShapeForPrims", LogHeader);
  309. BSParam.ShouldUseGImpactShapeForPrims = false;
  310. m_log.InfoFormat("{0} Setting terrain implimentation to Heightmap", LogHeader);
  311. BSParam.TerrainImplementation = (float)BSTerrainPhys.TerrainImplementation.Heightmap;
  312. break;
  313. }
  314. if (ret == null)
  315. {
  316. m_log.ErrorFormat("{0) COULD NOT SELECT BULLET ENGINE: '[BulletSim]PhysicsEngine' must be either 'BulletUnmanaged-*' or 'BulletXNA-*'", LogHeader);
  317. }
  318. else
  319. {
  320. m_log.InfoFormat("{0} Selected bullet engine {1} -> {2}/{3}", LogHeader, engineName, ret.BulletEngineName, ret.BulletEngineVersion);
  321. }
  322. return ret;
  323. }
  324. public override void Dispose()
  325. {
  326. // m_log.DebugFormat("{0}: Dispose()", LogHeader);
  327. // make sure no stepping happens while we're deleting stuff
  328. m_initialized = false;
  329. foreach (KeyValuePair<uint, BSPhysObject> kvp in PhysObjects)
  330. {
  331. kvp.Value.Destroy();
  332. }
  333. PhysObjects.Clear();
  334. // Now that the prims are all cleaned up, there should be no constraints left
  335. if (Constraints != null)
  336. {
  337. Constraints.Dispose();
  338. Constraints = null;
  339. }
  340. if (Shapes != null)
  341. {
  342. Shapes.Dispose();
  343. Shapes = null;
  344. }
  345. if (TerrainManager != null)
  346. {
  347. TerrainManager.ReleaseGroundPlaneAndTerrain();
  348. TerrainManager.Dispose();
  349. TerrainManager = null;
  350. }
  351. // Anything left in the unmanaged code should be cleaned out
  352. PE.Shutdown(World);
  353. // Not logging any more
  354. PhysicsLogging.Close();
  355. }
  356. #endregion // Construction and Initialization
  357. #region Prim and Avatar addition and removal
  358. public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 size, bool isFlying)
  359. {
  360. m_log.ErrorFormat("{0}: CALL TO AddAvatar in BSScene. NOT IMPLEMENTED", LogHeader);
  361. return null;
  362. }
  363. public override PhysicsActor AddAvatar(uint localID, string avName, Vector3 position, Vector3 size, bool isFlying)
  364. {
  365. // m_log.DebugFormat("{0}: AddAvatar: {1}", LogHeader, avName);
  366. if (!m_initialized) return null;
  367. BSCharacter actor = new BSCharacter(localID, avName, this, position, size, isFlying);
  368. lock (PhysObjects)
  369. PhysObjects.Add(localID, actor);
  370. // TODO: Remove kludge someday.
  371. // We must generate a collision for avatars whether they collide or not.
  372. // This is required by OpenSim to update avatar animations, etc.
  373. lock (m_avatars)
  374. m_avatars.Add(actor);
  375. return actor;
  376. }
  377. public override void RemoveAvatar(PhysicsActor actor)
  378. {
  379. // m_log.DebugFormat("{0}: RemoveAvatar", LogHeader);
  380. if (!m_initialized) return;
  381. BSCharacter bsactor = actor as BSCharacter;
  382. if (bsactor != null)
  383. {
  384. try
  385. {
  386. lock (PhysObjects)
  387. PhysObjects.Remove(bsactor.LocalID);
  388. // Remove kludge someday
  389. lock (m_avatars)
  390. m_avatars.Remove(bsactor);
  391. }
  392. catch (Exception e)
  393. {
  394. m_log.WarnFormat("{0}: Attempt to remove avatar that is not in physics scene: {1}", LogHeader, e);
  395. }
  396. bsactor.Destroy();
  397. // bsactor.dispose();
  398. }
  399. else
  400. {
  401. m_log.ErrorFormat("{0}: Requested to remove avatar that is not a BSCharacter. ID={1}, type={2}",
  402. LogHeader, actor.LocalID, actor.GetType().Name);
  403. }
  404. }
  405. public override void RemovePrim(PhysicsActor prim)
  406. {
  407. if (!m_initialized) return;
  408. BSPhysObject bsprim = prim as BSPhysObject;
  409. if (bsprim != null)
  410. {
  411. DetailLog("{0},RemovePrim,call", bsprim.LocalID);
  412. // m_log.DebugFormat("{0}: RemovePrim. id={1}/{2}", LogHeader, bsprim.Name, bsprim.LocalID);
  413. try
  414. {
  415. lock (PhysObjects) PhysObjects.Remove(bsprim.LocalID);
  416. }
  417. catch (Exception e)
  418. {
  419. m_log.ErrorFormat("{0}: Attempt to remove prim that is not in physics scene: {1}", LogHeader, e);
  420. }
  421. bsprim.Destroy();
  422. // bsprim.dispose();
  423. }
  424. else
  425. {
  426. m_log.ErrorFormat("{0}: Attempt to remove prim that is not a BSPrim type.", LogHeader);
  427. }
  428. }
  429. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  430. Vector3 size, Quaternion rotation, bool isPhysical, uint localID)
  431. {
  432. // m_log.DebugFormat("{0}: AddPrimShape2: {1}", LogHeader, primName);
  433. if (!m_initialized) return null;
  434. // DetailLog("{0},BSScene.AddPrimShape,call", localID);
  435. BSPhysObject prim = new BSPrimLinkable(localID, primName, this, position, size, rotation, pbs, isPhysical);
  436. lock (PhysObjects) PhysObjects.Add(localID, prim);
  437. return prim;
  438. }
  439. // This is a call from the simulator saying that some physical property has been updated.
  440. // The BulletSim driver senses the changing of relevant properties so this taint
  441. // information call is not needed.
  442. public override void AddPhysicsActorTaint(PhysicsActor prim) { }
  443. #endregion // Prim and Avatar addition and removal
  444. #region Simulation
  445. // Call from the simulator to send physics information to the simulator objects.
  446. // This pushes all the collision and property update events into the objects in
  447. // the simulator and, since it is on the heartbeat thread, there is an implicit
  448. // locking of those data structures from other heartbeat events.
  449. // If the physics engine is running on a separate thread, the update information
  450. // will be in the ObjectsWithCollions and ObjectsWithUpdates structures.
  451. public override float Simulate(float timeStep)
  452. {
  453. if (!BSParam.UseSeparatePhysicsThread)
  454. {
  455. DoPhysicsStep(timeStep);
  456. }
  457. return SendUpdatesToSimulator(timeStep);
  458. }
  459. // Call the physics engine to do one 'timeStep' and collect collisions and updates
  460. // into ObjectsWithCollisions and ObjectsWithUpdates data structures.
  461. private void DoPhysicsStep(float timeStep)
  462. {
  463. // prevent simulation until we've been initialized
  464. if (!m_initialized) return;
  465. LastTimeStep = timeStep;
  466. int updatedEntityCount = 0;
  467. int collidersCount = 0;
  468. int beforeTime = Util.EnvironmentTickCount();
  469. int simTime = 0;
  470. int numTaints = _taintOperations.Count;
  471. InTaintTime = true; // Only used for debugging so locking is not necessary.
  472. // update the prim states while we know the physics engine is not busy
  473. ProcessTaints();
  474. // Some of the physical objects requre individual, pre-step calls
  475. // (vehicles and avatar movement, in particular)
  476. TriggerPreStepEvent(timeStep);
  477. // the prestep actions might have added taints
  478. numTaints += _taintOperations.Count;
  479. ProcessTaints();
  480. InTaintTime = false; // Only used for debugging so locking is not necessary.
  481. // The following causes the unmanaged code to output ALL the values found in ALL the objects in the world.
  482. // Only enable this in a limited test world with few objects.
  483. if (m_physicsPhysicalDumpEnabled)
  484. PE.DumpAllInfo(World);
  485. // step the physical world one interval
  486. m_simulationStep++;
  487. int numSubSteps = 0;
  488. try
  489. {
  490. numSubSteps = PE.PhysicsStep(World, timeStep, m_maxSubSteps, m_fixedTimeStep, out updatedEntityCount, out collidersCount);
  491. }
  492. catch (Exception e)
  493. {
  494. m_log.WarnFormat("{0},PhysicsStep Exception: nTaints={1}, substeps={2}, updates={3}, colliders={4}, e={5}",
  495. LogHeader, numTaints, numSubSteps, updatedEntityCount, collidersCount, e);
  496. DetailLog("{0},PhysicsStepException,call, nTaints={1}, substeps={2}, updates={3}, colliders={4}",
  497. DetailLogZero, numTaints, numSubSteps, updatedEntityCount, collidersCount);
  498. updatedEntityCount = 0;
  499. collidersCount = 0;
  500. }
  501. // Make the physics engine dump useful statistics periodically
  502. if (PhysicsMetricDumpFrames != 0 && ((m_simulationStep % PhysicsMetricDumpFrames) == 0))
  503. PE.DumpPhysicsStatistics(World);
  504. // Get a value for 'now' so all the collision and update routines don't have to get their own.
  505. SimulationNowTime = Util.EnvironmentTickCount();
  506. // Send collision information to the colliding objects. The objects decide if the collision
  507. // is 'real' (like linksets don't collide with themselves) and the individual objects
  508. // know if the simulator has subscribed to collisions.
  509. lock (CollisionLock)
  510. {
  511. if (collidersCount > 0)
  512. {
  513. for (int ii = 0; ii < collidersCount; ii++)
  514. {
  515. uint cA = m_collisionArray[ii].aID;
  516. uint cB = m_collisionArray[ii].bID;
  517. Vector3 point = m_collisionArray[ii].point;
  518. Vector3 normal = m_collisionArray[ii].normal;
  519. float penetration = m_collisionArray[ii].penetration;
  520. SendCollision(cA, cB, point, normal, penetration);
  521. SendCollision(cB, cA, point, -normal, penetration);
  522. }
  523. }
  524. }
  525. // If any of the objects had updated properties, tell the managed objects about the update
  526. // and remember that there was a change so it will be passed to the simulator.
  527. lock (UpdateLock)
  528. {
  529. if (updatedEntityCount > 0)
  530. {
  531. for (int ii = 0; ii < updatedEntityCount; ii++)
  532. {
  533. EntityProperties entprop = m_updateArray[ii];
  534. BSPhysObject pobj;
  535. if (PhysObjects.TryGetValue(entprop.ID, out pobj))
  536. {
  537. if (pobj.IsInitialized)
  538. pobj.UpdateProperties(entprop);
  539. }
  540. }
  541. }
  542. }
  543. // Some actors want to know when the simulation step is complete.
  544. TriggerPostStepEvent(timeStep);
  545. simTime = Util.EnvironmentTickCountSubtract(beforeTime);
  546. if (PhysicsLogging.Enabled)
  547. {
  548. DetailLog("{0},DoPhysicsStep,complete,frame={1}, nTaints={2}, simTime={3}, substeps={4}, updates={5}, colliders={6}, objWColl={7}",
  549. DetailLogZero, m_simulationStep, numTaints, simTime, numSubSteps,
  550. updatedEntityCount, collidersCount, ObjectsWithCollisions.Count);
  551. }
  552. // The following causes the unmanaged code to output ALL the values found in ALL the objects in the world.
  553. // Only enable this in a limited test world with few objects.
  554. if (m_physicsPhysicalDumpEnabled)
  555. PE.DumpAllInfo(World);
  556. // The physics engine returns the number of milliseconds it simulated this call.
  557. // These are summed and normalized to one second and divided by 1000 to give the reported physics FPS.
  558. // Multiply by a fixed nominal frame rate to give a rate similar to the simulator (usually 55).
  559. m_simulatedTime += (float)numSubSteps * m_fixedTimeStep * 1000f * NominalFrameRate;
  560. }
  561. // Called by a BSPhysObject to note that it has changed properties and this information
  562. // should be passed up to the simulator at the proper time.
  563. // Note: this is called by the BSPhysObject from invocation via DoPhysicsStep() above so
  564. // this is is under UpdateLock.
  565. public void PostUpdate(BSPhysObject updatee)
  566. {
  567. ObjectsWithUpdates.Add(updatee);
  568. }
  569. // The simulator thinks it is physics time so return all the collisions and position
  570. // updates that were collected in actual physics simulation.
  571. private float SendUpdatesToSimulator(float timeStep)
  572. {
  573. if (!m_initialized) return 5.0f;
  574. DetailLog("{0},SendUpdatesToSimulator,collisions={1},updates={2},simedTime={3}",
  575. BSScene.DetailLogZero, ObjectsWithCollisions.Count, ObjectsWithUpdates.Count, m_simulatedTime);
  576. // Push the collisions into the simulator.
  577. lock (CollisionLock)
  578. {
  579. if (ObjectsWithCollisions.Count > 0)
  580. {
  581. foreach (BSPhysObject bsp in ObjectsWithCollisions)
  582. if (!bsp.SendCollisions())
  583. {
  584. // If the object is done colliding, see that it's removed from the colliding list
  585. ObjectsWithNoMoreCollisions.Add(bsp);
  586. }
  587. }
  588. // This is a kludge to get avatar movement updates.
  589. // The simulator expects collisions for avatars even if there are have been no collisions.
  590. // The event updates avatar animations and stuff.
  591. // If you fix avatar animation updates, remove this overhead and let normal collision processing happen.
  592. foreach (BSPhysObject bsp in m_avatars)
  593. if (!ObjectsWithCollisions.Contains(bsp)) // don't call avatars twice
  594. bsp.SendCollisions();
  595. // Objects that are done colliding are removed from the ObjectsWithCollisions list.
  596. // Not done above because it is inside an iteration of ObjectWithCollisions.
  597. // This complex collision processing is required to create an empty collision
  598. // event call after all real collisions have happened on an object. This allows
  599. // the simulator to generate the 'collision end' event.
  600. if (ObjectsWithNoMoreCollisions.Count > 0)
  601. {
  602. foreach (BSPhysObject po in ObjectsWithNoMoreCollisions)
  603. ObjectsWithCollisions.Remove(po);
  604. ObjectsWithNoMoreCollisions.Clear();
  605. }
  606. }
  607. // Call the simulator for each object that has physics property updates.
  608. HashSet<BSPhysObject> updatedObjects = null;
  609. lock (UpdateLock)
  610. {
  611. if (ObjectsWithUpdates.Count > 0)
  612. {
  613. updatedObjects = ObjectsWithUpdates;
  614. ObjectsWithUpdates = new HashSet<BSPhysObject>();
  615. }
  616. }
  617. if (updatedObjects != null)
  618. {
  619. foreach (BSPhysObject obj in updatedObjects)
  620. {
  621. obj.RequestPhysicsterseUpdate();
  622. }
  623. updatedObjects.Clear();
  624. }
  625. // Return the framerate simulated to give the above returned results.
  626. // (Race condition here but this is just bookkeeping so rare mistakes do not merit a lock).
  627. float simTime = m_simulatedTime;
  628. m_simulatedTime = 0f;
  629. return simTime;
  630. }
  631. // Something has collided
  632. private void SendCollision(uint localID, uint collidingWith, Vector3 collidePoint, Vector3 collideNormal, float penetration)
  633. {
  634. if (localID <= TerrainManager.HighestTerrainID)
  635. {
  636. return; // don't send collisions to the terrain
  637. }
  638. BSPhysObject collider;
  639. if (!PhysObjects.TryGetValue(localID, out collider))
  640. {
  641. // If the object that is colliding cannot be found, just ignore the collision.
  642. DetailLog("{0},BSScene.SendCollision,colliderNotInObjectList,id={1},with={2}", DetailLogZero, localID, collidingWith);
  643. return;
  644. }
  645. // Note: the terrain is not in the physical object list so 'collidee' can be null when Collide() is called.
  646. BSPhysObject collidee = null;
  647. PhysObjects.TryGetValue(collidingWith, out collidee);
  648. // DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith);
  649. if (collider.IsInitialized)
  650. {
  651. if (collider.Collide(collidingWith, collidee, collidePoint, collideNormal, penetration))
  652. {
  653. // If a collision was 'good', remember to send it to the simulator
  654. ObjectsWithCollisions.Add(collider);
  655. }
  656. }
  657. return;
  658. }
  659. public void BulletSPluginPhysicsThread()
  660. {
  661. while (m_initialized)
  662. {
  663. int beginSimulationRealtimeMS = Util.EnvironmentTickCount();
  664. DoPhysicsStep(BSParam.PhysicsTimeStep);
  665. int simulationRealtimeMS = Util.EnvironmentTickCountSubtract(beginSimulationRealtimeMS);
  666. int simulationTimeVsRealtimeDifferenceMS = ((int)(BSParam.PhysicsTimeStep*1000f)) - simulationRealtimeMS;
  667. if (simulationTimeVsRealtimeDifferenceMS > 0)
  668. {
  669. // The simulation of the time interval took less than realtime.
  670. // Do a sleep for the rest of realtime.
  671. Thread.Sleep(simulationTimeVsRealtimeDifferenceMS);
  672. }
  673. else
  674. {
  675. // The simulation took longer than realtime.
  676. // Do some scaling of simulation time.
  677. // TODO.
  678. DetailLog("{0},BulletSPluginPhysicsThread,longerThanRealtime={1}", BSScene.DetailLogZero, simulationTimeVsRealtimeDifferenceMS);
  679. }
  680. }
  681. }
  682. #endregion // Simulation
  683. public override void GetResults() { }
  684. #region Terrain
  685. public override void SetTerrain(float[] heightMap) {
  686. TerrainManager.SetTerrain(heightMap);
  687. }
  688. public override void SetWaterLevel(float baseheight)
  689. {
  690. SimpleWaterLevel = baseheight;
  691. }
  692. public override void DeleteTerrain()
  693. {
  694. // m_log.DebugFormat("{0}: DeleteTerrain()", LogHeader);
  695. }
  696. // Although no one seems to check this, I do support combining.
  697. public override bool SupportsCombining()
  698. {
  699. return TerrainManager.SupportsCombining();
  700. }
  701. // This call says I am a child to region zero in a mega-region. 'pScene' is that
  702. // of region zero, 'offset' is my offset from regions zero's origin, and
  703. // 'extents' is the largest XY that is handled in my region.
  704. public override void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents)
  705. {
  706. TerrainManager.Combine(pScene, offset, extents);
  707. }
  708. // Unhook all the combining that I know about.
  709. public override void UnCombine(PhysicsScene pScene)
  710. {
  711. TerrainManager.UnCombine(pScene);
  712. }
  713. #endregion // Terrain
  714. public override Dictionary<uint, float> GetTopColliders()
  715. {
  716. Dictionary<uint, float> topColliders;
  717. lock (PhysObjects)
  718. {
  719. foreach (KeyValuePair<uint, BSPhysObject> kvp in PhysObjects)
  720. {
  721. kvp.Value.ComputeCollisionScore();
  722. }
  723. List<BSPhysObject> orderedPrims = new List<BSPhysObject>(PhysObjects.Values);
  724. orderedPrims.OrderByDescending(p => p.CollisionScore);
  725. topColliders = orderedPrims.Take(25).ToDictionary(p => p.LocalID, p => p.CollisionScore);
  726. }
  727. return topColliders;
  728. }
  729. public override bool IsThreaded { get { return false; } }
  730. #region Extensions
  731. // =============================================================
  732. // Per scene functions. See below.
  733. // Per avatar functions. See BSCharacter.
  734. // Per prim functions. See BSPrim.
  735. public const string PhysFunctGetLinksetType = "BulletSim.GetLinksetType";
  736. public const string PhysFunctSetLinksetType = "BulletSim.SetLinksetType";
  737. // =============================================================
  738. public override object Extension(string pFunct, params object[] pParams)
  739. {
  740. return base.Extension(pFunct, pParams);
  741. }
  742. #endregion // Extensions
  743. #region Taints
  744. // The simulation execution order is:
  745. // Simulate()
  746. // DoOneTimeTaints
  747. // TriggerPreStepEvent
  748. // DoOneTimeTaints
  749. // Step()
  750. // ProcessAndSendToSimulatorCollisions
  751. // ProcessAndSendToSimulatorPropertyUpdates
  752. // TriggerPostStepEvent
  753. // Calls to the PhysicsActors can't directly call into the physics engine
  754. // because it might be busy. We delay changes to a known time.
  755. // We rely on C#'s closure to save and restore the context for the delegate.
  756. public void TaintedObject(String ident, TaintCallback callback)
  757. {
  758. if (!m_initialized) return;
  759. lock (_taintLock)
  760. {
  761. _taintOperations.Add(new TaintCallbackEntry(ident, callback));
  762. }
  763. return;
  764. }
  765. // Sometimes a potentially tainted operation can be used in and out of taint time.
  766. // This routine executes the command immediately if in taint-time otherwise it is queued.
  767. public void TaintedObject(bool inTaintTime, string ident, TaintCallback callback)
  768. {
  769. if (inTaintTime)
  770. callback();
  771. else
  772. TaintedObject(ident, callback);
  773. }
  774. private void TriggerPreStepEvent(float timeStep)
  775. {
  776. PreStepAction actions = BeforeStep;
  777. if (actions != null)
  778. actions(timeStep);
  779. }
  780. private void TriggerPostStepEvent(float timeStep)
  781. {
  782. PostStepAction actions = AfterStep;
  783. if (actions != null)
  784. actions(timeStep);
  785. }
  786. // When someone tries to change a property on a BSPrim or BSCharacter, the object queues
  787. // a callback into itself to do the actual property change. That callback is called
  788. // here just before the physics engine is called to step the simulation.
  789. public void ProcessTaints()
  790. {
  791. ProcessRegularTaints();
  792. ProcessPostTaintTaints();
  793. }
  794. private void ProcessRegularTaints()
  795. {
  796. if (_taintOperations.Count > 0) // save allocating new list if there is nothing to process
  797. {
  798. // swizzle a new list into the list location so we can process what's there
  799. List<TaintCallbackEntry> oldList;
  800. lock (_taintLock)
  801. {
  802. oldList = _taintOperations;
  803. _taintOperations = new List<TaintCallbackEntry>();
  804. }
  805. foreach (TaintCallbackEntry tcbe in oldList)
  806. {
  807. try
  808. {
  809. DetailLog("{0},BSScene.ProcessTaints,doTaint,id={1}", DetailLogZero, tcbe.ident); // DEBUG DEBUG DEBUG
  810. tcbe.callback();
  811. }
  812. catch (Exception e)
  813. {
  814. m_log.ErrorFormat("{0}: ProcessTaints: {1}: Exception: {2}", LogHeader, tcbe.ident, e);
  815. }
  816. }
  817. oldList.Clear();
  818. }
  819. }
  820. // Schedule an update to happen after all the regular taints are processed.
  821. // Note that new requests for the same operation ("ident") for the same object ("ID")
  822. // will replace any previous operation by the same object.
  823. public void PostTaintObject(String ident, uint ID, TaintCallback callback)
  824. {
  825. string uniqueIdent = ident + "-" + ID.ToString();
  826. lock (_taintLock)
  827. {
  828. _postTaintOperations[uniqueIdent] = new TaintCallbackEntry(uniqueIdent, callback);
  829. }
  830. return;
  831. }
  832. // Taints that happen after the normal taint processing but before the simulation step.
  833. private void ProcessPostTaintTaints()
  834. {
  835. if (_postTaintOperations.Count > 0)
  836. {
  837. Dictionary<string, TaintCallbackEntry> oldList;
  838. lock (_taintLock)
  839. {
  840. oldList = _postTaintOperations;
  841. _postTaintOperations = new Dictionary<string, TaintCallbackEntry>();
  842. }
  843. foreach (KeyValuePair<string,TaintCallbackEntry> kvp in oldList)
  844. {
  845. try
  846. {
  847. DetailLog("{0},BSScene.ProcessPostTaintTaints,doTaint,id={1}", DetailLogZero, kvp.Key); // DEBUG DEBUG DEBUG
  848. kvp.Value.callback();
  849. }
  850. catch (Exception e)
  851. {
  852. m_log.ErrorFormat("{0}: ProcessPostTaintTaints: {1}: Exception: {2}", LogHeader, kvp.Key, e);
  853. }
  854. }
  855. oldList.Clear();
  856. }
  857. }
  858. // Only used for debugging. Does not change state of anything so locking is not necessary.
  859. public bool AssertInTaintTime(string whereFrom)
  860. {
  861. if (!InTaintTime)
  862. {
  863. DetailLog("{0},BSScene.AssertInTaintTime,NOT IN TAINT TIME,Region={1},Where={2}", DetailLogZero, RegionName, whereFrom);
  864. m_log.ErrorFormat("{0} NOT IN TAINT TIME!! Region={1}, Where={2}", LogHeader, RegionName, whereFrom);
  865. // Util.PrintCallStack(DetailLog);
  866. }
  867. return InTaintTime;
  868. }
  869. #endregion // Taints
  870. #region IPhysicsParameters
  871. // Get the list of parameters this physics engine supports
  872. public PhysParameterEntry[] GetParameterList()
  873. {
  874. BSParam.BuildParameterTable();
  875. return BSParam.SettableParameters;
  876. }
  877. // Set parameter on a specific or all instances.
  878. // Return 'false' if not able to set the parameter.
  879. // Setting the value in the m_params block will change the value the physics engine
  880. // will use the next time since it's pinned and shared memory.
  881. // Some of the values require calling into the physics engine to get the new
  882. // value activated ('terrainFriction' for instance).
  883. public bool SetPhysicsParameter(string parm, string val, uint localID)
  884. {
  885. bool ret = false;
  886. BSParam.ParameterDefnBase theParam;
  887. if (BSParam.TryGetParameter(parm, out theParam))
  888. {
  889. // Set the value in the C# code
  890. theParam.SetValue(this, val);
  891. // Optionally set the parameter in the unmanaged code
  892. if (theParam.HasSetOnObject)
  893. {
  894. // update all the localIDs specified
  895. // If the local ID is APPLY_TO_NONE, just change the default value
  896. // If the localID is APPLY_TO_ALL change the default value and apply the new value to all the lIDs
  897. // If the localID is a specific object, apply the parameter change to only that object
  898. List<uint> objectIDs = new List<uint>();
  899. switch (localID)
  900. {
  901. case PhysParameterEntry.APPLY_TO_NONE:
  902. // This will cause a call into the physical world if some operation is specified (SetOnObject).
  903. objectIDs.Add(TERRAIN_ID);
  904. TaintedUpdateParameter(parm, objectIDs, val);
  905. break;
  906. case PhysParameterEntry.APPLY_TO_ALL:
  907. lock (PhysObjects) objectIDs = new List<uint>(PhysObjects.Keys);
  908. TaintedUpdateParameter(parm, objectIDs, val);
  909. break;
  910. default:
  911. // setting only one localID
  912. objectIDs.Add(localID);
  913. TaintedUpdateParameter(parm, objectIDs, val);
  914. break;
  915. }
  916. }
  917. ret = true;
  918. }
  919. return ret;
  920. }
  921. // schedule the actual updating of the paramter to when the phys engine is not busy
  922. private void TaintedUpdateParameter(string parm, List<uint> lIDs, string val)
  923. {
  924. string xval = val;
  925. List<uint> xlIDs = lIDs;
  926. string xparm = parm;
  927. TaintedObject("BSScene.UpdateParameterSet", delegate() {
  928. BSParam.ParameterDefnBase thisParam;
  929. if (BSParam.TryGetParameter(xparm, out thisParam))
  930. {
  931. if (thisParam.HasSetOnObject)
  932. {
  933. foreach (uint lID in xlIDs)
  934. {
  935. BSPhysObject theObject = null;
  936. if (PhysObjects.TryGetValue(lID, out theObject))
  937. thisParam.SetOnObject(this, theObject);
  938. }
  939. }
  940. }
  941. });
  942. }
  943. // Get parameter.
  944. // Return 'false' if not able to get the parameter.
  945. public bool GetPhysicsParameter(string parm, out string value)
  946. {
  947. string val = String.Empty;
  948. bool ret = false;
  949. BSParam.ParameterDefnBase theParam;
  950. if (BSParam.TryGetParameter(parm, out theParam))
  951. {
  952. val = theParam.GetValue(this);
  953. ret = true;
  954. }
  955. value = val;
  956. return ret;
  957. }
  958. #endregion IPhysicsParameters
  959. // Invoke the detailed logger and output something if it's enabled.
  960. public void DetailLog(string msg, params Object[] args)
  961. {
  962. PhysicsLogging.Write(msg, args);
  963. }
  964. // Used to fill in the LocalID when there isn't one. It's the correct number of characters.
  965. public const string DetailLogZero = "0000000000";
  966. }
  967. }