clockwerk-opensim-stable – Blame information for rev 1

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