BSScene.cs 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499
  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.Runtime.InteropServices;
  30. using System.Text;
  31. using System.Threading;
  32. using OpenSim.Framework;
  33. using OpenSim.Region.Framework;
  34. using OpenSim.Region.CoreModules;
  35. using Logging = OpenSim.Region.CoreModules.Framework.Statistics.Logging;
  36. using OpenSim.Region.Physics.Manager;
  37. using Nini.Config;
  38. using log4net;
  39. using OpenMetaverse;
  40. // TODOs for BulletSim (for BSScene, BSPrim, BSCharacter and BulletSim)
  41. // Based on material, set density and friction
  42. // More efficient memory usage when passing hull information from BSPrim to BulletSim
  43. // Do attachments need to be handled separately? Need collision events. Do not collide with VolumeDetect
  44. // Implement LockAngularMotion
  45. // Add PID movement operations. What does ScenePresence.MoveToTarget do?
  46. // Check terrain size. 128 or 127?
  47. // Raycast
  48. //
  49. namespace OpenSim.Region.Physics.BulletSPlugin
  50. {
  51. public sealed class BSScene : PhysicsScene, IPhysicsParameters
  52. {
  53. private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  54. private static readonly string LogHeader = "[BULLETS SCENE]";
  55. // The name of the region we're working for.
  56. public string RegionName { get; private set; }
  57. public string BulletSimVersion = "?";
  58. public Dictionary<uint, BSPhysObject> PhysObjects;
  59. public BSShapeCollection Shapes;
  60. // Keeping track of the objects with collisions so we can report begin and end of a collision
  61. public HashSet<BSPhysObject> ObjectsWithCollisions = new HashSet<BSPhysObject>();
  62. public HashSet<BSPhysObject> ObjectsWithNoMoreCollisions = new HashSet<BSPhysObject>();
  63. // Keep track of all the avatars so we can send them a collision event
  64. // every tick so OpenSim will update its animation.
  65. private HashSet<BSPhysObject> m_avatars = new HashSet<BSPhysObject>();
  66. // List of all the objects that have vehicle properties and should be called
  67. // to update each physics step.
  68. private List<BSPhysObject> m_vehicles = new List<BSPhysObject>();
  69. // let my minuions use my logger
  70. public ILog Logger { get { return m_log; } }
  71. public IMesher mesher;
  72. // Level of Detail values kept as float because that's what the Meshmerizer wants
  73. public float MeshLOD { get; private set; }
  74. public float MeshMegaPrimLOD { get; private set; }
  75. public float MeshMegaPrimThreshold { get; private set; }
  76. public float SculptLOD { get; private set; }
  77. public uint WorldID { get; private set; }
  78. public BulletSim World { get; private set; }
  79. // All the constraints that have been allocated in this instance.
  80. public BSConstraintCollection Constraints { get; private set; }
  81. // Simulation parameters
  82. private int m_maxSubSteps;
  83. private float m_fixedTimeStep;
  84. private long m_simulationStep = 0;
  85. public long SimulationStep { get { return m_simulationStep; } }
  86. private int m_taintsToProcessPerStep;
  87. // A value of the time now so all the collision and update routines do not have to get their own
  88. // Set to 'now' just before all the prims and actors are called for collisions and updates
  89. public int SimulationNowTime { get; private set; }
  90. // True if initialized and ready to do simulation steps
  91. private bool m_initialized = false;
  92. // Flag which is true when processing taints.
  93. // Not guaranteed to be correct all the time (don't depend on this) but good for debugging.
  94. public bool InTaintTime { get; private set; }
  95. // Pinned memory used to pass step information between managed and unmanaged
  96. private int m_maxCollisionsPerFrame;
  97. private CollisionDesc[] m_collisionArray;
  98. private GCHandle m_collisionArrayPinnedHandle;
  99. private int m_maxUpdatesPerFrame;
  100. private EntityProperties[] m_updateArray;
  101. private GCHandle m_updateArrayPinnedHandle;
  102. public bool ShouldMeshSculptedPrim { get; private set; } // cause scuplted prims to get meshed
  103. public bool ShouldForceSimplePrimMeshing { get; private set; } // if a cube or sphere, let Bullet do internal shapes
  104. public bool ShouldUseHullsForPhysicalObjects { get; private set; } // 'true' if should create hulls for physical objects
  105. public float PID_D { get; private set; } // derivative
  106. public float PID_P { get; private set; } // proportional
  107. public const uint TERRAIN_ID = 0; // OpenSim senses terrain with a localID of zero
  108. public const uint GROUNDPLANE_ID = 1;
  109. public const uint CHILDTERRAIN_ID = 2; // Terrain allocated based on our mega-prim childre start here
  110. public float SimpleWaterLevel { get; set; }
  111. public BSTerrainManager TerrainManager { get; private set; }
  112. public ConfigurationParameters Params
  113. {
  114. get { return m_params[0]; }
  115. }
  116. public Vector3 DefaultGravity
  117. {
  118. get { return new Vector3(0f, 0f, Params.gravity); }
  119. }
  120. // Just the Z value of the gravity
  121. public float DefaultGravityZ
  122. {
  123. get { return Params.gravity; }
  124. }
  125. public float MaximumObjectMass { get; private set; }
  126. // When functions in the unmanaged code must be called, it is only
  127. // done at a known time just before the simulation step. The taint
  128. // system saves all these function calls and executes them in
  129. // order before the simulation.
  130. public delegate void TaintCallback();
  131. private struct TaintCallbackEntry
  132. {
  133. public String ident;
  134. public TaintCallback callback;
  135. public TaintCallbackEntry(string i, TaintCallback c)
  136. {
  137. ident = i;
  138. callback = c;
  139. }
  140. }
  141. private Object _taintLock = new Object(); // lock for using the next object
  142. private List<TaintCallbackEntry> _taintOperations;
  143. private Dictionary<string, TaintCallbackEntry> _postTaintOperations;
  144. private List<TaintCallbackEntry> _postStepOperations;
  145. // A pointer to an instance if this structure is passed to the C++ code
  146. // Used to pass basic configuration values to the unmanaged code.
  147. ConfigurationParameters[] m_params;
  148. GCHandle m_paramsHandle;
  149. // Handle to the callback used by the unmanaged code to call into the managed code.
  150. // Used for debug logging.
  151. // Need to store the handle in a persistant variable so it won't be freed.
  152. private BulletSimAPI.DebugLogCallback m_DebugLogCallbackHandle;
  153. // Sometimes you just have to log everything.
  154. public Logging.LogWriter PhysicsLogging;
  155. private bool m_physicsLoggingEnabled;
  156. private string m_physicsLoggingDir;
  157. private string m_physicsLoggingPrefix;
  158. private int m_physicsLoggingFileMinutes;
  159. private bool m_physicsLoggingDoFlush;
  160. // 'true' of the vehicle code is to log lots of details
  161. public bool VehicleLoggingEnabled { get; private set; }
  162. #region Construction and Initialization
  163. public BSScene(string identifier)
  164. {
  165. m_initialized = false;
  166. // we are passed the name of the region we're working for.
  167. RegionName = identifier;
  168. }
  169. public override void Initialise(IMesher meshmerizer, IConfigSource config)
  170. {
  171. mesher = meshmerizer;
  172. _taintOperations = new List<TaintCallbackEntry>();
  173. _postTaintOperations = new Dictionary<string, TaintCallbackEntry>();
  174. _postStepOperations = new List<TaintCallbackEntry>();
  175. PhysObjects = new Dictionary<uint, BSPhysObject>();
  176. Shapes = new BSShapeCollection(this);
  177. // Allocate pinned memory to pass parameters.
  178. m_params = new ConfigurationParameters[1];
  179. m_paramsHandle = GCHandle.Alloc(m_params, GCHandleType.Pinned);
  180. // Set default values for physics parameters plus any overrides from the ini file
  181. GetInitialParameterValues(config);
  182. // allocate more pinned memory close to the above in an attempt to get the memory all together
  183. m_collisionArray = new CollisionDesc[m_maxCollisionsPerFrame];
  184. m_collisionArrayPinnedHandle = GCHandle.Alloc(m_collisionArray, GCHandleType.Pinned);
  185. m_updateArray = new EntityProperties[m_maxUpdatesPerFrame];
  186. m_updateArrayPinnedHandle = GCHandle.Alloc(m_updateArray, GCHandleType.Pinned);
  187. // Enable very detailed logging.
  188. // By creating an empty logger when not logging, the log message invocation code
  189. // can be left in and every call doesn't have to check for null.
  190. if (m_physicsLoggingEnabled)
  191. {
  192. PhysicsLogging = new Logging.LogWriter(m_physicsLoggingDir, m_physicsLoggingPrefix, m_physicsLoggingFileMinutes);
  193. PhysicsLogging.ErrorLogger = m_log; // for DEBUG. Let's the logger output error messages.
  194. }
  195. else
  196. {
  197. PhysicsLogging = new Logging.LogWriter();
  198. }
  199. // If Debug logging level, enable logging from the unmanaged code
  200. m_DebugLogCallbackHandle = null;
  201. if (m_log.IsDebugEnabled || PhysicsLogging.Enabled)
  202. {
  203. m_log.DebugFormat("{0}: Initialize: Setting debug callback for unmanaged code", LogHeader);
  204. if (PhysicsLogging.Enabled)
  205. // The handle is saved in a variable to make sure it doesn't get freed after this call
  206. m_DebugLogCallbackHandle = new BulletSimAPI.DebugLogCallback(BulletLoggerPhysLog);
  207. else
  208. m_DebugLogCallbackHandle = new BulletSimAPI.DebugLogCallback(BulletLogger);
  209. }
  210. // Get the version of the DLL
  211. // TODO: this doesn't work yet. Something wrong with marshaling the returned string.
  212. // BulletSimVersion = BulletSimAPI.GetVersion();
  213. // m_log.WarnFormat("{0}: BulletSim.dll version='{1}'", LogHeader, BulletSimVersion);
  214. // The bounding box for the simulated world. The origin is 0,0,0 unless we're
  215. // a child in a mega-region.
  216. // Bullet actually doesn't care about the extents of the simulated
  217. // area. It tracks active objects no matter where they are.
  218. Vector3 worldExtent = new Vector3(Constants.RegionSize, Constants.RegionSize, Constants.RegionHeight);
  219. // m_log.DebugFormat("{0}: Initialize: Calling BulletSimAPI.Initialize.", LogHeader);
  220. World = new BulletSim(0, this, BulletSimAPI.Initialize2(worldExtent, m_paramsHandle.AddrOfPinnedObject(),
  221. m_maxCollisionsPerFrame, m_collisionArrayPinnedHandle.AddrOfPinnedObject(),
  222. m_maxUpdatesPerFrame, m_updateArrayPinnedHandle.AddrOfPinnedObject(),
  223. m_DebugLogCallbackHandle));
  224. Constraints = new BSConstraintCollection(World);
  225. TerrainManager = new BSTerrainManager(this);
  226. TerrainManager.CreateInitialGroundPlaneAndTerrain();
  227. m_log.WarnFormat("{0} Linksets implemented with {1}", LogHeader, (BSLinkset.LinksetImplementation)Params.linksetImplementation);
  228. InTaintTime = false;
  229. m_initialized = true;
  230. }
  231. // All default parameter values are set here. There should be no values set in the
  232. // variable definitions.
  233. private void GetInitialParameterValues(IConfigSource config)
  234. {
  235. ConfigurationParameters parms = new ConfigurationParameters();
  236. m_params[0] = parms;
  237. SetParameterDefaultValues();
  238. if (config != null)
  239. {
  240. // If there are specifications in the ini file, use those values
  241. IConfig pConfig = config.Configs["BulletSim"];
  242. if (pConfig != null)
  243. {
  244. SetParameterConfigurationValues(pConfig);
  245. // Very detailed logging for physics debugging
  246. m_physicsLoggingEnabled = pConfig.GetBoolean("PhysicsLoggingEnabled", false);
  247. m_physicsLoggingDir = pConfig.GetString("PhysicsLoggingDir", ".");
  248. m_physicsLoggingPrefix = pConfig.GetString("PhysicsLoggingPrefix", "physics-%REGIONNAME%-");
  249. m_physicsLoggingFileMinutes = pConfig.GetInt("PhysicsLoggingFileMinutes", 5);
  250. m_physicsLoggingDoFlush = pConfig.GetBoolean("PhysicsLoggingDoFlush", false);
  251. // Very detailed logging for vehicle debugging
  252. VehicleLoggingEnabled = pConfig.GetBoolean("VehicleLoggingEnabled", false);
  253. // Do any replacements in the parameters
  254. m_physicsLoggingPrefix = m_physicsLoggingPrefix.Replace("%REGIONNAME%", RegionName);
  255. }
  256. // The material characteristics.
  257. BSMaterials.InitializeFromDefaults(Params);
  258. if (pConfig != null)
  259. {
  260. BSMaterials.InitializefromParameters(pConfig);
  261. }
  262. }
  263. }
  264. // A helper function that handles a true/false parameter and returns the proper float number encoding
  265. float ParamBoolean(IConfig config, string parmName, float deflt)
  266. {
  267. float ret = deflt;
  268. if (config.Contains(parmName))
  269. {
  270. ret = ConfigurationParameters.numericFalse;
  271. if (config.GetBoolean(parmName, false))
  272. {
  273. ret = ConfigurationParameters.numericTrue;
  274. }
  275. }
  276. return ret;
  277. }
  278. // Called directly from unmanaged code so don't do much
  279. private void BulletLogger(string msg)
  280. {
  281. m_log.Debug("[BULLETS UNMANAGED]:" + msg);
  282. }
  283. // Called directly from unmanaged code so don't do much
  284. private void BulletLoggerPhysLog(string msg)
  285. {
  286. DetailLog("[BULLETS UNMANAGED]:" + msg);
  287. }
  288. public override void Dispose()
  289. {
  290. // m_log.DebugFormat("{0}: Dispose()", LogHeader);
  291. // make sure no stepping happens while we're deleting stuff
  292. m_initialized = false;
  293. TerrainManager.ReleaseGroundPlaneAndTerrain();
  294. foreach (KeyValuePair<uint, BSPhysObject> kvp in PhysObjects)
  295. {
  296. kvp.Value.Destroy();
  297. }
  298. PhysObjects.Clear();
  299. // Now that the prims are all cleaned up, there should be no constraints left
  300. if (Constraints != null)
  301. {
  302. Constraints.Dispose();
  303. Constraints = null;
  304. }
  305. if (Shapes != null)
  306. {
  307. Shapes.Dispose();
  308. Shapes = null;
  309. }
  310. // Anything left in the unmanaged code should be cleaned out
  311. BulletSimAPI.Shutdown2(World.ptr);
  312. // Not logging any more
  313. PhysicsLogging.Close();
  314. }
  315. #endregion // Construction and Initialization
  316. #region Prim and Avatar addition and removal
  317. public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 size, bool isFlying)
  318. {
  319. m_log.ErrorFormat("{0}: CALL TO AddAvatar in BSScene. NOT IMPLEMENTED", LogHeader);
  320. return null;
  321. }
  322. public override PhysicsActor AddAvatar(uint localID, string avName, Vector3 position, Vector3 size, bool isFlying)
  323. {
  324. // m_log.DebugFormat("{0}: AddAvatar: {1}", LogHeader, avName);
  325. if (!m_initialized) return null;
  326. BSCharacter actor = new BSCharacter(localID, avName, this, position, size, isFlying);
  327. lock (PhysObjects) PhysObjects.Add(localID, actor);
  328. // TODO: Remove kludge someday.
  329. // We must generate a collision for avatars whether they collide or not.
  330. // This is required by OpenSim to update avatar animations, etc.
  331. lock (m_avatars) m_avatars.Add(actor);
  332. return actor;
  333. }
  334. public override void RemoveAvatar(PhysicsActor actor)
  335. {
  336. // m_log.DebugFormat("{0}: RemoveAvatar", LogHeader);
  337. if (!m_initialized) return;
  338. BSCharacter bsactor = actor as BSCharacter;
  339. if (bsactor != null)
  340. {
  341. try
  342. {
  343. lock (PhysObjects) PhysObjects.Remove(actor.LocalID);
  344. // Remove kludge someday
  345. lock (m_avatars) m_avatars.Remove(bsactor);
  346. }
  347. catch (Exception e)
  348. {
  349. m_log.WarnFormat("{0}: Attempt to remove avatar that is not in physics scene: {1}", LogHeader, e);
  350. }
  351. bsactor.Destroy();
  352. // bsactor.dispose();
  353. }
  354. }
  355. public override void RemovePrim(PhysicsActor prim)
  356. {
  357. if (!m_initialized) return;
  358. BSPrim bsprim = prim as BSPrim;
  359. if (bsprim != null)
  360. {
  361. DetailLog("{0},RemovePrim,call", bsprim.LocalID);
  362. // m_log.DebugFormat("{0}: RemovePrim. id={1}/{2}", LogHeader, bsprim.Name, bsprim.LocalID);
  363. try
  364. {
  365. lock (PhysObjects) PhysObjects.Remove(bsprim.LocalID);
  366. }
  367. catch (Exception e)
  368. {
  369. m_log.ErrorFormat("{0}: Attempt to remove prim that is not in physics scene: {1}", LogHeader, e);
  370. }
  371. bsprim.Destroy();
  372. // bsprim.dispose();
  373. }
  374. else
  375. {
  376. m_log.ErrorFormat("{0}: Attempt to remove prim that is not a BSPrim type.", LogHeader);
  377. }
  378. }
  379. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  380. Vector3 size, Quaternion rotation, bool isPhysical, uint localID)
  381. {
  382. // m_log.DebugFormat("{0}: AddPrimShape2: {1}", LogHeader, primName);
  383. if (!m_initialized) return null;
  384. DetailLog("{0},AddPrimShape,call", localID);
  385. BSPrim prim = new BSPrim(localID, primName, this, position, size, rotation, pbs, isPhysical);
  386. lock (PhysObjects) PhysObjects.Add(localID, prim);
  387. return prim;
  388. }
  389. // This is a call from the simulator saying that some physical property has been updated.
  390. // The BulletSim driver senses the changing of relevant properties so this taint
  391. // information call is not needed.
  392. public override void AddPhysicsActorTaint(PhysicsActor prim) { }
  393. #endregion // Prim and Avatar addition and removal
  394. #region Simulation
  395. // Simulate one timestep
  396. public override float Simulate(float timeStep)
  397. {
  398. int updatedEntityCount = 0;
  399. IntPtr updatedEntitiesPtr;
  400. int collidersCount = 0;
  401. IntPtr collidersPtr;
  402. int beforeTime = 0;
  403. int simTime = 0;
  404. // prevent simulation until we've been initialized
  405. if (!m_initialized) return 5.0f;
  406. // update the prim states while we know the physics engine is not busy
  407. int numTaints = _taintOperations.Count;
  408. ProcessTaints();
  409. // Some of the prims operate with special vehicle properties
  410. ProcessVehicles(timeStep);
  411. ProcessTaints(); // the vehicles might have added taints
  412. // step the physical world one interval
  413. m_simulationStep++;
  414. int numSubSteps = 0;
  415. try
  416. {
  417. // if (VehicleLoggingEnabled) DumpVehicles(); // DEBUG
  418. if (PhysicsLogging.Enabled) beforeTime = Util.EnvironmentTickCount();
  419. numSubSteps = BulletSimAPI.PhysicsStep2(World.ptr, timeStep, m_maxSubSteps, m_fixedTimeStep,
  420. out updatedEntityCount, out updatedEntitiesPtr, out collidersCount, out collidersPtr);
  421. if (PhysicsLogging.Enabled) simTime = Util.EnvironmentTickCountSubtract(beforeTime);
  422. DetailLog("{0},Simulate,call, frame={1}, nTaints={2}, simTime={3}, substeps={4}, updates={5}, colliders={6}",
  423. DetailLogZero, m_simulationStep, numTaints, simTime, numSubSteps, updatedEntityCount, collidersCount);
  424. // if (VehicleLoggingEnabled) DumpVehicles(); // DEBUG
  425. }
  426. catch (Exception e)
  427. {
  428. m_log.WarnFormat("{0},PhysicsStep Exception: nTaints={1}, substeps={2}, updates={3}, colliders={4}, e={5}",
  429. LogHeader, numTaints, numSubSteps, updatedEntityCount, collidersCount, e);
  430. DetailLog("{0},PhysicsStepException,call, nTaints={1}, substeps={2}, updates={3}, colliders={4}",
  431. DetailLogZero, numTaints, numSubSteps, updatedEntityCount, collidersCount);
  432. updatedEntityCount = 0;
  433. collidersCount = 0;
  434. }
  435. // Don't have to use the pointers passed back since we know it is the same pinned memory we passed in.
  436. // Get a value for 'now' so all the collision and update routines don't have to get their own.
  437. SimulationNowTime = Util.EnvironmentTickCount();
  438. // If there were collisions, process them by sending the event to the prim.
  439. // Collisions must be processed before updates.
  440. if (collidersCount > 0)
  441. {
  442. for (int ii = 0; ii < collidersCount; ii++)
  443. {
  444. uint cA = m_collisionArray[ii].aID;
  445. uint cB = m_collisionArray[ii].bID;
  446. Vector3 point = m_collisionArray[ii].point;
  447. Vector3 normal = m_collisionArray[ii].normal;
  448. SendCollision(cA, cB, point, normal, 0.01f);
  449. SendCollision(cB, cA, point, -normal, 0.01f);
  450. }
  451. }
  452. // The above SendCollision's batch up the collisions on the objects.
  453. // Now push the collisions into the simulator.
  454. if (ObjectsWithCollisions.Count > 0)
  455. {
  456. foreach (BSPhysObject bsp in ObjectsWithCollisions)
  457. if (!bsp.SendCollisions())
  458. {
  459. // If the object is done colliding, see that it's removed from the colliding list
  460. ObjectsWithNoMoreCollisions.Add(bsp);
  461. }
  462. }
  463. // This is a kludge to get avatar movement updates.
  464. // The simulator expects collisions for avatars even if there are have been no collisions.
  465. // The event updates avatar animations and stuff.
  466. // If you fix avatar animation updates, remove this overhead and let normal collision processing happen.
  467. foreach (BSPhysObject bsp in m_avatars)
  468. if (!ObjectsWithCollisions.Contains(bsp)) // don't call avatars twice
  469. bsp.SendCollisions();
  470. // Objects that are done colliding are removed from the ObjectsWithCollisions list.
  471. // Not done above because it is inside an iteration of ObjectWithCollisions.
  472. if (ObjectsWithNoMoreCollisions.Count > 0)
  473. {
  474. foreach (BSPhysObject po in ObjectsWithNoMoreCollisions)
  475. ObjectsWithCollisions.Remove(po);
  476. ObjectsWithNoMoreCollisions.Clear();
  477. }
  478. // Done with collisions.
  479. // If any of the objects had updated properties, tell the object it has been changed by the physics engine
  480. if (updatedEntityCount > 0)
  481. {
  482. for (int ii = 0; ii < updatedEntityCount; ii++)
  483. {
  484. EntityProperties entprop = m_updateArray[ii];
  485. BSPhysObject pobj;
  486. if (PhysObjects.TryGetValue(entprop.ID, out pobj))
  487. {
  488. pobj.UpdateProperties(entprop);
  489. }
  490. }
  491. }
  492. ProcessPostStepTaints();
  493. // This causes the unmanaged code to output ALL the values found in ALL the objects in the world.
  494. // Only enable this in a limited test world with few objects.
  495. // BulletSimAPI.DumpAllInfo2(World.ptr); // DEBUG DEBUG DEBUG
  496. // The physics engine returns the number of milliseconds it simulated this call.
  497. // These are summed and normalized to one second and divided by 1000 to give the reported physics FPS.
  498. // Multiply by 55 to give a nominal frame rate of 55.
  499. return (float)numSubSteps * m_fixedTimeStep * 1000f * 55f;
  500. }
  501. // Something has collided
  502. private void SendCollision(uint localID, uint collidingWith, Vector3 collidePoint, Vector3 collideNormal, float penetration)
  503. {
  504. if (localID <= TerrainManager.HighestTerrainID)
  505. {
  506. return; // don't send collisions to the terrain
  507. }
  508. BSPhysObject collider;
  509. if (!PhysObjects.TryGetValue(localID, out collider))
  510. {
  511. // If the object that is colliding cannot be found, just ignore the collision.
  512. DetailLog("{0},BSScene.SendCollision,colliderNotInObjectList,id={1},with={2}", DetailLogZero, localID, collidingWith);
  513. return;
  514. }
  515. // The terrain is not in the physical object list so 'collidee' can be null when Collide() is called.
  516. BSPhysObject collidee = null;
  517. PhysObjects.TryGetValue(collidingWith, out collidee);
  518. // DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith);
  519. if (collider.Collide(collidingWith, collidee, collidePoint, collideNormal, penetration))
  520. {
  521. // If a collision was posted, remember to send it to the simulator
  522. ObjectsWithCollisions.Add(collider);
  523. }
  524. return;
  525. }
  526. #endregion // Simulation
  527. public override void GetResults() { }
  528. #region Terrain
  529. public override void SetTerrain(float[] heightMap) {
  530. TerrainManager.SetTerrain(heightMap);
  531. }
  532. public override void SetWaterLevel(float baseheight)
  533. {
  534. SimpleWaterLevel = baseheight;
  535. }
  536. public override void DeleteTerrain()
  537. {
  538. // m_log.DebugFormat("{0}: DeleteTerrain()", LogHeader);
  539. }
  540. // Although no one seems to check this, I do support combining.
  541. public override bool SupportsCombining()
  542. {
  543. return TerrainManager.SupportsCombining();
  544. }
  545. // This call says I am a child to region zero in a mega-region. 'pScene' is that
  546. // of region zero, 'offset' is my offset from regions zero's origin, and
  547. // 'extents' is the largest XY that is handled in my region.
  548. public override void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents)
  549. {
  550. TerrainManager.Combine(pScene, offset, extents);
  551. }
  552. // Unhook all the combining that I know about.
  553. public override void UnCombine(PhysicsScene pScene)
  554. {
  555. TerrainManager.UnCombine(pScene);
  556. }
  557. #endregion // Terrain
  558. public override Dictionary<uint, float> GetTopColliders()
  559. {
  560. return new Dictionary<uint, float>();
  561. }
  562. public override bool IsThreaded { get { return false; } }
  563. #region Taints
  564. // Calls to the PhysicsActors can't directly call into the physics engine
  565. // because it might be busy. We delay changes to a known time.
  566. // We rely on C#'s closure to save and restore the context for the delegate.
  567. public void TaintedObject(String ident, TaintCallback callback)
  568. {
  569. if (!m_initialized) return;
  570. lock (_taintLock)
  571. {
  572. _taintOperations.Add(new TaintCallbackEntry(ident, callback));
  573. }
  574. return;
  575. }
  576. // Sometimes a potentially tainted operation can be used in and out of taint time.
  577. // This routine executes the command immediately if in taint-time otherwise it is queued.
  578. public void TaintedObject(bool inTaintTime, string ident, TaintCallback callback)
  579. {
  580. if (inTaintTime)
  581. callback();
  582. else
  583. TaintedObject(ident, callback);
  584. }
  585. // When someone tries to change a property on a BSPrim or BSCharacter, the object queues
  586. // a callback into itself to do the actual property change. That callback is called
  587. // here just before the physics engine is called to step the simulation.
  588. public void ProcessTaints()
  589. {
  590. InTaintTime = true; // Only used for debugging so locking is not necessary.
  591. ProcessRegularTaints();
  592. ProcessPostTaintTaints();
  593. InTaintTime = false;
  594. }
  595. private void ProcessRegularTaints()
  596. {
  597. if (_taintOperations.Count > 0) // save allocating new list if there is nothing to process
  598. {
  599. /*
  600. // Code to limit the number of taints processed per step. Meant to limit step time.
  601. // Unsure if a good idea as code assumes that taints are done before the step.
  602. int taintCount = m_taintsToProcessPerStep;
  603. TaintCallbackEntry oneCallback = new TaintCallbackEntry();
  604. while (_taintOperations.Count > 0 && taintCount-- > 0)
  605. {
  606. bool gotOne = false;
  607. lock (_taintLock)
  608. {
  609. if (_taintOperations.Count > 0)
  610. {
  611. oneCallback = _taintOperations[0];
  612. _taintOperations.RemoveAt(0);
  613. gotOne = true;
  614. }
  615. }
  616. if (gotOne)
  617. {
  618. try
  619. {
  620. DetailLog("{0},BSScene.ProcessTaints,doTaint,id={1}", DetailLogZero, oneCallback.ident);
  621. oneCallback.callback();
  622. }
  623. catch (Exception e)
  624. {
  625. DetailLog("{0},BSScene.ProcessTaints,doTaintException,id={1}", DetailLogZero, oneCallback.ident); // DEBUG DEBUG DEBUG
  626. m_log.ErrorFormat("{0}: ProcessTaints: {1}: Exception: {2}", LogHeader, oneCallback.ident, e);
  627. }
  628. }
  629. }
  630. if (_taintOperations.Count > 0)
  631. {
  632. DetailLog("{0},BSScene.ProcessTaints,leftTaintsOnList,numNotProcessed={1}", DetailLogZero, _taintOperations.Count);
  633. }
  634. */
  635. // swizzle a new list into the list location so we can process what's there
  636. List<TaintCallbackEntry> oldList;
  637. lock (_taintLock)
  638. {
  639. oldList = _taintOperations;
  640. _taintOperations = new List<TaintCallbackEntry>();
  641. }
  642. foreach (TaintCallbackEntry tcbe in oldList)
  643. {
  644. try
  645. {
  646. DetailLog("{0},BSScene.ProcessTaints,doTaint,id={1}", DetailLogZero, tcbe.ident); // DEBUG DEBUG DEBUG
  647. tcbe.callback();
  648. }
  649. catch (Exception e)
  650. {
  651. m_log.ErrorFormat("{0}: ProcessTaints: {1}: Exception: {2}", LogHeader, tcbe.ident, e);
  652. }
  653. }
  654. oldList.Clear();
  655. }
  656. }
  657. // Schedule an update to happen after all the regular taints are processed.
  658. // Note that new requests for the same operation ("ident") for the same object ("ID")
  659. // will replace any previous operation by the same object.
  660. public void PostTaintObject(String ident, uint ID, TaintCallback callback)
  661. {
  662. string uniqueIdent = ident + "-" + ID.ToString();
  663. lock (_taintLock)
  664. {
  665. _postTaintOperations[uniqueIdent] = new TaintCallbackEntry(uniqueIdent, callback);
  666. }
  667. return;
  668. }
  669. private void ProcessPostTaintTaints()
  670. {
  671. if (_postTaintOperations.Count > 0)
  672. {
  673. Dictionary<string, TaintCallbackEntry> oldList;
  674. lock (_taintLock)
  675. {
  676. oldList = _postTaintOperations;
  677. _postTaintOperations = new Dictionary<string, TaintCallbackEntry>();
  678. }
  679. foreach (KeyValuePair<string,TaintCallbackEntry> kvp in oldList)
  680. {
  681. try
  682. {
  683. DetailLog("{0},BSScene.ProcessPostTaintTaints,doTaint,id={1}", DetailLogZero, kvp.Key); // DEBUG DEBUG DEBUG
  684. kvp.Value.callback();
  685. }
  686. catch (Exception e)
  687. {
  688. m_log.ErrorFormat("{0}: ProcessPostTaintTaints: {1}: Exception: {2}", LogHeader, kvp.Key, e);
  689. }
  690. }
  691. oldList.Clear();
  692. }
  693. }
  694. public void PostStepTaintObject(String ident, TaintCallback callback)
  695. {
  696. if (!m_initialized) return;
  697. lock (_taintLock)
  698. {
  699. _postStepOperations.Add(new TaintCallbackEntry(ident, callback));
  700. }
  701. return;
  702. }
  703. private void ProcessPostStepTaints()
  704. {
  705. if (_postStepOperations.Count > 0)
  706. {
  707. List<TaintCallbackEntry> oldList;
  708. lock (_taintLock)
  709. {
  710. oldList = _postStepOperations;
  711. _postStepOperations = new List<TaintCallbackEntry>();
  712. }
  713. foreach (TaintCallbackEntry tcbe in oldList)
  714. {
  715. try
  716. {
  717. DetailLog("{0},BSScene.ProcessPostStepTaints,doTaint,id={1}", DetailLogZero, tcbe.ident); // DEBUG DEBUG DEBUG
  718. tcbe.callback();
  719. }
  720. catch (Exception e)
  721. {
  722. m_log.ErrorFormat("{0}: ProcessPostStepTaints: {1}: Exception: {2}", LogHeader, tcbe.ident, e);
  723. }
  724. }
  725. oldList.Clear();
  726. }
  727. }
  728. // Only used for debugging. Does not change state of anything so locking is not necessary.
  729. public bool AssertInTaintTime(string whereFrom)
  730. {
  731. if (!InTaintTime)
  732. {
  733. DetailLog("{0},BSScene.AssertInTaintTime,NOT IN TAINT TIME,Region={1},Where={2}", DetailLogZero, RegionName, whereFrom);
  734. m_log.ErrorFormat("{0} NOT IN TAINT TIME!! Region={1}, Where={2}", LogHeader, RegionName, whereFrom);
  735. Util.PrintCallStack(); // Prints the stack into the DEBUG log file.
  736. }
  737. return InTaintTime;
  738. }
  739. #endregion // Taints
  740. #region Vehicles
  741. public void VehicleInSceneTypeChanged(BSPrim vehic, Vehicle newType)
  742. {
  743. RemoveVehiclePrim(vehic);
  744. if (newType != Vehicle.TYPE_NONE)
  745. {
  746. // make it so the scene will call us each tick to do vehicle things
  747. AddVehiclePrim(vehic);
  748. }
  749. }
  750. // Make so the scene will call this prim for vehicle actions each tick.
  751. // Safe to call if prim is already in the vehicle list.
  752. public void AddVehiclePrim(BSPrim vehicle)
  753. {
  754. lock (m_vehicles)
  755. {
  756. if (!m_vehicles.Contains(vehicle))
  757. {
  758. m_vehicles.Add(vehicle);
  759. }
  760. }
  761. }
  762. // Remove a prim from our list of vehicles.
  763. // Safe to call if the prim is not in the vehicle list.
  764. public void RemoveVehiclePrim(BSPrim vehicle)
  765. {
  766. lock (m_vehicles)
  767. {
  768. if (m_vehicles.Contains(vehicle))
  769. {
  770. m_vehicles.Remove(vehicle);
  771. }
  772. }
  773. }
  774. // Some prims have extra vehicle actions
  775. // Called at taint time!
  776. private void ProcessVehicles(float timeStep)
  777. {
  778. foreach (BSPhysObject pobj in m_vehicles)
  779. {
  780. pobj.StepVehicle(timeStep);
  781. }
  782. }
  783. #endregion Vehicles
  784. #region INI and command line parameter processing
  785. delegate void ParamUser(BSScene scene, IConfig conf, string paramName, float val);
  786. delegate float ParamGet(BSScene scene);
  787. delegate void ParamSet(BSScene scene, string paramName, uint localID, float val);
  788. delegate void SetOnObject(BSScene scene, BSPhysObject obj, float val);
  789. private struct ParameterDefn
  790. {
  791. public string name; // string name of the parameter
  792. public string desc; // a short description of what the parameter means
  793. public float defaultValue; // default value if not specified anywhere else
  794. public ParamUser userParam; // get the value from the configuration file
  795. public ParamGet getter; // return the current value stored for this parameter
  796. public ParamSet setter; // set the current value for this parameter
  797. public SetOnObject onObject; // set the value on an object in the physical domain
  798. public ParameterDefn(string n, string d, float v, ParamUser u, ParamGet g, ParamSet s)
  799. {
  800. name = n;
  801. desc = d;
  802. defaultValue = v;
  803. userParam = u;
  804. getter = g;
  805. setter = s;
  806. onObject = null;
  807. }
  808. public ParameterDefn(string n, string d, float v, ParamUser u, ParamGet g, ParamSet s, SetOnObject o)
  809. {
  810. name = n;
  811. desc = d;
  812. defaultValue = v;
  813. userParam = u;
  814. getter = g;
  815. setter = s;
  816. onObject = o;
  817. }
  818. }
  819. // List of all of the externally visible parameters.
  820. // For each parameter, this table maps a text name to getter and setters.
  821. // To add a new externally referencable/settable parameter, add the paramter storage
  822. // location somewhere in the program and make an entry in this table with the
  823. // getters and setters.
  824. // It is easiest to find an existing definition and copy it.
  825. // Parameter values are floats. Booleans are converted to a floating value.
  826. //
  827. // A ParameterDefn() takes the following parameters:
  828. // -- the text name of the parameter. This is used for console input and ini file.
  829. // -- a short text description of the parameter. This shows up in the console listing.
  830. // -- a delegate for fetching the parameter from the ini file.
  831. // Should handle fetching the right type from the ini file and converting it.
  832. // -- a delegate for getting the value as a float
  833. // -- a delegate for setting the value from a float
  834. //
  835. // The single letter parameters for the delegates are:
  836. // s = BSScene
  837. // o = BSPhysObject
  838. // p = string parameter name
  839. // l = localID of referenced object
  840. // v = float value
  841. // cf = parameter configuration class (for fetching values from ini file)
  842. private ParameterDefn[] ParameterDefinitions =
  843. {
  844. new ParameterDefn("MeshSculptedPrim", "Whether to create meshes for sculpties",
  845. ConfigurationParameters.numericTrue,
  846. (s,cf,p,v) => { s.ShouldMeshSculptedPrim = cf.GetBoolean(p, s.BoolNumeric(v)); },
  847. (s) => { return s.NumericBool(s.ShouldMeshSculptedPrim); },
  848. (s,p,l,v) => { s.ShouldMeshSculptedPrim = s.BoolNumeric(v); } ),
  849. new ParameterDefn("ForceSimplePrimMeshing", "If true, only use primitive meshes for objects",
  850. ConfigurationParameters.numericFalse,
  851. (s,cf,p,v) => { s.ShouldForceSimplePrimMeshing = cf.GetBoolean(p, s.BoolNumeric(v)); },
  852. (s) => { return s.NumericBool(s.ShouldForceSimplePrimMeshing); },
  853. (s,p,l,v) => { s.ShouldForceSimplePrimMeshing = s.BoolNumeric(v); } ),
  854. new ParameterDefn("UseHullsForPhysicalObjects", "If true, create hulls for physical objects",
  855. ConfigurationParameters.numericTrue,
  856. (s,cf,p,v) => { s.ShouldUseHullsForPhysicalObjects = cf.GetBoolean(p, s.BoolNumeric(v)); },
  857. (s) => { return s.NumericBool(s.ShouldUseHullsForPhysicalObjects); },
  858. (s,p,l,v) => { s.ShouldUseHullsForPhysicalObjects = s.BoolNumeric(v); } ),
  859. new ParameterDefn("MeshLevelOfDetail", "Level of detail to render meshes (32, 16, 8 or 4. 32=most detailed)",
  860. 8f,
  861. (s,cf,p,v) => { s.MeshLOD = (float)cf.GetInt(p, (int)v); },
  862. (s) => { return s.MeshLOD; },
  863. (s,p,l,v) => { s.MeshLOD = v; } ),
  864. new ParameterDefn("MeshLevelOfDetailMegaPrim", "Level of detail to render meshes larger than threshold meters",
  865. 16f,
  866. (s,cf,p,v) => { s.MeshMegaPrimLOD = (float)cf.GetInt(p, (int)v); },
  867. (s) => { return s.MeshMegaPrimLOD; },
  868. (s,p,l,v) => { s.MeshMegaPrimLOD = v; } ),
  869. new ParameterDefn("MeshLevelOfDetailMegaPrimThreshold", "Size (in meters) of a mesh before using MeshMegaPrimLOD",
  870. 10f,
  871. (s,cf,p,v) => { s.MeshMegaPrimThreshold = (float)cf.GetInt(p, (int)v); },
  872. (s) => { return s.MeshMegaPrimThreshold; },
  873. (s,p,l,v) => { s.MeshMegaPrimThreshold = v; } ),
  874. new ParameterDefn("SculptLevelOfDetail", "Level of detail to render sculpties (32, 16, 8 or 4. 32=most detailed)",
  875. 32f,
  876. (s,cf,p,v) => { s.SculptLOD = (float)cf.GetInt(p, (int)v); },
  877. (s) => { return s.SculptLOD; },
  878. (s,p,l,v) => { s.SculptLOD = v; } ),
  879. new ParameterDefn("MaxSubStep", "In simulation step, maximum number of substeps",
  880. 10f,
  881. (s,cf,p,v) => { s.m_maxSubSteps = cf.GetInt(p, (int)v); },
  882. (s) => { return (float)s.m_maxSubSteps; },
  883. (s,p,l,v) => { s.m_maxSubSteps = (int)v; } ),
  884. new ParameterDefn("FixedTimeStep", "In simulation step, seconds of one substep (1/60)",
  885. 1f / 60f,
  886. (s,cf,p,v) => { s.m_fixedTimeStep = cf.GetFloat(p, v); },
  887. (s) => { return (float)s.m_fixedTimeStep; },
  888. (s,p,l,v) => { s.m_fixedTimeStep = v; } ),
  889. new ParameterDefn("MaxCollisionsPerFrame", "Max collisions returned at end of each frame",
  890. 2048f,
  891. (s,cf,p,v) => { s.m_maxCollisionsPerFrame = cf.GetInt(p, (int)v); },
  892. (s) => { return (float)s.m_maxCollisionsPerFrame; },
  893. (s,p,l,v) => { s.m_maxCollisionsPerFrame = (int)v; } ),
  894. new ParameterDefn("MaxUpdatesPerFrame", "Max updates returned at end of each frame",
  895. 8000f,
  896. (s,cf,p,v) => { s.m_maxUpdatesPerFrame = cf.GetInt(p, (int)v); },
  897. (s) => { return (float)s.m_maxUpdatesPerFrame; },
  898. (s,p,l,v) => { s.m_maxUpdatesPerFrame = (int)v; } ),
  899. new ParameterDefn("MaxTaintsToProcessPerStep", "Number of update taints to process before each simulation step",
  900. 500f,
  901. (s,cf,p,v) => { s.m_taintsToProcessPerStep = cf.GetInt(p, (int)v); },
  902. (s) => { return (float)s.m_taintsToProcessPerStep; },
  903. (s,p,l,v) => { s.m_taintsToProcessPerStep = (int)v; } ),
  904. new ParameterDefn("MaxObjectMass", "Maximum object mass (10000.01)",
  905. 10000.01f,
  906. (s,cf,p,v) => { s.MaximumObjectMass = cf.GetFloat(p, v); },
  907. (s) => { return (float)s.MaximumObjectMass; },
  908. (s,p,l,v) => { s.MaximumObjectMass = v; } ),
  909. new ParameterDefn("PID_D", "Derivitive factor for motion smoothing",
  910. 2200f,
  911. (s,cf,p,v) => { s.PID_D = cf.GetFloat(p, v); },
  912. (s) => { return (float)s.PID_D; },
  913. (s,p,l,v) => { s.PID_D = v; } ),
  914. new ParameterDefn("PID_P", "Parameteric factor for motion smoothing",
  915. 900f,
  916. (s,cf,p,v) => { s.PID_P = cf.GetFloat(p, v); },
  917. (s) => { return (float)s.PID_P; },
  918. (s,p,l,v) => { s.PID_P = v; } ),
  919. new ParameterDefn("DefaultFriction", "Friction factor used on new objects",
  920. 0.2f,
  921. (s,cf,p,v) => { s.m_params[0].defaultFriction = cf.GetFloat(p, v); },
  922. (s) => { return s.m_params[0].defaultFriction; },
  923. (s,p,l,v) => { s.m_params[0].defaultFriction = v; } ),
  924. new ParameterDefn("DefaultDensity", "Density for new objects" ,
  925. 10.000006836f, // Aluminum g/cm3
  926. (s,cf,p,v) => { s.m_params[0].defaultDensity = cf.GetFloat(p, v); },
  927. (s) => { return s.m_params[0].defaultDensity; },
  928. (s,p,l,v) => { s.m_params[0].defaultDensity = v; } ),
  929. new ParameterDefn("DefaultRestitution", "Bouncyness of an object" ,
  930. 0f,
  931. (s,cf,p,v) => { s.m_params[0].defaultRestitution = cf.GetFloat(p, v); },
  932. (s) => { return s.m_params[0].defaultRestitution; },
  933. (s,p,l,v) => { s.m_params[0].defaultRestitution = v; } ),
  934. new ParameterDefn("CollisionMargin", "Margin around objects before collisions are calculated (must be zero!)",
  935. 0.04f,
  936. (s,cf,p,v) => { s.m_params[0].collisionMargin = cf.GetFloat(p, v); },
  937. (s) => { return s.m_params[0].collisionMargin; },
  938. (s,p,l,v) => { s.m_params[0].collisionMargin = v; } ),
  939. new ParameterDefn("Gravity", "Vertical force of gravity (negative means down)",
  940. -9.80665f,
  941. (s,cf,p,v) => { s.m_params[0].gravity = cf.GetFloat(p, v); },
  942. (s) => { return s.m_params[0].gravity; },
  943. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].gravity, p, PhysParameterEntry.APPLY_TO_NONE, v); },
  944. (s,o,v) => { BulletSimAPI.SetGravity2(s.World.ptr, new Vector3(0f,0f,v)); } ),
  945. new ParameterDefn("LinearDamping", "Factor to damp linear movement per second (0.0 - 1.0)",
  946. 0f,
  947. (s,cf,p,v) => { s.m_params[0].linearDamping = cf.GetFloat(p, v); },
  948. (s) => { return s.m_params[0].linearDamping; },
  949. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].linearDamping, p, l, v); },
  950. (s,o,v) => { BulletSimAPI.SetDamping2(o.PhysBody.ptr, v, s.m_params[0].angularDamping); } ),
  951. new ParameterDefn("AngularDamping", "Factor to damp angular movement per second (0.0 - 1.0)",
  952. 0f,
  953. (s,cf,p,v) => { s.m_params[0].angularDamping = cf.GetFloat(p, v); },
  954. (s) => { return s.m_params[0].angularDamping; },
  955. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].angularDamping, p, l, v); },
  956. (s,o,v) => { BulletSimAPI.SetDamping2(o.PhysBody.ptr, s.m_params[0].linearDamping, v); } ),
  957. new ParameterDefn("DeactivationTime", "Seconds before considering an object potentially static",
  958. 0.2f,
  959. (s,cf,p,v) => { s.m_params[0].deactivationTime = cf.GetFloat(p, v); },
  960. (s) => { return s.m_params[0].deactivationTime; },
  961. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].deactivationTime, p, l, v); },
  962. (s,o,v) => { BulletSimAPI.SetDeactivationTime2(o.PhysBody.ptr, v); } ),
  963. new ParameterDefn("LinearSleepingThreshold", "Seconds to measure linear movement before considering static",
  964. 0.8f,
  965. (s,cf,p,v) => { s.m_params[0].linearSleepingThreshold = cf.GetFloat(p, v); },
  966. (s) => { return s.m_params[0].linearSleepingThreshold; },
  967. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].linearSleepingThreshold, p, l, v); },
  968. (s,o,v) => { BulletSimAPI.SetSleepingThresholds2(o.PhysBody.ptr, v, v); } ),
  969. new ParameterDefn("AngularSleepingThreshold", "Seconds to measure angular movement before considering static",
  970. 1.0f,
  971. (s,cf,p,v) => { s.m_params[0].angularSleepingThreshold = cf.GetFloat(p, v); },
  972. (s) => { return s.m_params[0].angularSleepingThreshold; },
  973. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].angularSleepingThreshold, p, l, v); },
  974. (s,o,v) => { BulletSimAPI.SetSleepingThresholds2(o.PhysBody.ptr, v, v); } ),
  975. new ParameterDefn("CcdMotionThreshold", "Continuious collision detection threshold (0 means no CCD)" ,
  976. 0f, // set to zero to disable
  977. (s,cf,p,v) => { s.m_params[0].ccdMotionThreshold = cf.GetFloat(p, v); },
  978. (s) => { return s.m_params[0].ccdMotionThreshold; },
  979. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].ccdMotionThreshold, p, l, v); },
  980. (s,o,v) => { BulletSimAPI.SetCcdMotionThreshold2(o.PhysBody.ptr, v); } ),
  981. new ParameterDefn("CcdSweptSphereRadius", "Continuious collision detection test radius" ,
  982. 0f,
  983. (s,cf,p,v) => { s.m_params[0].ccdSweptSphereRadius = cf.GetFloat(p, v); },
  984. (s) => { return s.m_params[0].ccdSweptSphereRadius; },
  985. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].ccdSweptSphereRadius, p, l, v); },
  986. (s,o,v) => { BulletSimAPI.SetCcdSweptSphereRadius2(o.PhysBody.ptr, v); } ),
  987. new ParameterDefn("ContactProcessingThreshold", "Distance between contacts before doing collision check" ,
  988. 0.1f,
  989. (s,cf,p,v) => { s.m_params[0].contactProcessingThreshold = cf.GetFloat(p, v); },
  990. (s) => { return s.m_params[0].contactProcessingThreshold; },
  991. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].contactProcessingThreshold, p, l, v); },
  992. (s,o,v) => { BulletSimAPI.SetContactProcessingThreshold2(o.PhysBody.ptr, v); } ),
  993. new ParameterDefn("TerrainImplementation", "Type of shape to use for terrain (0=heightmap, 1=mesh)",
  994. (float)BSTerrainPhys.TerrainImplementation.Mesh,
  995. (s,cf,p,v) => { s.m_params[0].terrainImplementation = cf.GetFloat(p,v); },
  996. (s) => { return s.m_params[0].terrainImplementation; },
  997. (s,p,l,v) => { s.m_params[0].terrainImplementation = v; } ),
  998. new ParameterDefn("TerrainFriction", "Factor to reduce movement against terrain surface" ,
  999. 0.3f,
  1000. (s,cf,p,v) => { s.m_params[0].terrainFriction = cf.GetFloat(p, v); },
  1001. (s) => { return s.m_params[0].terrainFriction; },
  1002. (s,p,l,v) => { s.m_params[0].terrainFriction = v; /* TODO: set on real terrain */} ),
  1003. new ParameterDefn("TerrainHitFraction", "Distance to measure hit collisions" ,
  1004. 0.8f,
  1005. (s,cf,p,v) => { s.m_params[0].terrainHitFraction = cf.GetFloat(p, v); },
  1006. (s) => { return s.m_params[0].terrainHitFraction; },
  1007. (s,p,l,v) => { s.m_params[0].terrainHitFraction = v; /* TODO: set on real terrain */ } ),
  1008. new ParameterDefn("TerrainRestitution", "Bouncyness" ,
  1009. 0f,
  1010. (s,cf,p,v) => { s.m_params[0].terrainRestitution = cf.GetFloat(p, v); },
  1011. (s) => { return s.m_params[0].terrainRestitution; },
  1012. (s,p,l,v) => { s.m_params[0].terrainRestitution = v; /* TODO: set on real terrain */ } ),
  1013. new ParameterDefn("TerrainCollisionMargin", "Margin where collision checking starts" ,
  1014. 0.04f,
  1015. (s,cf,p,v) => { s.m_params[0].terrainCollisionMargin = cf.GetFloat(p, v); },
  1016. (s) => { return s.m_params[0].terrainCollisionMargin; },
  1017. (s,p,l,v) => { s.m_params[0].terrainCollisionMargin = v; /* TODO: set on real terrain */ } ),
  1018. new ParameterDefn("AvatarFriction", "Factor to reduce movement against an avatar. Changed on avatar recreation.",
  1019. 0.2f,
  1020. (s,cf,p,v) => { s.m_params[0].avatarFriction = cf.GetFloat(p, v); },
  1021. (s) => { return s.m_params[0].avatarFriction; },
  1022. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarFriction, p, l, v); } ),
  1023. new ParameterDefn("AvatarStandingFriction", "Avatar friction when standing. Changed on avatar recreation.",
  1024. 10.0f,
  1025. (s,cf,p,v) => { s.m_params[0].avatarStandingFriction = cf.GetFloat(p, v); },
  1026. (s) => { return s.m_params[0].avatarStandingFriction; },
  1027. (s,p,l,v) => { s.m_params[0].avatarStandingFriction = v; } ),
  1028. new ParameterDefn("AvatarDensity", "Density of an avatar. Changed on avatar recreation.",
  1029. 60f,
  1030. (s,cf,p,v) => { s.m_params[0].avatarDensity = cf.GetFloat(p, v); },
  1031. (s) => { return s.m_params[0].avatarDensity; },
  1032. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarDensity, p, l, v); } ),
  1033. new ParameterDefn("AvatarRestitution", "Bouncyness. Changed on avatar recreation.",
  1034. 0f,
  1035. (s,cf,p,v) => { s.m_params[0].avatarRestitution = cf.GetFloat(p, v); },
  1036. (s) => { return s.m_params[0].avatarRestitution; },
  1037. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarRestitution, p, l, v); } ),
  1038. new ParameterDefn("AvatarCapsuleWidth", "The distance between the sides of the avatar capsule",
  1039. 0.6f,
  1040. (s,cf,p,v) => { s.m_params[0].avatarCapsuleWidth = cf.GetFloat(p, v); },
  1041. (s) => { return s.m_params[0].avatarCapsuleWidth; },
  1042. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarCapsuleWidth, p, l, v); } ),
  1043. new ParameterDefn("AvatarCapsuleDepth", "The distance between the front and back of the avatar capsule",
  1044. 0.45f,
  1045. (s,cf,p,v) => { s.m_params[0].avatarCapsuleDepth = cf.GetFloat(p, v); },
  1046. (s) => { return s.m_params[0].avatarCapsuleDepth; },
  1047. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarCapsuleDepth, p, l, v); } ),
  1048. new ParameterDefn("AvatarCapsuleHeight", "Default height of space around avatar",
  1049. 1.5f,
  1050. (s,cf,p,v) => { s.m_params[0].avatarCapsuleHeight = cf.GetFloat(p, v); },
  1051. (s) => { return s.m_params[0].avatarCapsuleHeight; },
  1052. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarCapsuleHeight, p, l, v); } ),
  1053. new ParameterDefn("AvatarContactProcessingThreshold", "Distance from capsule to check for collisions",
  1054. 0.1f,
  1055. (s,cf,p,v) => { s.m_params[0].avatarContactProcessingThreshold = cf.GetFloat(p, v); },
  1056. (s) => { return s.m_params[0].avatarContactProcessingThreshold; },
  1057. (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarContactProcessingThreshold, p, l, v); } ),
  1058. new ParameterDefn("VehicleAngularDamping", "Factor to damp vehicle angular movement per second (0.0 - 1.0)",
  1059. 0.95f,
  1060. (s,cf,p,v) => { s.m_params[0].vehicleAngularDamping = cf.GetFloat(p, v); },
  1061. (s) => { return s.m_params[0].vehicleAngularDamping; },
  1062. (s,p,l,v) => { s.m_params[0].vehicleAngularDamping = v; } ),
  1063. new ParameterDefn("MaxPersistantManifoldPoolSize", "Number of manifolds pooled (0 means default of 4096)",
  1064. 0f,
  1065. (s,cf,p,v) => { s.m_params[0].maxPersistantManifoldPoolSize = cf.GetFloat(p, v); },
  1066. (s) => { return s.m_params[0].maxPersistantManifoldPoolSize; },
  1067. (s,p,l,v) => { s.m_params[0].maxPersistantManifoldPoolSize = v; } ),
  1068. new ParameterDefn("MaxCollisionAlgorithmPoolSize", "Number of collisions pooled (0 means default of 4096)",
  1069. 0f,
  1070. (s,cf,p,v) => { s.m_params[0].maxCollisionAlgorithmPoolSize = cf.GetFloat(p, v); },
  1071. (s) => { return s.m_params[0].maxCollisionAlgorithmPoolSize; },
  1072. (s,p,l,v) => { s.m_params[0].maxCollisionAlgorithmPoolSize = v; } ),
  1073. new ParameterDefn("ShouldDisableContactPoolDynamicAllocation", "Enable to allow large changes in object count",
  1074. ConfigurationParameters.numericFalse,
  1075. (s,cf,p,v) => { s.m_params[0].shouldDisableContactPoolDynamicAllocation = s.NumericBool(cf.GetBoolean(p, s.BoolNumeric(v))); },
  1076. (s) => { return s.m_params[0].shouldDisableContactPoolDynamicAllocation; },
  1077. (s,p,l,v) => { s.m_params[0].shouldDisableContactPoolDynamicAllocation = v; } ),
  1078. new ParameterDefn("ShouldForceUpdateAllAabbs", "Enable to recomputer AABBs every simulator step",
  1079. ConfigurationParameters.numericFalse,
  1080. (s,cf,p,v) => { s.m_params[0].shouldForceUpdateAllAabbs = s.NumericBool(cf.GetBoolean(p, s.BoolNumeric(v))); },
  1081. (s) => { return s.m_params[0].shouldForceUpdateAllAabbs; },
  1082. (s,p,l,v) => { s.m_params[0].shouldForceUpdateAllAabbs = v; } ),
  1083. new ParameterDefn("ShouldRandomizeSolverOrder", "Enable for slightly better stacking interaction",
  1084. ConfigurationParameters.numericTrue,
  1085. (s,cf,p,v) => { s.m_params[0].shouldRandomizeSolverOrder = s.NumericBool(cf.GetBoolean(p, s.BoolNumeric(v))); },
  1086. (s) => { return s.m_params[0].shouldRandomizeSolverOrder; },
  1087. (s,p,l,v) => { s.m_params[0].shouldRandomizeSolverOrder = v; } ),
  1088. new ParameterDefn("ShouldSplitSimulationIslands", "Enable splitting active object scanning islands",
  1089. ConfigurationParameters.numericTrue,
  1090. (s,cf,p,v) => { s.m_params[0].shouldSplitSimulationIslands = s.NumericBool(cf.GetBoolean(p, s.BoolNumeric(v))); },
  1091. (s) => { return s.m_params[0].shouldSplitSimulationIslands; },
  1092. (s,p,l,v) => { s.m_params[0].shouldSplitSimulationIslands = v; } ),
  1093. new ParameterDefn("ShouldEnableFrictionCaching", "Enable friction computation caching",
  1094. ConfigurationParameters.numericFalse,
  1095. (s,cf,p,v) => { s.m_params[0].shouldEnableFrictionCaching = s.NumericBool(cf.GetBoolean(p, s.BoolNumeric(v))); },
  1096. (s) => { return s.m_params[0].shouldEnableFrictionCaching; },
  1097. (s,p,l,v) => { s.m_params[0].shouldEnableFrictionCaching = v; } ),
  1098. new ParameterDefn("NumberOfSolverIterations", "Number of internal iterations (0 means default)",
  1099. 0f, // zero says use Bullet default
  1100. (s,cf,p,v) => { s.m_params[0].numberOfSolverIterations = cf.GetFloat(p, v); },
  1101. (s) => { return s.m_params[0].numberOfSolverIterations; },
  1102. (s,p,l,v) => { s.m_params[0].numberOfSolverIterations = v; } ),
  1103. new ParameterDefn("LinksetImplementation", "Type of linkset implementation (0=Constraint, 1=Compound, 2=Manual)",
  1104. (float)BSLinkset.LinksetImplementation.Compound,
  1105. (s,cf,p,v) => { s.m_params[0].linksetImplementation = cf.GetFloat(p,v); },
  1106. (s) => { return s.m_params[0].linksetImplementation; },
  1107. (s,p,l,v) => { s.m_params[0].linksetImplementation = v; } ),
  1108. new ParameterDefn("LinkConstraintUseFrameOffset", "For linksets built with constraints, enable frame offsetFor linksets built with constraints, enable frame offset.",
  1109. ConfigurationParameters.numericFalse,
  1110. (s,cf,p,v) => { s.m_params[0].linkConstraintUseFrameOffset = s.NumericBool(cf.GetBoolean(p, s.BoolNumeric(v))); },
  1111. (s) => { return s.m_params[0].linkConstraintUseFrameOffset; },
  1112. (s,p,l,v) => { s.m_params[0].linkConstraintUseFrameOffset = v; } ),
  1113. new ParameterDefn("LinkConstraintEnableTransMotor", "Whether to enable translational motor on linkset constraints",
  1114. ConfigurationParameters.numericTrue,
  1115. (s,cf,p,v) => { s.m_params[0].linkConstraintEnableTransMotor = s.NumericBool(cf.GetBoolean(p, s.BoolNumeric(v))); },
  1116. (s) => { return s.m_params[0].linkConstraintEnableTransMotor; },
  1117. (s,p,l,v) => { s.m_params[0].linkConstraintEnableTransMotor = v; } ),
  1118. new ParameterDefn("LinkConstraintTransMotorMaxVel", "Maximum velocity to be applied by translational motor in linkset constraints",
  1119. 5.0f,
  1120. (s,cf,p,v) => { s.m_params[0].linkConstraintTransMotorMaxVel = cf.GetFloat(p, v); },
  1121. (s) => { return s.m_params[0].linkConstraintTransMotorMaxVel; },
  1122. (s,p,l,v) => { s.m_params[0].linkConstraintTransMotorMaxVel = v; } ),
  1123. new ParameterDefn("LinkConstraintTransMotorMaxForce", "Maximum force to be applied by translational motor in linkset constraints",
  1124. 0.1f,
  1125. (s,cf,p,v) => { s.m_params[0].linkConstraintTransMotorMaxForce = cf.GetFloat(p, v); },
  1126. (s) => { return s.m_params[0].linkConstraintTransMotorMaxForce; },
  1127. (s,p,l,v) => { s.m_params[0].linkConstraintTransMotorMaxForce = v; } ),
  1128. new ParameterDefn("LinkConstraintCFM", "Amount constraint can be violated. 0=no violation, 1=infinite. Default=0.1",
  1129. 0.1f,
  1130. (s,cf,p,v) => { s.m_params[0].linkConstraintCFM = cf.GetFloat(p, v); },
  1131. (s) => { return s.m_params[0].linkConstraintCFM; },
  1132. (s,p,l,v) => { s.m_params[0].linkConstraintCFM = v; } ),
  1133. new ParameterDefn("LinkConstraintERP", "Amount constraint is corrected each tick. 0=none, 1=all. Default = 0.2",
  1134. 0.1f,
  1135. (s,cf,p,v) => { s.m_params[0].linkConstraintERP = cf.GetFloat(p, v); },
  1136. (s) => { return s.m_params[0].linkConstraintERP; },
  1137. (s,p,l,v) => { s.m_params[0].linkConstraintERP = v; } ),
  1138. new ParameterDefn("LinkConstraintSolverIterations", "Number of solver iterations when computing constraint. (0 = Bullet default)",
  1139. 40,
  1140. (s,cf,p,v) => { s.m_params[0].linkConstraintSolverIterations = cf.GetFloat(p, v); },
  1141. (s) => { return s.m_params[0].linkConstraintSolverIterations; },
  1142. (s,p,l,v) => { s.m_params[0].linkConstraintSolverIterations = v; } ),
  1143. new ParameterDefn("LogPhysicsStatisticsFrames", "Frames between outputting detailed phys stats. (0 is off)",
  1144. 0f,
  1145. (s,cf,p,v) => { s.m_params[0].physicsLoggingFrames = cf.GetInt(p, (int)v); },
  1146. (s) => { return (float)s.m_params[0].physicsLoggingFrames; },
  1147. (s,p,l,v) => { s.m_params[0].physicsLoggingFrames = (int)v; } ),
  1148. };
  1149. // Convert a boolean to our numeric true and false values
  1150. public float NumericBool(bool b)
  1151. {
  1152. return (b ? ConfigurationParameters.numericTrue : ConfigurationParameters.numericFalse);
  1153. }
  1154. // Convert numeric true and false values to a boolean
  1155. public bool BoolNumeric(float b)
  1156. {
  1157. return (b == ConfigurationParameters.numericTrue ? true : false);
  1158. }
  1159. // Search through the parameter definitions and return the matching
  1160. // ParameterDefn structure.
  1161. // Case does not matter as names are compared after converting to lower case.
  1162. // Returns 'false' if the parameter is not found.
  1163. private bool TryGetParameter(string paramName, out ParameterDefn defn)
  1164. {
  1165. bool ret = false;
  1166. ParameterDefn foundDefn = new ParameterDefn();
  1167. string pName = paramName.ToLower();
  1168. foreach (ParameterDefn parm in ParameterDefinitions)
  1169. {
  1170. if (pName == parm.name.ToLower())
  1171. {
  1172. foundDefn = parm;
  1173. ret = true;
  1174. break;
  1175. }
  1176. }
  1177. defn = foundDefn;
  1178. return ret;
  1179. }
  1180. // Pass through the settable parameters and set the default values
  1181. private void SetParameterDefaultValues()
  1182. {
  1183. foreach (ParameterDefn parm in ParameterDefinitions)
  1184. {
  1185. parm.setter(this, parm.name, PhysParameterEntry.APPLY_TO_NONE, parm.defaultValue);
  1186. }
  1187. }
  1188. // Get user set values out of the ini file.
  1189. private void SetParameterConfigurationValues(IConfig cfg)
  1190. {
  1191. foreach (ParameterDefn parm in ParameterDefinitions)
  1192. {
  1193. parm.userParam(this, cfg, parm.name, parm.defaultValue);
  1194. }
  1195. }
  1196. private PhysParameterEntry[] SettableParameters = new PhysParameterEntry[1];
  1197. // This creates an array in the correct format for returning the list of
  1198. // parameters. This is used by the 'list' option of the 'physics' command.
  1199. private void BuildParameterTable()
  1200. {
  1201. if (SettableParameters.Length < ParameterDefinitions.Length)
  1202. {
  1203. List<PhysParameterEntry> entries = new List<PhysParameterEntry>();
  1204. for (int ii = 0; ii < ParameterDefinitions.Length; ii++)
  1205. {
  1206. ParameterDefn pd = ParameterDefinitions[ii];
  1207. entries.Add(new PhysParameterEntry(pd.name, pd.desc));
  1208. }
  1209. // make the list in alphabetical order for estetic reasons
  1210. entries.Sort(delegate(PhysParameterEntry ppe1, PhysParameterEntry ppe2)
  1211. {
  1212. return ppe1.name.CompareTo(ppe2.name);
  1213. });
  1214. SettableParameters = entries.ToArray();
  1215. }
  1216. }
  1217. #region IPhysicsParameters
  1218. // Get the list of parameters this physics engine supports
  1219. public PhysParameterEntry[] GetParameterList()
  1220. {
  1221. BuildParameterTable();
  1222. return SettableParameters;
  1223. }
  1224. // Set parameter on a specific or all instances.
  1225. // Return 'false' if not able to set the parameter.
  1226. // Setting the value in the m_params block will change the value the physics engine
  1227. // will use the next time since it's pinned and shared memory.
  1228. // Some of the values require calling into the physics engine to get the new
  1229. // value activated ('terrainFriction' for instance).
  1230. public bool SetPhysicsParameter(string parm, float val, uint localID)
  1231. {
  1232. bool ret = false;
  1233. ParameterDefn theParam;
  1234. if (TryGetParameter(parm, out theParam))
  1235. {
  1236. theParam.setter(this, parm, localID, val);
  1237. ret = true;
  1238. }
  1239. return ret;
  1240. }
  1241. // update all the localIDs specified
  1242. // If the local ID is APPLY_TO_NONE, just change the default value
  1243. // If the localID is APPLY_TO_ALL change the default value and apply the new value to all the lIDs
  1244. // If the localID is a specific object, apply the parameter change to only that object
  1245. private void UpdateParameterObject(ref float defaultLoc, string parm, uint localID, float val)
  1246. {
  1247. List<uint> objectIDs = new List<uint>();
  1248. switch (localID)
  1249. {
  1250. case PhysParameterEntry.APPLY_TO_NONE:
  1251. defaultLoc = val; // setting only the default value
  1252. // This will cause a call into the physical world if some operation is specified (SetOnObject).
  1253. objectIDs.Add(TERRAIN_ID);
  1254. TaintedUpdateParameter(parm, objectIDs, val);
  1255. break;
  1256. case PhysParameterEntry.APPLY_TO_ALL:
  1257. defaultLoc = val; // setting ALL also sets the default value
  1258. lock (PhysObjects) objectIDs = new List<uint>(PhysObjects.Keys);
  1259. TaintedUpdateParameter(parm, objectIDs, val);
  1260. break;
  1261. default:
  1262. // setting only one localID
  1263. objectIDs.Add(localID);
  1264. TaintedUpdateParameter(parm, objectIDs, val);
  1265. break;
  1266. }
  1267. }
  1268. // schedule the actual updating of the paramter to when the phys engine is not busy
  1269. private void TaintedUpdateParameter(string parm, List<uint> lIDs, float val)
  1270. {
  1271. float xval = val;
  1272. List<uint> xlIDs = lIDs;
  1273. string xparm = parm;
  1274. TaintedObject("BSScene.UpdateParameterSet", delegate() {
  1275. ParameterDefn thisParam;
  1276. if (TryGetParameter(xparm, out thisParam))
  1277. {
  1278. if (thisParam.onObject != null)
  1279. {
  1280. foreach (uint lID in xlIDs)
  1281. {
  1282. BSPhysObject theObject = null;
  1283. PhysObjects.TryGetValue(lID, out theObject);
  1284. thisParam.onObject(this, theObject, xval);
  1285. }
  1286. }
  1287. }
  1288. });
  1289. }
  1290. // Get parameter.
  1291. // Return 'false' if not able to get the parameter.
  1292. public bool GetPhysicsParameter(string parm, out float value)
  1293. {
  1294. float val = 0f;
  1295. bool ret = false;
  1296. ParameterDefn theParam;
  1297. if (TryGetParameter(parm, out theParam))
  1298. {
  1299. val = theParam.getter(this);
  1300. ret = true;
  1301. }
  1302. value = val;
  1303. return ret;
  1304. }
  1305. #endregion IPhysicsParameters
  1306. #endregion Runtime settable parameters
  1307. // Debugging routine for dumping detailed physical information for vehicle prims
  1308. private void DumpVehicles()
  1309. {
  1310. foreach (BSPrim prim in m_vehicles)
  1311. {
  1312. BulletSimAPI.DumpRigidBody2(World.ptr, prim.PhysBody.ptr);
  1313. BulletSimAPI.DumpCollisionShape2(World.ptr, prim.PhysShape.ptr);
  1314. }
  1315. }
  1316. // Invoke the detailed logger and output something if it's enabled.
  1317. public void DetailLog(string msg, params Object[] args)
  1318. {
  1319. PhysicsLogging.Write(msg, args);
  1320. // Add the Flush() if debugging crashes. Gets all the messages written out.
  1321. if (m_physicsLoggingDoFlush) PhysicsLogging.Flush();
  1322. }
  1323. // Used to fill in the LocalID when there isn't one. It's the correct number of characters.
  1324. public const string DetailLogZero = "0000000000";
  1325. }
  1326. }