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