BSScene.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  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. pobj.UpdateProperties(entprop);
  538. }
  539. }
  540. }
  541. }
  542. // Some actors want to know when the simulation step is complete.
  543. TriggerPostStepEvent(timeStep);
  544. simTime = Util.EnvironmentTickCountSubtract(beforeTime);
  545. if (PhysicsLogging.Enabled)
  546. {
  547. DetailLog("{0},DoPhysicsStep,complete,frame={1}, nTaints={2}, simTime={3}, substeps={4}, updates={5}, colliders={6}, objWColl={7}",
  548. DetailLogZero, m_simulationStep, numTaints, simTime, numSubSteps,
  549. updatedEntityCount, collidersCount, ObjectsWithCollisions.Count);
  550. }
  551. // The following causes the unmanaged code to output ALL the values found in ALL the objects in the world.
  552. // Only enable this in a limited test world with few objects.
  553. if (m_physicsPhysicalDumpEnabled)
  554. PE.DumpAllInfo(World);
  555. // The physics engine returns the number of milliseconds it simulated this call.
  556. // These are summed and normalized to one second and divided by 1000 to give the reported physics FPS.
  557. // Multiply by a fixed nominal frame rate to give a rate similar to the simulator (usually 55).
  558. m_simulatedTime += (float)numSubSteps * m_fixedTimeStep * 1000f * NominalFrameRate;
  559. }
  560. // Called by a BSPhysObject to note that it has changed properties and this information
  561. // should be passed up to the simulator at the proper time.
  562. // Note: this is called by the BSPhysObject from invocation via DoPhysicsStep() above so
  563. // this is is under UpdateLock.
  564. public void PostUpdate(BSPhysObject updatee)
  565. {
  566. ObjectsWithUpdates.Add(updatee);
  567. }
  568. // The simulator thinks it is physics time so return all the collisions and position
  569. // updates that were collected in actual physics simulation.
  570. private float SendUpdatesToSimulator(float timeStep)
  571. {
  572. if (!m_initialized) return 5.0f;
  573. DetailLog("{0},SendUpdatesToSimulator,collisions={1},updates={2},simedTime={3}",
  574. BSScene.DetailLogZero, ObjectsWithCollisions.Count, ObjectsWithUpdates.Count, m_simulatedTime);
  575. // Push the collisions into the simulator.
  576. lock (CollisionLock)
  577. {
  578. if (ObjectsWithCollisions.Count > 0)
  579. {
  580. foreach (BSPhysObject bsp in ObjectsWithCollisions)
  581. if (!bsp.SendCollisions())
  582. {
  583. // If the object is done colliding, see that it's removed from the colliding list
  584. ObjectsWithNoMoreCollisions.Add(bsp);
  585. }
  586. }
  587. // This is a kludge to get avatar movement updates.
  588. // The simulator expects collisions for avatars even if there are have been no collisions.
  589. // The event updates avatar animations and stuff.
  590. // If you fix avatar animation updates, remove this overhead and let normal collision processing happen.
  591. foreach (BSPhysObject bsp in m_avatars)
  592. if (!ObjectsWithCollisions.Contains(bsp)) // don't call avatars twice
  593. bsp.SendCollisions();
  594. // Objects that are done colliding are removed from the ObjectsWithCollisions list.
  595. // Not done above because it is inside an iteration of ObjectWithCollisions.
  596. // This complex collision processing is required to create an empty collision
  597. // event call after all real collisions have happened on an object. This allows
  598. // the simulator to generate the 'collision end' event.
  599. if (ObjectsWithNoMoreCollisions.Count > 0)
  600. {
  601. foreach (BSPhysObject po in ObjectsWithNoMoreCollisions)
  602. ObjectsWithCollisions.Remove(po);
  603. ObjectsWithNoMoreCollisions.Clear();
  604. }
  605. }
  606. // Call the simulator for each object that has physics property updates.
  607. HashSet<BSPhysObject> updatedObjects = null;
  608. lock (UpdateLock)
  609. {
  610. if (ObjectsWithUpdates.Count > 0)
  611. {
  612. updatedObjects = ObjectsWithUpdates;
  613. ObjectsWithUpdates = new HashSet<BSPhysObject>();
  614. }
  615. }
  616. if (updatedObjects != null)
  617. {
  618. foreach (BSPhysObject obj in updatedObjects)
  619. {
  620. obj.RequestPhysicsterseUpdate();
  621. }
  622. updatedObjects.Clear();
  623. }
  624. // Return the framerate simulated to give the above returned results.
  625. // (Race condition here but this is just bookkeeping so rare mistakes do not merit a lock).
  626. float simTime = m_simulatedTime;
  627. m_simulatedTime = 0f;
  628. return simTime;
  629. }
  630. // Something has collided
  631. private void SendCollision(uint localID, uint collidingWith, Vector3 collidePoint, Vector3 collideNormal, float penetration)
  632. {
  633. if (localID <= TerrainManager.HighestTerrainID)
  634. {
  635. return; // don't send collisions to the terrain
  636. }
  637. BSPhysObject collider;
  638. if (!PhysObjects.TryGetValue(localID, out collider))
  639. {
  640. // If the object that is colliding cannot be found, just ignore the collision.
  641. DetailLog("{0},BSScene.SendCollision,colliderNotInObjectList,id={1},with={2}", DetailLogZero, localID, collidingWith);
  642. return;
  643. }
  644. // Note: the terrain is not in the physical object list so 'collidee' can be null when Collide() is called.
  645. BSPhysObject collidee = null;
  646. PhysObjects.TryGetValue(collidingWith, out collidee);
  647. // DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith);
  648. if (collider.Collide(collidingWith, collidee, collidePoint, collideNormal, penetration))
  649. {
  650. // If a collision was 'good', remember to send it to the simulator
  651. ObjectsWithCollisions.Add(collider);
  652. }
  653. return;
  654. }
  655. public void BulletSPluginPhysicsThread()
  656. {
  657. while (m_initialized)
  658. {
  659. int beginSimulationRealtimeMS = Util.EnvironmentTickCount();
  660. DoPhysicsStep(BSParam.PhysicsTimeStep);
  661. int simulationRealtimeMS = Util.EnvironmentTickCountSubtract(beginSimulationRealtimeMS);
  662. int simulationTimeVsRealtimeDifferenceMS = ((int)(BSParam.PhysicsTimeStep*1000f)) - simulationRealtimeMS;
  663. if (simulationTimeVsRealtimeDifferenceMS > 0)
  664. {
  665. // The simulation of the time interval took less than realtime.
  666. // Do a sleep for the rest of realtime.
  667. Thread.Sleep(simulationTimeVsRealtimeDifferenceMS);
  668. }
  669. else
  670. {
  671. // The simulation took longer than realtime.
  672. // Do some scaling of simulation time.
  673. // TODO.
  674. DetailLog("{0},BulletSPluginPhysicsThread,longerThanRealtime={1}", BSScene.DetailLogZero, simulationTimeVsRealtimeDifferenceMS);
  675. }
  676. }
  677. }
  678. #endregion // Simulation
  679. public override void GetResults() { }
  680. #region Terrain
  681. public override void SetTerrain(float[] heightMap) {
  682. TerrainManager.SetTerrain(heightMap);
  683. }
  684. public override void SetWaterLevel(float baseheight)
  685. {
  686. SimpleWaterLevel = baseheight;
  687. }
  688. public override void DeleteTerrain()
  689. {
  690. // m_log.DebugFormat("{0}: DeleteTerrain()", LogHeader);
  691. }
  692. // Although no one seems to check this, I do support combining.
  693. public override bool SupportsCombining()
  694. {
  695. return TerrainManager.SupportsCombining();
  696. }
  697. // This call says I am a child to region zero in a mega-region. 'pScene' is that
  698. // of region zero, 'offset' is my offset from regions zero's origin, and
  699. // 'extents' is the largest XY that is handled in my region.
  700. public override void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents)
  701. {
  702. TerrainManager.Combine(pScene, offset, extents);
  703. }
  704. // Unhook all the combining that I know about.
  705. public override void UnCombine(PhysicsScene pScene)
  706. {
  707. TerrainManager.UnCombine(pScene);
  708. }
  709. #endregion // Terrain
  710. public override Dictionary<uint, float> GetTopColliders()
  711. {
  712. Dictionary<uint, float> topColliders;
  713. lock (PhysObjects)
  714. {
  715. foreach (KeyValuePair<uint, BSPhysObject> kvp in PhysObjects)
  716. {
  717. kvp.Value.ComputeCollisionScore();
  718. }
  719. List<BSPhysObject> orderedPrims = new List<BSPhysObject>(PhysObjects.Values);
  720. orderedPrims.OrderByDescending(p => p.CollisionScore);
  721. topColliders = orderedPrims.Take(25).ToDictionary(p => p.LocalID, p => p.CollisionScore);
  722. }
  723. return topColliders;
  724. }
  725. public override bool IsThreaded { get { return false; } }
  726. #region Extensions
  727. // =============================================================
  728. // Per scene functions. See below.
  729. // Per avatar functions. See BSCharacter.
  730. // Per prim functions. See BSPrim.
  731. public const string PhysFunctGetLinksetType = "BulletSim.GetLinksetType";
  732. public const string PhysFunctSetLinksetType = "BulletSim.SetLinksetType";
  733. // =============================================================
  734. public override object Extension(string pFunct, params object[] pParams)
  735. {
  736. return base.Extension(pFunct, pParams);
  737. }
  738. #endregion // Extensions
  739. #region Taints
  740. // The simulation execution order is:
  741. // Simulate()
  742. // DoOneTimeTaints
  743. // TriggerPreStepEvent
  744. // DoOneTimeTaints
  745. // Step()
  746. // ProcessAndSendToSimulatorCollisions
  747. // ProcessAndSendToSimulatorPropertyUpdates
  748. // TriggerPostStepEvent
  749. // Calls to the PhysicsActors can't directly call into the physics engine
  750. // because it might be busy. We delay changes to a known time.
  751. // We rely on C#'s closure to save and restore the context for the delegate.
  752. public void TaintedObject(String ident, TaintCallback callback)
  753. {
  754. if (!m_initialized) return;
  755. lock (_taintLock)
  756. {
  757. _taintOperations.Add(new TaintCallbackEntry(ident, callback));
  758. }
  759. return;
  760. }
  761. // Sometimes a potentially tainted operation can be used in and out of taint time.
  762. // This routine executes the command immediately if in taint-time otherwise it is queued.
  763. public void TaintedObject(bool inTaintTime, string ident, TaintCallback callback)
  764. {
  765. if (inTaintTime)
  766. callback();
  767. else
  768. TaintedObject(ident, callback);
  769. }
  770. private void TriggerPreStepEvent(float timeStep)
  771. {
  772. PreStepAction actions = BeforeStep;
  773. if (actions != null)
  774. actions(timeStep);
  775. }
  776. private void TriggerPostStepEvent(float timeStep)
  777. {
  778. PostStepAction actions = AfterStep;
  779. if (actions != null)
  780. actions(timeStep);
  781. }
  782. // When someone tries to change a property on a BSPrim or BSCharacter, the object queues
  783. // a callback into itself to do the actual property change. That callback is called
  784. // here just before the physics engine is called to step the simulation.
  785. public void ProcessTaints()
  786. {
  787. ProcessRegularTaints();
  788. ProcessPostTaintTaints();
  789. }
  790. private void ProcessRegularTaints()
  791. {
  792. if (_taintOperations.Count > 0) // save allocating new list if there is nothing to process
  793. {
  794. // swizzle a new list into the list location so we can process what's there
  795. List<TaintCallbackEntry> oldList;
  796. lock (_taintLock)
  797. {
  798. oldList = _taintOperations;
  799. _taintOperations = new List<TaintCallbackEntry>();
  800. }
  801. foreach (TaintCallbackEntry tcbe in oldList)
  802. {
  803. try
  804. {
  805. DetailLog("{0},BSScene.ProcessTaints,doTaint,id={1}", DetailLogZero, tcbe.ident); // DEBUG DEBUG DEBUG
  806. tcbe.callback();
  807. }
  808. catch (Exception e)
  809. {
  810. m_log.ErrorFormat("{0}: ProcessTaints: {1}: Exception: {2}", LogHeader, tcbe.ident, e);
  811. }
  812. }
  813. oldList.Clear();
  814. }
  815. }
  816. // Schedule an update to happen after all the regular taints are processed.
  817. // Note that new requests for the same operation ("ident") for the same object ("ID")
  818. // will replace any previous operation by the same object.
  819. public void PostTaintObject(String ident, uint ID, TaintCallback callback)
  820. {
  821. string uniqueIdent = ident + "-" + ID.ToString();
  822. lock (_taintLock)
  823. {
  824. _postTaintOperations[uniqueIdent] = new TaintCallbackEntry(uniqueIdent, callback);
  825. }
  826. return;
  827. }
  828. // Taints that happen after the normal taint processing but before the simulation step.
  829. private void ProcessPostTaintTaints()
  830. {
  831. if (_postTaintOperations.Count > 0)
  832. {
  833. Dictionary<string, TaintCallbackEntry> oldList;
  834. lock (_taintLock)
  835. {
  836. oldList = _postTaintOperations;
  837. _postTaintOperations = new Dictionary<string, TaintCallbackEntry>();
  838. }
  839. foreach (KeyValuePair<string,TaintCallbackEntry> kvp in oldList)
  840. {
  841. try
  842. {
  843. DetailLog("{0},BSScene.ProcessPostTaintTaints,doTaint,id={1}", DetailLogZero, kvp.Key); // DEBUG DEBUG DEBUG
  844. kvp.Value.callback();
  845. }
  846. catch (Exception e)
  847. {
  848. m_log.ErrorFormat("{0}: ProcessPostTaintTaints: {1}: Exception: {2}", LogHeader, kvp.Key, e);
  849. }
  850. }
  851. oldList.Clear();
  852. }
  853. }
  854. // Only used for debugging. Does not change state of anything so locking is not necessary.
  855. public bool AssertInTaintTime(string whereFrom)
  856. {
  857. if (!InTaintTime)
  858. {
  859. DetailLog("{0},BSScene.AssertInTaintTime,NOT IN TAINT TIME,Region={1},Where={2}", DetailLogZero, RegionName, whereFrom);
  860. m_log.ErrorFormat("{0} NOT IN TAINT TIME!! Region={1}, Where={2}", LogHeader, RegionName, whereFrom);
  861. // Util.PrintCallStack(DetailLog);
  862. }
  863. return InTaintTime;
  864. }
  865. #endregion // Taints
  866. #region IPhysicsParameters
  867. // Get the list of parameters this physics engine supports
  868. public PhysParameterEntry[] GetParameterList()
  869. {
  870. BSParam.BuildParameterTable();
  871. return BSParam.SettableParameters;
  872. }
  873. // Set parameter on a specific or all instances.
  874. // Return 'false' if not able to set the parameter.
  875. // Setting the value in the m_params block will change the value the physics engine
  876. // will use the next time since it's pinned and shared memory.
  877. // Some of the values require calling into the physics engine to get the new
  878. // value activated ('terrainFriction' for instance).
  879. public bool SetPhysicsParameter(string parm, string val, uint localID)
  880. {
  881. bool ret = false;
  882. BSParam.ParameterDefnBase theParam;
  883. if (BSParam.TryGetParameter(parm, out theParam))
  884. {
  885. // Set the value in the C# code
  886. theParam.SetValue(this, val);
  887. // Optionally set the parameter in the unmanaged code
  888. if (theParam.HasSetOnObject)
  889. {
  890. // update all the localIDs specified
  891. // If the local ID is APPLY_TO_NONE, just change the default value
  892. // If the localID is APPLY_TO_ALL change the default value and apply the new value to all the lIDs
  893. // If the localID is a specific object, apply the parameter change to only that object
  894. List<uint> objectIDs = new List<uint>();
  895. switch (localID)
  896. {
  897. case PhysParameterEntry.APPLY_TO_NONE:
  898. // This will cause a call into the physical world if some operation is specified (SetOnObject).
  899. objectIDs.Add(TERRAIN_ID);
  900. TaintedUpdateParameter(parm, objectIDs, val);
  901. break;
  902. case PhysParameterEntry.APPLY_TO_ALL:
  903. lock (PhysObjects) objectIDs = new List<uint>(PhysObjects.Keys);
  904. TaintedUpdateParameter(parm, objectIDs, val);
  905. break;
  906. default:
  907. // setting only one localID
  908. objectIDs.Add(localID);
  909. TaintedUpdateParameter(parm, objectIDs, val);
  910. break;
  911. }
  912. }
  913. ret = true;
  914. }
  915. return ret;
  916. }
  917. // schedule the actual updating of the paramter to when the phys engine is not busy
  918. private void TaintedUpdateParameter(string parm, List<uint> lIDs, string val)
  919. {
  920. string xval = val;
  921. List<uint> xlIDs = lIDs;
  922. string xparm = parm;
  923. TaintedObject("BSScene.UpdateParameterSet", delegate() {
  924. BSParam.ParameterDefnBase thisParam;
  925. if (BSParam.TryGetParameter(xparm, out thisParam))
  926. {
  927. if (thisParam.HasSetOnObject)
  928. {
  929. foreach (uint lID in xlIDs)
  930. {
  931. BSPhysObject theObject = null;
  932. if (PhysObjects.TryGetValue(lID, out theObject))
  933. thisParam.SetOnObject(this, theObject);
  934. }
  935. }
  936. }
  937. });
  938. }
  939. // Get parameter.
  940. // Return 'false' if not able to get the parameter.
  941. public bool GetPhysicsParameter(string parm, out string value)
  942. {
  943. string val = String.Empty;
  944. bool ret = false;
  945. BSParam.ParameterDefnBase theParam;
  946. if (BSParam.TryGetParameter(parm, out theParam))
  947. {
  948. val = theParam.GetValue(this);
  949. ret = true;
  950. }
  951. value = val;
  952. return ret;
  953. }
  954. #endregion IPhysicsParameters
  955. // Invoke the detailed logger and output something if it's enabled.
  956. public void DetailLog(string msg, params Object[] args)
  957. {
  958. PhysicsLogging.Write(msg, args);
  959. }
  960. // Used to fill in the LocalID when there isn't one. It's the correct number of characters.
  961. public const string DetailLogZero = "0000000000";
  962. }
  963. }