aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs
blob: c4b4332e75debcb0b5f012bad537ca52d78970ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
/*
 * Copyright (c) Contributors, http://opensimulator.org/
 * See CONTRIBUTORS.TXT for a full list of copyright holders.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyrightD
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSimulator Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework.Statistics.Logging;
using OpenSim.Region.Framework;
using OpenSim.Region.Physics.Manager;
using Nini.Config;
using log4net;
using OpenMetaverse;

// TODOs for BulletSim (for BSScene, BSPrim, BSCharacter and BulletSim)
// Debug linkset 
// Test with multiple regions in one simulator 
// Adjust character capsule size when height is adjusted (ScenePresence.SetHeight)
// Test sculpties
// Compute physics FPS reasonably
// Based on material, set density and friction
// More efficient memory usage when passing hull information from BSPrim to BulletSim
// Four states of prim: Physical, regular, phantom and selected. Are we modeling these correctly?
//     In SL one can set both physical and phantom (gravity, does not effect others, makes collisions with ground)
//     At the moment, physical and phantom causes object to drop through the terrain
// Physical phantom objects and related typing (collision options )
// Check out llVolumeDetect. Must do something for that.
// Should prim.link() and prim.delink() membership checking happen at taint time?
// Mesh sharing. Use meshHash to tell if we already have a hull of that shape and only create once
// Do attachments need to be handled separately? Need collision events. Do not collide with VolumeDetect
// Use collision masks for collision with terrain and phantom objects 
// Implement the genCollisions feature in BulletSim::SetObjectProperties (don't pass up unneeded collisions)
// Implement LockAngularMotion
// Decide if clearing forces is the right thing to do when setting position (BulletSim::SetObjectTranslation)
// Does NeedsMeshing() really need to exclude all the different shapes?
// Remove mesh and Hull stuff. Use mesh passed to bullet and use convexdecom from bullet.
// Add PID movement operations. What does ScenePresence.MoveToTarget do?
// Check terrain size. 128 or 127?
// Multiple contact points on collision?
//    See code in ode::near... calls to collision_accounting_events()
//    (This might not be a problem. ODE collects all the collisions with one object in one tick.)
// Raycast
// 
namespace OpenSim.Region.Physics.BulletSPlugin
{
public class BSScene : PhysicsScene, IPhysicsParameters
{
    private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    private static readonly string LogHeader = "[BULLETS SCENE]";

    private void DebugLog(string mm, params Object[] xx) { if (shouldDebugLog) m_log.DebugFormat(mm, xx); }

    public string BulletSimVersion = "?";

    private Dictionary<uint, BSCharacter> m_avatars = new Dictionary<uint, BSCharacter>();
    private Dictionary<uint, BSPrim> m_prims = new Dictionary<uint, BSPrim>();
    private HashSet<BSCharacter> m_avatarsWithCollisions = new HashSet<BSCharacter>();
    private HashSet<BSPrim> m_primsWithCollisions = new HashSet<BSPrim>();
    private List<BSPrim> m_vehicles = new List<BSPrim>();
    private float[] m_heightMap;
    private float m_waterLevel;
    private uint m_worldID;
    public uint WorldID { get { return m_worldID; } }

    private bool m_initialized = false;

    private int m_detailedStatsStep = 0;

    public IMesher mesher;
    private float m_meshLOD;
    public float MeshLOD
    {
        get { return m_meshLOD; }
    }
    private float m_sculptLOD;
    public float SculptLOD
    {
        get { return m_sculptLOD; }
    }

    private int m_maxSubSteps;
    private float m_fixedTimeStep;
    private long m_simulationStep = 0;
    public long SimulationStep { get { return m_simulationStep; } }

    public float LastSimulatedTimestep { get; private set; }

    // A value of the time now so all the collision and update routines do not have to get their own
    // Set to 'now' just before all the prims and actors are called for collisions and updates
    private int m_simulationNowTime;
    public int SimulationNowTime { get { return m_simulationNowTime; } }

    private int m_maxCollisionsPerFrame;
    private CollisionDesc[] m_collisionArray;
    private GCHandle m_collisionArrayPinnedHandle;

    private int m_maxUpdatesPerFrame;
    private EntityProperties[] m_updateArray;
    private GCHandle m_updateArrayPinnedHandle;

    private bool _meshSculptedPrim = true;         // cause scuplted prims to get meshed
    private bool _forceSimplePrimMeshing = false;   // if a cube or sphere, let Bullet do internal shapes

    public float PID_D { get; private set; }    // derivative
    public float PID_P { get; private set; }    // proportional

    public const uint TERRAIN_ID = 0;       // OpenSim senses terrain with a localID of zero
    public const uint GROUNDPLANE_ID = 1;

    public ConfigurationParameters Params
    {
        get { return m_params[0]; }
    }
    public Vector3 DefaultGravity
    {
        get { return new Vector3(0f, 0f, Params.gravity); }
    }

    private float m_maximumObjectMass;
    public float MaximumObjectMass
    {
        get { return m_maximumObjectMass; }
    }

    public delegate void TaintCallback();
    private List<TaintCallback> _taintedObjects;
    private Object _taintLock = new Object();

    // A pointer to an instance if this structure is passed to the C++ code
    ConfigurationParameters[] m_params;
    GCHandle m_paramsHandle;

    public bool shouldDebugLog { get; private set; }

    private BulletSimAPI.DebugLogCallback m_DebugLogCallbackHandle;

    // Sometimes you just have to log everything.
    public LogWriter PhysicsLogging;
    private bool m_physicsLoggingEnabled;
    private string m_physicsLoggingDir;
    private string m_physicsLoggingPrefix;
    private int m_physicsLoggingFileMinutes;

    public LogWriter VehicleLogging;
    private bool m_vehicleLoggingEnabled;
    private string m_vehicleLoggingDir;
    private string m_vehicleLoggingPrefix;
    private int m_vehicleLoggingFileMinutes;

    public BSScene(string identifier)
    {
        m_initialized = false;
    }

    public override void Initialise(IMesher meshmerizer, IConfigSource config)
    {
        // Allocate pinned memory to pass parameters.
        m_params = new ConfigurationParameters[1];
        m_paramsHandle = GCHandle.Alloc(m_params, GCHandleType.Pinned);

        // Set default values for physics parameters plus any overrides from the ini file
        GetInitialParameterValues(config);

        // allocate more pinned memory close to the above in an attempt to get the memory all together
        m_collisionArray = new CollisionDesc[m_maxCollisionsPerFrame];
        m_collisionArrayPinnedHandle = GCHandle.Alloc(m_collisionArray, GCHandleType.Pinned);
        m_updateArray = new EntityProperties[m_maxUpdatesPerFrame];
        m_updateArrayPinnedHandle = GCHandle.Alloc(m_updateArray, GCHandleType.Pinned);

        // Enable very detailed logging.
        // By creating an empty logger when not logging, the log message invocation code
        // can be left in and every call doesn't have to check for null.
        if (m_physicsLoggingEnabled)
        {
            PhysicsLogging = new LogWriter(m_physicsLoggingDir, m_physicsLoggingPrefix, m_physicsLoggingFileMinutes);
        }
        else
        {
            PhysicsLogging = new LogWriter();
        }
        if (m_vehicleLoggingEnabled)
        {
            VehicleLogging = new LogWriter(m_vehicleLoggingDir, m_vehicleLoggingPrefix, m_vehicleLoggingFileMinutes);
        }
        else
        {
            VehicleLogging = new LogWriter();
        }

        // Get the version of the DLL
        // TODO: this doesn't work yet. Something wrong with marshaling the returned string.
        // BulletSimVersion = BulletSimAPI.GetVersion();
        // m_log.WarnFormat("{0}: BulletSim.dll version='{1}'", LogHeader, BulletSimVersion);

        // if Debug, enable logging from the unmanaged code
        if (m_log.IsDebugEnabled)
        {
            m_log.DebugFormat("{0}: Initialize: Setting debug callback for unmanaged code", LogHeader);
            // the handle is saved to it doesn't get freed after this call
            m_DebugLogCallbackHandle = new BulletSimAPI.DebugLogCallback(BulletLogger);
            BulletSimAPI.SetDebugLogCallback(m_DebugLogCallbackHandle);
        }

        _taintedObjects = new List<TaintCallback>();

        mesher = meshmerizer;
        // The bounding box for the simulated world
        Vector3 worldExtent = new Vector3(Constants.RegionSize, Constants.RegionSize, 8192f);

        // m_log.DebugFormat("{0}: Initialize: Calling BulletSimAPI.Initialize.", LogHeader);
        m_worldID = BulletSimAPI.Initialize(worldExtent, m_paramsHandle.AddrOfPinnedObject(),
                                        m_maxCollisionsPerFrame, m_collisionArrayPinnedHandle.AddrOfPinnedObject(),
                                        m_maxUpdatesPerFrame, m_updateArrayPinnedHandle.AddrOfPinnedObject());

        m_initialized = true;
    }

    // All default parameter values are set here. There should be no values set in the
    // variable definitions.
    private void GetInitialParameterValues(IConfigSource config)
    {
        ConfigurationParameters parms = new ConfigurationParameters();

        _meshSculptedPrim = true;           // mesh sculpted prims
        _forceSimplePrimMeshing = false;    // use complex meshing if called for

        m_meshLOD = 8f;
        m_sculptLOD = 32f;

        shouldDebugLog = false;
        m_detailedStatsStep = 0;            // disabled

        m_maxSubSteps = 10;
        m_fixedTimeStep = 1f / 60f;
        m_maxCollisionsPerFrame = 2048;
        m_maxUpdatesPerFrame = 2048;
        m_maximumObjectMass = 10000.01f;

        PID_D = 2200f;
        PID_P = 900f;

        parms.defaultFriction = 0.5f;
        parms.defaultDensity = 10.000006836f; // Aluminum g/cm3
        parms.defaultRestitution = 0f;
        parms.collisionMargin = 0.0f;
        parms.gravity = -9.80665f;

        parms.linearDamping = 0.0f;
        parms.angularDamping = 0.0f;
        parms.deactivationTime = 0.2f;
        parms.linearSleepingThreshold = 0.8f;
        parms.angularSleepingThreshold = 1.0f;
        parms.ccdMotionThreshold = 0.0f;    // set to zero to disable
        parms.ccdSweptSphereRadius = 0.0f;
        parms.contactProcessingThreshold = 0.1f;

        parms.terrainFriction = 0.5f;
        parms.terrainHitFraction = 0.8f;
        parms.terrainRestitution = 0f;
        parms.avatarFriction = 0.5f;
        parms.avatarRestitution = 0.0f;
        parms.avatarDensity = 60f;
        parms.avatarCapsuleRadius = 0.37f;
        parms.avatarCapsuleHeight = 1.5f; // 2.140599f
    	parms.avatarContactProcessingThreshold = 0.1f;

    	parms.maxPersistantManifoldPoolSize = 0f;
    	parms.shouldDisableContactPoolDynamicAllocation = ConfigurationParameters.numericTrue;
    	parms.shouldForceUpdateAllAabbs = ConfigurationParameters.numericFalse;
    	parms.shouldRandomizeSolverOrder = ConfigurationParameters.numericFalse;
    	parms.shouldSplitSimulationIslands = ConfigurationParameters.numericFalse;
    	parms.shouldEnableFrictionCaching = ConfigurationParameters.numericFalse;
    	parms.numberOfSolverIterations = 0f;    // means use default

        if (config != null)
        {
            // If there are specifications in the ini file, use those values
            // WHEN ADDING OR UPDATING THIS SECTION, BE SURE TO UPDATE OpenSimDefaults.ini
            // ALSO REMEMBER TO UPDATE THE RUNTIME SETTING OF THE PARAMETERS.
            IConfig pConfig = config.Configs["BulletSim"];
            if (pConfig != null)
            {
                _meshSculptedPrim = pConfig.GetBoolean("MeshSculptedPrim", _meshSculptedPrim);
                _forceSimplePrimMeshing = pConfig.GetBoolean("ForceSimplePrimMeshing", _forceSimplePrimMeshing);

                shouldDebugLog = pConfig.GetBoolean("ShouldDebugLog", shouldDebugLog);
                m_detailedStatsStep = pConfig.GetInt("DetailedStatsStep", m_detailedStatsStep);

                m_meshLOD = pConfig.GetFloat("MeshLevelOfDetail", m_meshLOD);
                m_sculptLOD = pConfig.GetFloat("SculptLevelOfDetail", m_sculptLOD);

                m_maxSubSteps = pConfig.GetInt("MaxSubSteps", m_maxSubSteps);
                m_fixedTimeStep = pConfig.GetFloat("FixedTimeStep", m_fixedTimeStep);
                m_maxCollisionsPerFrame = pConfig.GetInt("MaxCollisionsPerFrame", m_maxCollisionsPerFrame);
                m_maxUpdatesPerFrame = pConfig.GetInt("MaxUpdatesPerFrame", m_maxUpdatesPerFrame);
                m_maximumObjectMass = pConfig.GetFloat("MaxObjectMass", m_maximumObjectMass);

                PID_D = pConfig.GetFloat("PIDDerivative", PID_D);
                PID_P = pConfig.GetFloat("PIDProportional", PID_P);

                parms.defaultFriction = pConfig.GetFloat("DefaultFriction", parms.defaultFriction);
                parms.defaultDensity = pConfig.GetFloat("DefaultDensity", parms.defaultDensity);
                parms.defaultRestitution = pConfig.GetFloat("DefaultRestitution", parms.defaultRestitution);
                parms.collisionMargin = pConfig.GetFloat("CollisionMargin", parms.collisionMargin);
                parms.gravity = pConfig.GetFloat("Gravity", parms.gravity);

                parms.linearDamping = pConfig.GetFloat("LinearDamping", parms.linearDamping);
                parms.angularDamping = pConfig.GetFloat("AngularDamping", parms.angularDamping);
                parms.deactivationTime = pConfig.GetFloat("DeactivationTime", parms.deactivationTime);
                parms.linearSleepingThreshold = pConfig.GetFloat("LinearSleepingThreshold", parms.linearSleepingThreshold);
                parms.angularSleepingThreshold = pConfig.GetFloat("AngularSleepingThreshold", parms.angularSleepingThreshold);
                parms.ccdMotionThreshold = pConfig.GetFloat("CcdMotionThreshold", parms.ccdMotionThreshold);
                parms.ccdSweptSphereRadius = pConfig.GetFloat("CcdSweptSphereRadius", parms.ccdSweptSphereRadius);
                parms.contactProcessingThreshold = pConfig.GetFloat("ContactProcessingThreshold", parms.contactProcessingThreshold);

                parms.terrainFriction = pConfig.GetFloat("TerrainFriction", parms.terrainFriction);
                parms.terrainHitFraction = pConfig.GetFloat("TerrainHitFraction", parms.terrainHitFraction);
                parms.terrainRestitution = pConfig.GetFloat("TerrainRestitution", parms.terrainRestitution);
                parms.avatarFriction = pConfig.GetFloat("AvatarFriction", parms.avatarFriction);
                parms.avatarRestitution = pConfig.GetFloat("AvatarRestitution", parms.avatarRestitution);
                parms.avatarDensity = pConfig.GetFloat("AvatarDensity", parms.avatarDensity);
                parms.avatarCapsuleRadius = pConfig.GetFloat("AvatarCapsuleRadius", parms.avatarCapsuleRadius);
                parms.avatarCapsuleHeight = pConfig.GetFloat("AvatarCapsuleHeight", parms.avatarCapsuleHeight);
                parms.avatarContactProcessingThreshold = pConfig.GetFloat("AvatarContactProcessingThreshold", parms.avatarContactProcessingThreshold);

                parms.maxPersistantManifoldPoolSize = pConfig.GetFloat("MaxPersistantManifoldPoolSize", parms.maxPersistantManifoldPoolSize);
                parms.shouldDisableContactPoolDynamicAllocation = ParamBoolean(pConfig, "ShouldDisableContactPoolDynamicAllocation", parms.shouldDisableContactPoolDynamicAllocation);
	            parms.shouldForceUpdateAllAabbs = ParamBoolean(pConfig, "ShouldForceUpdateAllAabbs", parms.shouldForceUpdateAllAabbs);
	            parms.shouldRandomizeSolverOrder = ParamBoolean(pConfig, "ShouldRandomizeSolverOrder", parms.shouldRandomizeSolverOrder);
	            parms.shouldSplitSimulationIslands = ParamBoolean(pConfig, "ShouldSplitSimulationIslands", parms.shouldSplitSimulationIslands);
	            parms.shouldEnableFrictionCaching = ParamBoolean(pConfig, "ShouldEnableFrictionCaching", parms.shouldEnableFrictionCaching);
	            parms.numberOfSolverIterations = pConfig.GetFloat("NumberOfSolverIterations", parms.numberOfSolverIterations);

                // Very detailed logging for physics debugging
                m_physicsLoggingEnabled = pConfig.GetBoolean("PhysicsLoggingEnabled", false);
                m_physicsLoggingDir = pConfig.GetString("PhysicsLoggingDir", ".");
                m_physicsLoggingPrefix = pConfig.GetString("PhysicsLoggingPrefix", "physics-");
                m_physicsLoggingFileMinutes = pConfig.GetInt("PhysicsLoggingFileMinutes", 5);
                // Very detailed logging for vehicle debugging
                m_vehicleLoggingEnabled = pConfig.GetBoolean("VehicleLoggingEnabled", false);
                m_vehicleLoggingDir = pConfig.GetString("VehicleLoggingDir", ".");
                m_vehicleLoggingPrefix = pConfig.GetString("VehicleLoggingPrefix", "vehicle-");
                m_vehicleLoggingFileMinutes = pConfig.GetInt("VehicleLoggingFileMinutes", 5);
            }
        }
        m_params[0] = parms;
    }

    // A helper function that handles a true/false parameter and returns the proper float number encoding
    float ParamBoolean(IConfig config, string parmName, float deflt)
    {
        float ret = deflt;
        if (config.Contains(parmName))
        {
            ret = ConfigurationParameters.numericFalse;
            if (config.GetBoolean(parmName, false))
            {
                ret = ConfigurationParameters.numericTrue;
            }
        }
        return ret;
    }


    // Called directly from unmanaged code so don't do much
    private void BulletLogger(string msg)
    {
        m_log.Debug("[BULLETS UNMANAGED]:" + msg);
    }

    public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 size, bool isFlying)
    {
        m_log.ErrorFormat("{0}: CALL TO AddAvatar in BSScene. NOT IMPLEMENTED", LogHeader);
        return null;
    }

    public override PhysicsActor AddAvatar(uint localID, string avName, Vector3 position, Vector3 size, bool isFlying)
    {
        // m_log.DebugFormat("{0}: AddAvatar: {1}", LogHeader, avName);
        BSCharacter actor = new BSCharacter(localID, avName, this, position, size, isFlying);
        lock (m_avatars) m_avatars.Add(localID, actor);
        return actor;
    }

    public override void RemoveAvatar(PhysicsActor actor)
    {
        // m_log.DebugFormat("{0}: RemoveAvatar", LogHeader);
        BSCharacter bsactor = actor as BSCharacter;
        if (bsactor != null)
        {
            try
            {
                lock (m_avatars) m_avatars.Remove(actor.LocalID);
            }
            catch (Exception e)
            {
                m_log.WarnFormat("{0}: Attempt to remove avatar that is not in physics scene: {1}", LogHeader, e);
            }
            bsactor.Destroy();
            // bsactor.dispose();
        }
    }

    public override void RemovePrim(PhysicsActor prim)
    {
        BSPrim bsprim = prim as BSPrim;
        if (bsprim != null)
        {
            m_log.DebugFormat("{0}: RemovePrim. id={1}/{2}", LogHeader, bsprim.Name, bsprim.LocalID);
            try
            {
                lock (m_prims) m_prims.Remove(bsprim.LocalID);
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("{0}: Attempt to remove prim that is not in physics scene: {1}", LogHeader, e);
            }
            bsprim.Destroy();
            // bsprim.dispose();
        }
        else
        {
            m_log.ErrorFormat("{0}: Attempt to remove prim that is not a BSPrim type.", LogHeader);
        }
    }

    public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
                                              Vector3 size, Quaternion rotation, bool isPhysical, uint localID)
    {
        // m_log.DebugFormat("{0}: AddPrimShape2: {1}", LogHeader, primName);
        BSPrim prim = new BSPrim(localID, primName, this, position, size, rotation, pbs, isPhysical);
        lock (m_prims) m_prims.Add(localID, prim);
        return prim;
    }

    // This is a call from the simulator saying that some physical property has been updated.
    // The BulletSim driver senses the changing of relevant properties so this taint 
    // information call is not needed.
    public override void AddPhysicsActorTaint(PhysicsActor prim) { }

    // Simulate one timestep
    public override float Simulate(float timeStep)
    {
        int updatedEntityCount;
        IntPtr updatedEntitiesPtr;
        int collidersCount;
        IntPtr collidersPtr;

        LastSimulatedTimestep = timeStep;

        // prevent simulation until we've been initialized
        if (!m_initialized) return 10.0f;

        long simulateStartTime = Util.EnvironmentTickCount();

        // update the prim states while we know the physics engine is not busy
        ProcessTaints();

        // Some of the prims operate with special vehicle properties
        ProcessVehicles(timeStep);
        ProcessTaints();    // the vehicles might have added taints

        // step the physical world one interval
        m_simulationStep++;
        int numSubSteps = BulletSimAPI.PhysicsStep(m_worldID, timeStep, m_maxSubSteps, m_fixedTimeStep, 
                    out updatedEntityCount, out updatedEntitiesPtr, out collidersCount, out collidersPtr);

        // Don't have to use the pointers passed back since we know it is the same pinned memory we passed in

        // Get a value for 'now' so all the collision and update routines don't have to get their own
        m_simulationNowTime = Util.EnvironmentTickCount();

        // If there were collisions, process them by sending the event to the prim.
        // Collisions must be processed before updates.
        if (collidersCount > 0)
        {
            for (int ii = 0; ii < collidersCount; ii++)
            {
                uint cA = m_collisionArray[ii].aID;
                uint cB = m_collisionArray[ii].bID;
                Vector3 point = m_collisionArray[ii].point;
                Vector3 normal = m_collisionArray[ii].normal;
                SendCollision(cA, cB, point, normal, 0.01f);
                SendCollision(cB, cA, point, -normal, 0.01f);
            }
        }

        // The above SendCollision's batch up the collisions on the objects.
        //      Now push the collisions into the simulator.
        foreach (BSPrim bsp in m_primsWithCollisions)
            bsp.SendCollisions();
        m_primsWithCollisions.Clear();

        // This is a kludge to get avatar movement updated. 
        //   Don't send collisions only if there were collisions -- send everytime.
        //   ODE sends collisions even if there are none and this is used to update
        //   avatar animations and stuff.
        // foreach (BSCharacter bsc in m_avatarsWithCollisions)
        //     bsc.SendCollisions();
        foreach (KeyValuePair<uint, BSCharacter> kvp in m_avatars)
            kvp.Value.SendCollisions();
        m_avatarsWithCollisions.Clear();

        // If any of the objects had updated properties, tell the object it has been changed by the physics engine
        if (updatedEntityCount > 0)
        {
            for (int ii = 0; ii < updatedEntityCount; ii++)
            {
                EntityProperties entprop = m_updateArray[ii];
                // m_log.DebugFormat("{0}: entprop[{1}]: id={2}, pos={3}", LogHeader, ii, entprop.ID, entprop.Position);
                BSPrim prim;
                if (m_prims.TryGetValue(entprop.ID, out prim))
                {
                    prim.UpdateProperties(entprop);
                    continue;
                }
                BSCharacter actor;
                if (m_avatars.TryGetValue(entprop.ID, out actor))
                {
                    actor.UpdateProperties(entprop);
                    continue;
                }
            }
        }

        // If enabled, call into the physics engine to dump statistics
        if (m_detailedStatsStep > 0)
        {
            if ((m_simulationStep % m_detailedStatsStep) == 0)
            {
                BulletSimAPI.DumpBulletStatistics();
            }
        }

        // this is a waste since the outside routine also calcuates the physics simulation
        //   period. TODO: There should be a way of computing physics frames from simulator computation.
        // long simulateTotalTime = Util.EnvironmentTickCountSubtract(simulateStartTime);
        // return (timeStep * (float)simulateTotalTime);

        // TODO: FIX THIS: fps calculation wrong. This calculation always returns about 1 in normal operation.
        return timeStep / (numSubSteps * m_fixedTimeStep) * 1000f;
    }

    // Something has collided
    private void SendCollision(uint localID, uint collidingWith, Vector3 collidePoint, Vector3 collideNormal, float penitration)
    {
        if (localID == TERRAIN_ID || localID == GROUNDPLANE_ID)
        {
            return;         // don't send collisions to the terrain
        }

        ActorTypes type = ActorTypes.Prim;
        if (collidingWith == TERRAIN_ID || collidingWith == GROUNDPLANE_ID)
            type = ActorTypes.Ground;
        else if (m_avatars.ContainsKey(collidingWith))
            type = ActorTypes.Agent;

        BSPrim prim;
        if (m_prims.TryGetValue(localID, out prim)) {
            prim.Collide(collidingWith, type, collidePoint, collideNormal, penitration);
            m_primsWithCollisions.Add(prim);
            return;
        }
        BSCharacter actor;
        if (m_avatars.TryGetValue(localID, out actor)) {
            actor.Collide(collidingWith, type, collidePoint, collideNormal, penitration);
            m_avatarsWithCollisions.Add(actor);
            return;
        }
        return;
    }

    public override void GetResults() { }

    public override void SetTerrain(float[] heightMap) {
        m_heightMap = heightMap;
        this.TaintedObject(delegate()
        {
            BulletSimAPI.SetHeightmap(m_worldID, m_heightMap);
        });
    }

    // Someday we will have complex terrain with caves and tunnels
    // For the moment, it's flat and convex
    public float GetTerrainHeightAtXYZ(Vector3 loc)
    {
        return GetTerrainHeightAtXY(loc.X, loc.Y);
    }

    public float GetTerrainHeightAtXY(float tX, float tY)
    {
        if (tX < 0 || tX >= Constants.RegionSize || tY < 0 || tY >= Constants.RegionSize)
            return 30;
        return m_heightMap[((int)tX) * Constants.RegionSize + ((int)tY)];
    }

    public override void SetWaterLevel(float baseheight) 
    {
        m_waterLevel = baseheight;
        // TODO: pass to physics engine so things will float?
    }
    public float GetWaterLevel()
    {
        return m_waterLevel;
    }

    public override void DeleteTerrain() 
    {
        // m_log.DebugFormat("{0}: DeleteTerrain()", LogHeader);
    }

    public override void Dispose()
    {
        // m_log.DebugFormat("{0}: Dispose()", LogHeader);
    }

    public override Dictionary<uint, float> GetTopColliders()
    {
        return new Dictionary<uint, float>();
    }

    public override bool IsThreaded { get { return false;  } }

    /// <summary>
    /// Routine to figure out if we need to mesh this prim with our mesher
    /// </summary>
    /// <param name="pbs"></param>
    /// <returns>true if the prim needs meshing</returns>
    public bool NeedsMeshing(PrimitiveBaseShape pbs)
    {
        // most of this is redundant now as the mesher will return null if it cant mesh a prim
        // but we still need to check for sculptie meshing being enabled so this is the most
        // convenient place to do it for now...

        // int iPropertiesNotSupportedDefault = 0;

        if (pbs.SculptEntry && !_meshSculptedPrim)
        {
            // Render sculpties as boxes
            return false;
        }

        // if it's a standard box or sphere with no cuts, hollows, twist or top shear, return false since Bullet 
        // can use an internal representation for the prim
        if (!_forceSimplePrimMeshing)
        {
            if ((pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight)
                || (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1
                        && pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z))
            {

                if (pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0
                    && pbs.ProfileHollow == 0
                    && pbs.PathTwist == 0 && pbs.PathTwistBegin == 0
                    && pbs.PathBegin == 0 && pbs.PathEnd == 0
                    && pbs.PathTaperX == 0 && pbs.PathTaperY == 0
                    && pbs.PathScaleX == 100 && pbs.PathScaleY == 100
                    && pbs.PathShearX == 0 && pbs.PathShearY == 0)
                {
                    return false;
                }
            }
        }

        /*  TODO: verify that the mesher will now do all these shapes
        if (pbs.ProfileHollow != 0)
            iPropertiesNotSupportedDefault++;

        if ((pbs.PathBegin != 0) || pbs.PathEnd != 0)
            iPropertiesNotSupportedDefault++;

        if ((pbs.PathTwistBegin != 0) || (pbs.PathTwist != 0))
            iPropertiesNotSupportedDefault++; 

        if ((pbs.ProfileBegin != 0) || pbs.ProfileEnd != 0)
            iPropertiesNotSupportedDefault++;

        if ((pbs.PathScaleX != 100) || (pbs.PathScaleY != 100))
            iPropertiesNotSupportedDefault++;

        if ((pbs.PathShearX != 0) || (pbs.PathShearY != 0))
            iPropertiesNotSupportedDefault++;

        if (pbs.ProfileShape == ProfileShape.Circle && pbs.PathCurve == (byte)Extrusion.Straight)
            iPropertiesNotSupportedDefault++;

        if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1 && (pbs.Scale.X != pbs.Scale.Y || pbs.Scale.Y != pbs.Scale.Z || pbs.Scale.Z != pbs.Scale.X))
            iPropertiesNotSupportedDefault++;

        if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte) Extrusion.Curve1)
            iPropertiesNotSupportedDefault++;

        // test for torus
        if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Square)
        {
            if (pbs.PathCurve == (byte)Extrusion.Curve1)
            {
                iPropertiesNotSupportedDefault++;
            }
        }
        else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
        {
            if (pbs.PathCurve == (byte)Extrusion.Straight)
            {
                iPropertiesNotSupportedDefault++;
            }
            // ProfileCurve seems to combine hole shape and profile curve so we need to only compare against the lower 3 bits
            else if (pbs.PathCurve == (byte)Extrusion.Curve1)
            {
                iPropertiesNotSupportedDefault++;
            }
        }
        else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
        {
            if (pbs.PathCurve == (byte)Extrusion.Curve1 || pbs.PathCurve == (byte)Extrusion.Curve2)
            {
                iPropertiesNotSupportedDefault++;
            }
        }
        else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
        {
            if (pbs.PathCurve == (byte)Extrusion.Straight)
            {
                iPropertiesNotSupportedDefault++;
            }
            else if (pbs.PathCurve == (byte)Extrusion.Curve1)
            {
                iPropertiesNotSupportedDefault++;
            }
        }
        if (iPropertiesNotSupportedDefault == 0)
        {
            return false;
        }
         */
        return true; 
    }

    // The calls to the PhysicsActors can't directly call into the physics engine
    // because it might be busy. We we delay changes to a known time.
    // We rely on C#'s closure to save and restore the context for the delegate.
    public void TaintedObject(TaintCallback callback)
    {
        lock (_taintLock)
            _taintedObjects.Add(callback);
        return;
    }

    // When someone tries to change a property on a BSPrim or BSCharacter, the object queues
    // a callback into itself to do the actual property change. That callback is called
    // here just before the physics engine is called to step the simulation.
    public void ProcessTaints()
    {
        if (_taintedObjects.Count > 0)  // save allocating new list if there is nothing to process
        {
            // swizzle a new list into the list location so we can process what's there
            List<TaintCallback> oldList;
            lock (_taintLock)
            {
                oldList = _taintedObjects;
                _taintedObjects = new List<TaintCallback>();
            }

            foreach (TaintCallback callback in oldList)
            {
                try
                {
                    callback();
                }
                catch (Exception e)
                {
                    m_log.ErrorFormat("{0}: ProcessTaints: Exception: {1}", LogHeader, e);
                }
            }
            oldList.Clear();
        }
    }

    #region Vehicles
    // Make so the scene will call this prim for vehicle actions each tick.
    // Safe to call if prim is already in the vehicle list.
    public void AddVehiclePrim(BSPrim vehicle)
    {
        lock (m_vehicles)
        {
            if (!m_vehicles.Contains(vehicle))
            {
                m_vehicles.Add(vehicle);
            }
        }
    }

    // Remove a prim from our list of vehicles.
    // Safe to call if the prim is not in the vehicle list.
    public void RemoveVehiclePrim(BSPrim vehicle)
    {
        lock (m_vehicles)
        {
            if (m_vehicles.Contains(vehicle))
            {
                m_vehicles.Remove(vehicle);
            }
        }
    }

    // Some prims have extra vehicle actions
    // no locking because only called when physics engine is not busy
    private void ProcessVehicles(float timeStep)
    {
        foreach (BSPrim prim in m_vehicles)
        {
            prim.StepVehicle(timeStep);
        }
    }
    #endregion Vehicles

    #region Runtime settable parameters
    public static PhysParameterEntry[] SettableParameters = new PhysParameterEntry[]
    {
        new PhysParameterEntry("MeshLOD", "Level of detail to render meshes (32, 16, 8 or 4. 32=most detailed)"),
        new PhysParameterEntry("SculptLOD", "Level of detail to render sculpties (32, 16, 8 or 4. 32=most detailed)"),
        new PhysParameterEntry("MaxSubStep", "In simulation step, maximum number of substeps"),
        new PhysParameterEntry("FixedTimeStep", "In simulation step, seconds of one substep (1/60)"),
        new PhysParameterEntry("MaxObjectMass", "Maximum object mass (10000.01)"),
        new PhysParameterEntry("DetailedStats", "Frames between outputting detailed phys stats. Zero is off"),

        new PhysParameterEntry("DefaultFriction", "Friction factor used on new objects"),
        new PhysParameterEntry("DefaultDensity", "Density for new objects" ),
        new PhysParameterEntry("DefaultRestitution", "Bouncyness of an object" ),
        // new PhysParameterEntry("CollisionMargin", "Margin around objects before collisions are calculated (must be zero!!)" ),
        new PhysParameterEntry("Gravity", "Vertical force of gravity (negative means down)" ),

        new PhysParameterEntry("LinearDamping", "Factor to damp linear movement per second (0.0 - 1.0)" ),
        new PhysParameterEntry("AngularDamping", "Factor to damp angular movement per second (0.0 - 1.0)" ),
        new PhysParameterEntry("DeactivationTime", "Seconds before considering an object potentially static" ),
        new PhysParameterEntry("LinearSleepingThreshold", "Seconds to measure linear movement before considering static" ),
        new PhysParameterEntry("AngularSleepingThreshold", "Seconds to measure angular movement before considering static" ),
        new PhysParameterEntry("CcdMotionThreshold", "Continuious collision detection threshold (0 means no CCD)" ),
        new PhysParameterEntry("CcdSweptSphereRadius", "Continuious collision detection test radius" ),
        new PhysParameterEntry("ContactProcessingThreshold", "Distance between contacts before doing collision check" ),
        // Can only change the following at initialization time. Change the INI file and reboot.
	    new PhysParameterEntry("MaxPersistantManifoldPoolSize", "Number of manifolds pooled (0 means default)"),
	    new PhysParameterEntry("ShouldDisableContactPoolDynamicAllocation", "Enable to allow large changes in object count"),
	    new PhysParameterEntry("ShouldForceUpdateAllAabbs", "Enable to recomputer AABBs every simulator step"),
	    new PhysParameterEntry("ShouldRandomizeSolverOrder", "Enable for slightly better stacking interaction"),
	    new PhysParameterEntry("ShouldSplitSimulationIslands", "Enable splitting active object scanning islands"),
	    new PhysParameterEntry("ShouldEnableFrictionCaching", "Enable friction computation caching"),
	    new PhysParameterEntry("NumberOfSolverIterations", "Number of internal iterations (0 means default)"),

        new PhysParameterEntry("Friction", "Set friction parameter for a specific object" ),
        new PhysParameterEntry("Restitution", "Set restitution parameter for a specific object" ),

        new PhysParameterEntry("Friction", "Set friction parameter for a specific object" ),
        new PhysParameterEntry("Restitution", "Set restitution parameter for a specific object" ),

        new PhysParameterEntry("TerrainFriction", "Factor to reduce movement against terrain surface" ),
        new PhysParameterEntry("TerrainHitFraction", "Distance to measure hit collisions" ),
        new PhysParameterEntry("TerrainRestitution", "Bouncyness" ),
        new PhysParameterEntry("AvatarFriction", "Factor to reduce movement against an avatar. Changed on avatar recreation." ),
        new PhysParameterEntry("AvatarDensity", "Density of an avatar. Changed on avatar recreation." ),
        new PhysParameterEntry("AvatarRestitution", "Bouncyness. Changed on avatar recreation." ),
        new PhysParameterEntry("AvatarCapsuleRadius", "Radius of space around an avatar" ),
        new PhysParameterEntry("AvatarCapsuleHeight", "Default height of space around avatar" ),
	    new PhysParameterEntry("AvatarContactProcessingThreshold", "Distance from capsule to check for collisions")

    };

    #region IPhysicsParameters
    // Get the list of parameters this physics engine supports
    public PhysParameterEntry[] GetParameterList()
    {
        return SettableParameters;
    }

    // Set parameter on a specific or all instances.
    // Return 'false' if not able to set the parameter.
    // Setting the value in the m_params block will change the value the physics engine
    //   will use the next time since it's pinned and shared memory.
    // Some of the values require calling into the physics engine to get the new
    //   value activated ('terrainFriction' for instance).
    public bool SetPhysicsParameter(string parm, float val, uint localID)
    {
        bool ret = true;
        string lparm = parm.ToLower();
        switch (lparm)
        {
            case "detailedstats": m_detailedStatsStep = (int)val; break;

            case "meshlod": m_meshLOD = (int)val; break;
            case "sculptlod": m_sculptLOD = (int)val; break;
            case "maxsubstep": m_maxSubSteps = (int)val; break;
            case "fixedtimestep": m_fixedTimeStep = val; break;
            case "maxobjectmass": m_maximumObjectMass = val; break;

            case "defaultfriction": m_params[0].defaultFriction = val; break;
            case "defaultdensity": m_params[0].defaultDensity = val; break;
            case "defaultrestitution": m_params[0].defaultRestitution = val; break;
            case "collisionmargin": m_params[0].collisionMargin = val; break;
            case "gravity": m_params[0].gravity = val; TaintedUpdateParameter(lparm, localID, val); break;

            case "lineardamping": UpdateParameterPrims(ref m_params[0].linearDamping, lparm, localID, val); break;
            case "angulardamping": UpdateParameterPrims(ref m_params[0].angularDamping, lparm, localID, val); break;
            case "deactivationtime": UpdateParameterPrims(ref m_params[0].deactivationTime, lparm, localID, val); break;
            case "linearsleepingthreshold": UpdateParameterPrims(ref m_params[0].linearSleepingThreshold, lparm, localID, val); break;
            case "angularsleepingthreshold": UpdateParameterPrims(ref m_params[0].angularDamping, lparm, localID, val); break;
            case "ccdmotionthreshold": UpdateParameterPrims(ref m_params[0].ccdMotionThreshold, lparm, localID, val); break;
            case "ccdsweptsphereradius": UpdateParameterPrims(ref m_params[0].ccdSweptSphereRadius, lparm, localID, val); break;
            case "contactprocessingthreshold": UpdateParameterPrims(ref m_params[0].contactProcessingThreshold, lparm, localID, val); break;
            // the following are used only at initialization time so setting them makes no sense
	        // case "maxPersistantmanifoldpoolSize": m_params[0].maxPersistantManifoldPoolSize = val; break;
	        // case "shoulddisablecontactpooldynamicallocation": m_params[0].shouldDisableContactPoolDynamicAllocation = val; break;
	        // case "shouldforceupdateallaabbs": m_params[0].shouldForceUpdateAllAabbs = val; break;
	        // case "shouldrandomizesolverorder": m_params[0].shouldRandomizeSolverOrder = val; break;
	        // case "shouldsplitsimulationislands": m_params[0].shouldSplitSimulationIslands = val; break;
	        // case "shouldenablefrictioncaching": m_params[0].shouldEnableFrictionCaching = val; break;
	        // case "numberofsolveriterations": m_params[0].numberOfSolverIterations = val; break;

            case "friction": TaintedUpdateParameter(lparm, localID, val); break;
            case "restitution": TaintedUpdateParameter(lparm, localID, val); break;

            // set a terrain physical feature and cause terrain to be recalculated
            case "terrainfriction": m_params[0].terrainFriction = val; TaintedUpdateParameter("terrain", 0, val); break;
            case "terrainhitfraction": m_params[0].terrainHitFraction = val; TaintedUpdateParameter("terrain", 0, val); break;
            case "terrainrestitution": m_params[0].terrainRestitution = val; TaintedUpdateParameter("terrain", 0, val); break;
            // set an avatar physical feature and cause avatar(s) to be recalculated
            case "avatarfriction": UpdateParameterAvatars(ref m_params[0].avatarFriction, "avatar", localID, val); break;
            case "avatardensity": UpdateParameterAvatars(ref m_params[0].avatarDensity, "avatar", localID, val); break;
            case "avatarrestitution": UpdateParameterAvatars(ref m_params[0].avatarRestitution, "avatar", localID, val); break;
            case "avatarcapsuleradius": UpdateParameterAvatars(ref m_params[0].avatarCapsuleRadius, "avatar", localID, val); break;
            case "avatarcapsuleheight": UpdateParameterAvatars(ref m_params[0].avatarCapsuleHeight, "avatar", localID, val); break;
            case "avatarcontactprocessingthreshold": UpdateParameterAvatars(ref m_params[0].avatarContactProcessingThreshold, "avatar", localID, val); break;

            default: ret = false; break;
        }
        return ret;
    }

    // check to see if we are updating a parameter for a particular or all of the prims
    private void UpdateParameterPrims(ref float loc, string parm, uint localID, float val)
    {
        List<uint> operateOn;
        lock (m_prims) operateOn = new List<uint>(m_prims.Keys);
        UpdateParameterSet(operateOn, ref loc, parm, localID, val);
    }

    // check to see if we are updating a parameter for a particular or all of the avatars
    private void UpdateParameterAvatars(ref float loc, string parm, uint localID, float val)
    {
        List<uint> operateOn;
        lock (m_avatars) operateOn = new List<uint>(m_avatars.Keys);
        UpdateParameterSet(operateOn, ref loc, parm, localID, val);
    }

    // update all the localIDs specified
    // If the local ID is APPLY_TO_NONE, just change the default value
    // If the localID is APPLY_TO_ALL change the default value and apply the new value to all the lIDs
    // If the localID is a specific object, apply the parameter change to only that object
    private void UpdateParameterSet(List<uint> lIDs, ref float defaultLoc, string parm, uint localID, float val)
    {
        switch (localID)
        {
            case PhysParameterEntry.APPLY_TO_NONE:
                defaultLoc = val;   // setting only the default value
                break;
            case PhysParameterEntry.APPLY_TO_ALL:
                defaultLoc = val;  // setting ALL also sets the default value
                List<uint> objectIDs = lIDs;
                string xparm = parm.ToLower();
                float xval = val;
                TaintedObject(delegate() {
                    foreach (uint lID in objectIDs)
                    {
                        BulletSimAPI.UpdateParameter(m_worldID, lID, xparm, xval);
                    }
                });
                break;
            default: 
                // setting only one localID
                TaintedUpdateParameter(parm, localID, val);
                break;
        }
    }

    // schedule the actual updating of the paramter to when the phys engine is not busy
    private void TaintedUpdateParameter(string parm, uint localID, float val)
    {
        uint xlocalID = localID;
        string xparm = parm.ToLower();
        float xval = val;
        TaintedObject(delegate() {
            BulletSimAPI.UpdateParameter(m_worldID, xlocalID, xparm, xval);
        });
    }

    // Get parameter.
    // Return 'false' if not able to get the parameter.
    public bool GetPhysicsParameter(string parm, out float value)
    {
        float val = 0f;
        bool ret = true;
        switch (parm.ToLower())
        {
            case "detailedstats": val = (int)m_detailedStatsStep; break;
            case "meshlod": val = (float)m_meshLOD; break;
            case "sculptlod": val = (float)m_sculptLOD; break;
            case "maxsubstep": val = (float)m_maxSubSteps; break;
            case "fixedtimestep": val = m_fixedTimeStep; break;
            case "maxobjectmass": val = m_maximumObjectMass; break;

            case "defaultfriction": val = m_params[0].defaultFriction; break;
            case "defaultdensity": val = m_params[0].defaultDensity; break;
            case "defaultrestitution": val = m_params[0].defaultRestitution; break;
            case "collisionmargin": val = m_params[0].collisionMargin; break;
            case "gravity": val = m_params[0].gravity; break;

            case "lineardamping": val = m_params[0].linearDamping; break;
            case "angulardamping": val = m_params[0].angularDamping; break;
            case "deactivationtime": val = m_params[0].deactivationTime; break;
            case "linearsleepingthreshold": val = m_params[0].linearSleepingThreshold; break;
            case "angularsleepingthreshold": val = m_params[0].angularDamping; break;
            case "ccdmotionthreshold": val = m_params[0].ccdMotionThreshold; break;
            case "ccdsweptsphereradius": val = m_params[0].ccdSweptSphereRadius; break;
            case "contactprocessingthreshold": val = m_params[0].contactProcessingThreshold; break;
	        case "maxPersistantmanifoldpoolSize": val = m_params[0].maxPersistantManifoldPoolSize; break;
	        case "shoulddisablecontactpooldynamicallocation": val = m_params[0].shouldDisableContactPoolDynamicAllocation; break;
	        case "shouldforceupdateallaabbs": val = m_params[0].shouldForceUpdateAllAabbs; break;
	        case "shouldrandomizesolverorder": val = m_params[0].shouldRandomizeSolverOrder; break;
	        case "shouldsplitsimulationislands": val = m_params[0].shouldSplitSimulationIslands; break;
	        case "shouldenablefrictioncaching": val = m_params[0].shouldEnableFrictionCaching; break;
	        case "numberofsolveriterations": val = m_params[0].numberOfSolverIterations; break;

            case "terrainfriction": val = m_params[0].terrainFriction; break;
            case "terrainhitfraction": val = m_params[0].terrainHitFraction; break;
            case "terrainrestitution": val = m_params[0].terrainRestitution; break;

            case "avatarfriction": val = m_params[0].avatarFriction; break;
            case "avatardensity": val = m_params[0].avatarDensity; break;
            case "avatarrestitution": val = m_params[0].avatarRestitution; break;
            case "avatarcapsuleradius": val = m_params[0].avatarCapsuleRadius; break;
            case "avatarcapsuleheight": val = m_params[0].avatarCapsuleHeight; break;
            case "avatarcontactprocessingthreshold": val = m_params[0].avatarContactProcessingThreshold; break;
            default: ret = false; break;

        }
        value = val;
        return ret;
    }

    #endregion IPhysicsParameters

    #endregion Runtime settable parameters

}
}