1
0

BSScene.cs 63 KB

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