aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/Physics/UbitOdePlugin/ODECharacter.cs
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim/Region/Physics/UbitOdePlugin/ODECharacter.cs')
-rw-r--r--OpenSim/Region/Physics/UbitOdePlugin/ODECharacter.cs1411
1 files changed, 1411 insertions, 0 deletions
diff --git a/OpenSim/Region/Physics/UbitOdePlugin/ODECharacter.cs b/OpenSim/Region/Physics/UbitOdePlugin/ODECharacter.cs
new file mode 100644
index 0000000..6ffcb9e
--- /dev/null
+++ b/OpenSim/Region/Physics/UbitOdePlugin/ODECharacter.cs
@@ -0,0 +1,1411 @@
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 copyright
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
28
29// Revision by Ubit 2011/12
30
31using System;
32using System.Collections.Generic;
33using System.Reflection;
34using OpenMetaverse;
35using OdeAPI;
36using OpenSim.Framework;
37using OpenSim.Region.Physics.Manager;
38using log4net;
39
40namespace OpenSim.Region.Physics.OdePlugin
41{
42 /// <summary>
43 /// Various properties that ODE uses for AMotors but isn't exposed in ODE.NET so we must define them ourselves.
44 /// </summary>
45
46 public enum dParam : int
47 {
48 LowStop = 0,
49 HiStop = 1,
50 Vel = 2,
51 FMax = 3,
52 FudgeFactor = 4,
53 Bounce = 5,
54 CFM = 6,
55 StopERP = 7,
56 StopCFM = 8,
57 LoStop2 = 256,
58 HiStop2 = 257,
59 Vel2 = 258,
60 FMax2 = 259,
61 StopERP2 = 7 + 256,
62 StopCFM2 = 8 + 256,
63 LoStop3 = 512,
64 HiStop3 = 513,
65 Vel3 = 514,
66 FMax3 = 515,
67 StopERP3 = 7 + 512,
68 StopCFM3 = 8 + 512
69 }
70
71 public class OdeCharacter : PhysicsActor
72 {
73 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
74
75 private Vector3 _position;
76 private Vector3 _zeroPosition;
77 private bool _zeroFlag = false;
78 private Vector3 _velocity;
79 private Vector3 _target_velocity;
80 private Vector3 _acceleration;
81 private Vector3 m_rotationalVelocity;
82 private float m_mass = 80f;
83 public float m_density = 60f;
84 private bool m_pidControllerActive = true;
85 public float PID_D = 800.0f;
86 public float PID_P = 900.0f;
87 //private static float POSTURE_SERVO = 10000.0f;
88 public float CAPSULE_RADIUS = 0.37f;
89 public float CAPSULE_LENGTH = 2.140599f;
90 public float walkDivisor = 1.3f;
91 public float runDivisor = 0.8f;
92 private bool flying = false;
93 private bool m_iscolliding = false;
94 private bool m_iscollidingGround = false;
95 private bool m_iscollidingObj = false;
96 private bool m_alwaysRun = false;
97 private int m_requestedUpdateFrequency = 0;
98 public uint m_localID = 0;
99 public bool m_returnCollisions = false;
100 // taints and their non-tainted counterparts
101 public bool m_isPhysical = false; // the current physical status
102 public float MinimumGroundFlightOffset = 3f;
103
104 private float m_buoyancy = 0f;
105
106 // private CollisionLocker ode;
107
108 private string m_name = String.Empty;
109 // other filter control
110 int m_colliderfilter = 0;
111 // int m_colliderGroundfilter = 0;
112 int m_colliderObjectfilter = 0;
113
114 // Default we're a Character
115 private CollisionCategories m_collisionCategories = (CollisionCategories.Character);
116
117 // Default, Collide with Other Geometries, spaces, bodies and characters.
118 private CollisionCategories m_collisionFlags = (CollisionCategories.Character
119 | CollisionCategories.Geom
120 | CollisionCategories.VolumeDtc
121 );
122 // we do land collisions not ode | CollisionCategories.Land);
123 public IntPtr Body = IntPtr.Zero;
124 private OdeScene _parent_scene;
125 public IntPtr Shell = IntPtr.Zero;
126 public IntPtr Amotor = IntPtr.Zero;
127 public d.Mass ShellMass;
128// public bool collidelock = false;
129
130 private bool m_haseventsubscription = false;
131 public int m_eventsubscription = 0;
132 private CollisionEventUpdate CollisionEventsThisFrame = new CollisionEventUpdate();
133
134 // unique UUID of this character object
135 public UUID m_uuid;
136 public bool bad = false;
137
138 float mu;
139
140 public OdeCharacter(String avName, OdeScene parent_scene, Vector3 pos, Vector3 size, float pid_d, float pid_p, float capsule_radius, float density, float walk_divisor, float rundivisor)
141 {
142 m_uuid = UUID.Random();
143
144 if (pos.IsFinite())
145 {
146 if (pos.Z > 99999f)
147 {
148 pos.Z = parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
149 }
150 if (pos.Z < -100f) // shouldn't this be 0 ?
151 {
152 pos.Z = parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
153 }
154 _position = pos;
155 }
156 else
157 {
158 _position = new Vector3(((float)_parent_scene.WorldExtents.X * 0.5f), ((float)_parent_scene.WorldExtents.Y * 0.5f), parent_scene.GetTerrainHeightAtXY(128f, 128f) + 10f);
159 m_log.Warn("[PHYSICS]: Got NaN Position on Character Create");
160 }
161
162 _parent_scene = parent_scene;
163
164 PID_D = pid_d;
165 PID_P = pid_p;
166 CAPSULE_RADIUS = capsule_radius;
167 m_density = density;
168 m_mass = 80f; // sure we have a default
169
170 mu = parent_scene.AvatarFriction;
171
172 walkDivisor = walk_divisor;
173 runDivisor = rundivisor;
174
175 CAPSULE_LENGTH = size.Z * 1.15f - CAPSULE_RADIUS * 2.0f;
176 //m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString());
177
178 m_isPhysical = false; // current status: no ODE information exists
179
180 m_name = avName;
181
182 AddChange(changes.Add, null);
183 }
184
185 public override int PhysicsActorType
186 {
187 get { return (int)ActorTypes.Agent; }
188 set { return; }
189 }
190
191 public override void getContactData(ref ContactData cdata)
192 {
193 cdata.mu = mu;
194 cdata.bounce = 0;
195 cdata.softcolide = false;
196 }
197
198 public override bool Building { get; set; }
199
200 /// <summary>
201 /// If this is set, the avatar will move faster
202 /// </summary>
203 public override bool SetAlwaysRun
204 {
205 get { return m_alwaysRun; }
206 set { m_alwaysRun = value; }
207 }
208
209 public override uint LocalID
210 {
211 set { m_localID = value; }
212 }
213
214 public override bool Grabbed
215 {
216 set { return; }
217 }
218
219 public override bool Selected
220 {
221 set { return; }
222 }
223
224 public override float Buoyancy
225 {
226 get { return m_buoyancy; }
227 set { m_buoyancy = value; }
228 }
229
230 public override bool FloatOnWater
231 {
232 set { return; }
233 }
234
235 public override bool IsPhysical
236 {
237 get { return false; }
238 set { return; }
239 }
240
241 public override bool ThrottleUpdates
242 {
243 get { return false; }
244 set { return; }
245 }
246
247 public override bool Flying
248 {
249 get { return flying; }
250 set
251 {
252 flying = value;
253 // m_log.DebugFormat("[PHYSICS]: Set OdeCharacter Flying to {0}", flying);
254 }
255 }
256
257 /// <summary>
258 /// Returns if the avatar is colliding in general.
259 /// This includes the ground and objects and avatar.
260 /// </summary>
261 public override bool IsColliding
262 {
263 get { return (m_iscolliding || m_iscollidingGround); }
264 set
265 {
266 if (value)
267 {
268 m_colliderfilter += 2;
269 if (m_colliderfilter > 2)
270 m_colliderfilter = 2;
271 }
272 else
273 {
274 m_colliderfilter--;
275 if (m_colliderfilter < 0)
276 m_colliderfilter = 0;
277 }
278
279 if (m_colliderfilter == 0)
280 m_iscolliding = false;
281 else
282 {
283// SetPidStatus(false);
284 m_pidControllerActive = true;
285 m_iscolliding = true;
286 }
287 }
288 }
289
290 /// <summary>
291 /// Returns if an avatar is colliding with the ground
292 /// </summary>
293 public override bool CollidingGround
294 {
295 get { return m_iscollidingGround; }
296 set
297 {
298 /* we now control this
299 if (value)
300 {
301 m_colliderGroundfilter += 2;
302 if (m_colliderGroundfilter > 2)
303 m_colliderGroundfilter = 2;
304 }
305 else
306 {
307 m_colliderGroundfilter--;
308 if (m_colliderGroundfilter < 0)
309 m_colliderGroundfilter = 0;
310 }
311
312 if (m_colliderGroundfilter == 0)
313 m_iscollidingGround = false;
314 else
315 m_iscollidingGround = true;
316 */
317 }
318
319 }
320
321 /// <summary>
322 /// Returns if the avatar is colliding with an object
323 /// </summary>
324 public override bool CollidingObj
325 {
326 get { return m_iscollidingObj; }
327 set
328 {
329 // Ubit filter this also
330 if (value)
331 {
332 m_colliderObjectfilter += 2;
333 if (m_colliderObjectfilter > 2)
334 m_colliderObjectfilter = 2;
335 }
336 else
337 {
338 m_colliderObjectfilter--;
339 if (m_colliderObjectfilter < 0)
340 m_colliderObjectfilter = 0;
341 }
342
343 if (m_colliderObjectfilter == 0)
344 m_iscollidingObj = false;
345 else
346 m_iscollidingObj = true;
347
348 // m_iscollidingObj = value;
349/*
350 if (m_iscollidingObj)
351 m_pidControllerActive = false;
352 else
353 m_pidControllerActive = true;
354 */
355 }
356 }
357
358 /// <summary>
359 /// turn the PID controller on or off.
360 /// The PID Controller will turn on all by itself in many situations
361 /// </summary>
362 /// <param name="status"></param>
363 public void SetPidStatus(bool status)
364 {
365 m_pidControllerActive = status;
366 }
367
368 public override bool Stopped
369 {
370 get { return _zeroFlag; }
371 }
372
373 /// <summary>
374 /// This 'puts' an avatar somewhere in the physics space.
375 /// Not really a good choice unless you 'know' it's a good
376 /// spot otherwise you're likely to orbit the avatar.
377 /// </summary>
378 public override Vector3 Position
379 {
380 get { return _position; }
381 set
382 {
383 if (Body == IntPtr.Zero || Shell == IntPtr.Zero)
384 {
385 if (value.IsFinite())
386 {
387 if (value.Z > 9999999f)
388 {
389 value.Z = _parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
390 }
391 if (value.Z < -100f)
392 {
393 value.Z = _parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
394 }
395 AddChange(changes.Position, value);
396 }
397 else
398 {
399 m_log.Warn("[PHYSICS]: Got a NaN Position from Scene on a Character");
400 }
401 }
402 }
403 }
404
405 public override Vector3 RotationalVelocity
406 {
407 get { return m_rotationalVelocity; }
408 set { m_rotationalVelocity = value; }
409 }
410
411 /// <summary>
412 /// This property sets the height of the avatar only. We use the height to make sure the avatar stands up straight
413 /// and use it to offset landings properly
414 /// </summary>
415 public override Vector3 Size
416 {
417 get {
418 float d = CAPSULE_RADIUS * 2;
419 return new Vector3(d, d, (CAPSULE_LENGTH +d)/1.15f); }
420 set
421 {
422 if (value.IsFinite())
423 {
424 AddChange(changes.Size, value);
425 }
426 else
427 {
428 m_log.Warn("[PHYSICS]: Got a NaN Size from Scene on a Character");
429 }
430 }
431 }
432
433 /// <summary>
434 /// This creates the Avatar's physical Surrogate at the position supplied
435 /// </summary>
436 /// <param name="npositionX"></param>
437 /// <param name="npositionY"></param>
438 /// <param name="npositionZ"></param>
439
440 //
441 /// <summary>
442 /// Uses the capped cyllinder volume formula to calculate the avatar's mass.
443 /// This may be used in calculations in the scene/scenepresence
444 /// </summary>
445 public override float Mass
446 {
447 get
448 {
449 float AVvolume = (float)(Math.PI * CAPSULE_RADIUS * CAPSULE_RADIUS * (1.3333333333f * CAPSULE_RADIUS + CAPSULE_LENGTH));
450 return m_density * AVvolume;
451 }
452 }
453 public override void link(PhysicsActor obj)
454 {
455
456 }
457
458 public override void delink()
459 {
460
461 }
462
463 public override void LockAngularMotion(Vector3 axis)
464 {
465
466 }
467
468
469 public override Vector3 Force
470 {
471 get { return _target_velocity; }
472 set { return; }
473 }
474
475 public override int VehicleType
476 {
477 get { return 0; }
478 set { return; }
479 }
480
481 public override void VehicleFloatParam(int param, float value)
482 {
483
484 }
485
486 public override void VehicleVectorParam(int param, Vector3 value)
487 {
488
489 }
490
491 public override void VehicleRotationParam(int param, Quaternion rotation)
492 {
493
494 }
495
496 public override void VehicleFlags(int param, bool remove)
497 {
498
499 }
500
501 public override void SetVolumeDetect(int param)
502 {
503
504 }
505
506 public override Vector3 CenterOfMass
507 {
508 get
509 {
510 Vector3 pos = _position;
511 return pos;
512 }
513 }
514
515 public override Vector3 GeometricCenter
516 {
517 get
518 {
519 Vector3 pos = _position;
520 return pos;
521 }
522 }
523
524 //UBit mess
525 /* for later use
526 public override Vector3 PrimOOBsize
527 {
528 get
529 {
530 Vector3 s=Size;
531 s.X *=0.5f;
532 s.Y *=0.5f;
533 s.Z *=0.5f;
534 return s;
535 }
536 }
537
538 public override Vector3 PrimOOBoffset
539 {
540 get
541 {
542 return Vector3.Zero;
543 }
544 }
545 */
546
547 public override PrimitiveBaseShape Shape
548 {
549 set { return; }
550 }
551
552 public override Vector3 Velocity
553 {
554 get
555 {
556 return _velocity;
557 }
558 set
559 {
560 if (value.IsFinite())
561 {
562 AddChange(changes.Velocity, value);
563 }
564 else
565 {
566 m_log.Warn("[PHYSICS]: Got a NaN velocity from Scene in a Character");
567 }
568 }
569 }
570
571 public override Vector3 Torque
572 {
573 get { return Vector3.Zero; }
574 set { return; }
575 }
576
577 public override float CollisionScore
578 {
579 get { return 0f; }
580 set { }
581 }
582
583 public override bool Kinematic
584 {
585 get { return false; }
586 set { }
587 }
588
589 public override Quaternion Orientation
590 {
591 get { return Quaternion.Identity; }
592 set
593 {
594 }
595 }
596
597 public override Vector3 Acceleration
598 {
599 get { return _acceleration; }
600 set { }
601 }
602
603 public void SetAcceleration(Vector3 accel)
604 {
605 m_pidControllerActive = true;
606 _acceleration = accel;
607 }
608
609 /// <summary>
610 /// Adds the force supplied to the Target Velocity
611 /// The PID controller takes this target velocity and tries to make it a reality
612 /// </summary>
613 /// <param name="force"></param>
614 public override void AddForce(Vector3 force, bool pushforce)
615 {
616 if (force.IsFinite())
617 {
618 if (pushforce)
619 {
620 AddChange(changes.Force, force * m_density / _parent_scene.ODE_STEPSIZE / 28f);
621 }
622 else
623 {
624 AddChange(changes.Velocity, force);
625 }
626 }
627 else
628 {
629 m_log.Warn("[PHYSICS]: Got a NaN force applied to a Character");
630 }
631 //m_lastUpdateSent = false;
632 }
633
634 public override void AddAngularForce(Vector3 force, bool pushforce)
635 {
636
637 }
638
639 public override void SetMomentum(Vector3 momentum)
640 {
641 if (momentum.IsFinite())
642 AddChange(changes.Momentum, momentum);
643 }
644
645
646 // WARNING: This MUST NOT be called outside of ProcessTaints, else we can have unsynchronized access
647 // to ODE internals. ProcessTaints is called from within thread-locked Simulate(), so it is the only
648 // place that is safe to call this routine AvatarGeomAndBodyCreation.
649 private void AvatarGeomAndBodyCreation(float npositionX, float npositionY, float npositionZ)
650 {
651 _parent_scene.waitForSpaceUnlock(_parent_scene.ActiveSpace);
652 if (CAPSULE_LENGTH <= 0)
653 {
654 m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!");
655 CAPSULE_LENGTH = 0.01f;
656
657 }
658
659 if (CAPSULE_RADIUS <= 0)
660 {
661 m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!");
662 CAPSULE_RADIUS = 0.01f;
663
664 }
665 Shell = d.CreateCapsule(_parent_scene.ActiveSpace, CAPSULE_RADIUS, CAPSULE_LENGTH);
666
667 d.GeomSetCategoryBits(Shell, (uint)m_collisionCategories);
668 d.GeomSetCollideBits(Shell, (uint)m_collisionFlags);
669
670 d.MassSetCapsule(out ShellMass, m_density, 3, CAPSULE_RADIUS, CAPSULE_LENGTH);
671
672 m_mass = ShellMass.mass; // update mass
673
674 // rescale PID parameters
675 PID_D = _parent_scene.avPIDD;
676 PID_P = _parent_scene.avPIDP;
677
678 // rescale PID parameters so that this aren't affected by mass
679 // and so don't get unstable for some masses
680 // also scale by ode time step so you don't need to refix them
681
682 PID_D /= 50 * 80; //scale to original mass of around 80 and 50 ODE fps
683 PID_D *= m_mass / _parent_scene.ODE_STEPSIZE;
684 PID_P /= 50 * 80;
685 PID_P *= m_mass / _parent_scene.ODE_STEPSIZE;
686
687 Body = d.BodyCreate(_parent_scene.world);
688
689 _zeroFlag = false;
690 m_pidControllerActive = true;
691
692 d.BodySetAutoDisableFlag(Body, false);
693 d.BodySetPosition(Body, npositionX, npositionY, npositionZ);
694
695 _position.X = npositionX;
696 _position.Y = npositionY;
697 _position.Z = npositionZ;
698
699 d.BodySetMass(Body, ref ShellMass);
700 d.GeomSetBody(Shell, Body);
701
702 // The purpose of the AMotor here is to keep the avatar's physical
703 // surrogate from rotating while moving
704 Amotor = d.JointCreateAMotor(_parent_scene.world, IntPtr.Zero);
705 d.JointAttach(Amotor, Body, IntPtr.Zero);
706
707 d.JointSetAMotorMode(Amotor, 0);
708 d.JointSetAMotorNumAxes(Amotor, 3);
709 d.JointSetAMotorAxis(Amotor, 0, 0, 1, 0, 0);
710 d.JointSetAMotorAxis(Amotor, 1, 0, 0, 1, 0);
711 d.JointSetAMotorAxis(Amotor, 2, 0, 0, 0, 1);
712
713 d.JointSetAMotorAngle(Amotor, 0, 0);
714 d.JointSetAMotorAngle(Amotor, 1, 0);
715 d.JointSetAMotorAngle(Amotor, 2, 0);
716
717 d.JointSetAMotorParam(Amotor, (int)dParam.StopCFM, 0f); // make it HARD
718 d.JointSetAMotorParam(Amotor, (int)dParam.StopCFM2, 0f);
719 d.JointSetAMotorParam(Amotor, (int)dParam.StopCFM3, 0f);
720 d.JointSetAMotorParam(Amotor, (int)dParam.StopERP, 0.8f);
721 d.JointSetAMotorParam(Amotor, (int)dParam.StopERP2, 0.8f);
722 d.JointSetAMotorParam(Amotor, (int)dParam.StopERP3, 0.8f);
723
724 // These lowstops and high stops are effectively (no wiggle room)
725 d.JointSetAMotorParam(Amotor, (int)dParam.LowStop, -1e-5f);
726 d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, 1e-5f);
727 d.JointSetAMotorParam(Amotor, (int)dParam.LoStop2, -1e-5f);
728 d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, 1e-5f);
729 d.JointSetAMotorParam(Amotor, (int)dParam.LoStop3, -1e-5f);
730 d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 1e-5f);
731
732 d.JointSetAMotorParam(Amotor, (int)d.JointParam.Vel, 0);
733 d.JointSetAMotorParam(Amotor, (int)d.JointParam.Vel2, 0);
734 d.JointSetAMotorParam(Amotor, (int)d.JointParam.Vel3, 0);
735
736 d.JointSetAMotorParam(Amotor, (int)dParam.FMax, 5e6f);
737 d.JointSetAMotorParam(Amotor, (int)dParam.FMax2, 5e6f);
738 d.JointSetAMotorParam(Amotor, (int)dParam.FMax3, 5e6f);
739 }
740
741 /// <summary>
742 /// Destroys the avatar body and geom
743
744 private void AvatarGeomAndBodyDestroy()
745 {
746 // Kill the Amotor
747 if (Amotor != IntPtr.Zero)
748 {
749 d.JointDestroy(Amotor);
750 Amotor = IntPtr.Zero;
751 }
752
753 if (Body != IntPtr.Zero)
754 {
755 //kill the body
756 d.BodyDestroy(Body);
757 Body = IntPtr.Zero;
758 }
759
760 //kill the Geometry
761 if (Shell != IntPtr.Zero)
762 {
763 _parent_scene.geom_name_map.Remove(Shell);
764 _parent_scene.waitForSpaceUnlock(_parent_scene.ActiveSpace);
765 d.GeomDestroy(Shell);
766 Shell = IntPtr.Zero;
767 }
768 }
769
770 /// <summary>
771 /// Called from Simulate
772 /// This is the avatar's movement control + PID Controller
773 /// </summary>
774 /// <param name="timeStep"></param>
775 public void Move(float timeStep, List<OdeCharacter> defects)
776 {
777 if (Body == IntPtr.Zero)
778 return;
779
780 d.Vector3 dtmp = d.BodyGetPosition(Body);
781 Vector3 localpos = new Vector3(dtmp.X, dtmp.Y, dtmp.Z);
782
783 // the Amotor still lets avatar rotation to drift during colisions
784 // so force it back to identity
785
786 d.Quaternion qtmp;
787 qtmp.W = 1;
788 qtmp.X = 0;
789 qtmp.Y = 0;
790 qtmp.Z = 0;
791 d.BodySetQuaternion(Body, ref qtmp);
792
793 if (m_pidControllerActive == false)
794 {
795 _zeroPosition = localpos;
796 }
797
798 if (!localpos.IsFinite())
799 {
800 m_log.Warn("[PHYSICS]: Avatar Position is non-finite!");
801 defects.Add(this);
802 // _parent_scene.RemoveCharacter(this);
803
804 // destroy avatar capsule and related ODE data
805 AvatarGeomAndBodyDestroy();
806 return;
807 }
808
809 // check outbounds forcing to be in world
810 bool fixbody = false;
811 if (localpos.X < 0.0f)
812 {
813 fixbody = true;
814 localpos.X = 0.1f;
815 }
816 else if (localpos.X > _parent_scene.WorldExtents.X - 0.1f)
817 {
818 fixbody = true;
819 localpos.X = _parent_scene.WorldExtents.X - 0.1f;
820 }
821 if (localpos.Y < 0.0f)
822 {
823 fixbody = true;
824 localpos.Y = 0.1f;
825 }
826 else if (localpos.Y > _parent_scene.WorldExtents.Y - 0.1)
827 {
828 fixbody = true;
829 localpos.Y = _parent_scene.WorldExtents.Y - 0.1f;
830 }
831 if (fixbody)
832 d.BodySetPosition(Body, localpos.X, localpos.Y, localpos.Z);
833
834 Vector3 vec = Vector3.Zero;
835 dtmp = d.BodyGetLinearVel(Body);
836 Vector3 vel = new Vector3(dtmp.X, dtmp.Y, dtmp.Z);
837
838 float movementdivisor = 1f;
839 //Ubit change divisions into multiplications below
840 if (!m_alwaysRun)
841 movementdivisor = 1 / walkDivisor;
842 else
843 movementdivisor = 1 / runDivisor;
844
845 //******************************************
846 // colide with land
847 d.AABB aabb;
848 d.GeomGetAABB(Shell, out aabb);
849 float chrminZ = aabb.MinZ;
850
851 Vector3 posch = localpos;
852
853 float ftmp;
854
855 if (flying)
856 {
857 ftmp = timeStep;
858 posch.X += vel.X * ftmp;
859 posch.Y += vel.Y * ftmp;
860 }
861
862 float terrainheight = _parent_scene.GetTerrainHeightAtXY(posch.X, posch.Y);
863 if (chrminZ < terrainheight)
864 {
865 float depth = terrainheight - chrminZ;
866 if (!flying)
867 {
868 vec.Z = -vel.Z * PID_D * 1.5f + depth * PID_P * 50;
869 }
870 else
871 vec.Z = depth * PID_P * 50;
872
873 if (depth < 0.1f)
874 {
875 m_iscolliding = true;
876 m_colliderfilter = 2;
877 m_iscollidingGround = true;
878
879 ContactPoint contact = new ContactPoint();
880 contact.PenetrationDepth = depth;
881 contact.Position.X = localpos.X;
882 contact.Position.Y = localpos.Y;
883 contact.Position.Z = chrminZ;
884 contact.SurfaceNormal.X = 0f;
885 contact.SurfaceNormal.Y = 0f;
886 contact.SurfaceNormal.Z = -1f;
887 AddCollisionEvent(0, contact);
888
889 vec.Z *= 0.5f;
890 }
891
892 else
893 m_iscollidingGround = false;
894 }
895 else
896 m_iscollidingGround = false;
897
898 //******************************************
899
900 // if velocity is zero, use position control; otherwise, velocity control
901 if (_target_velocity.X == 0.0f && _target_velocity.Y == 0.0f && _target_velocity.Z == 0.0f
902 && m_iscolliding)
903 {
904 // keep track of where we stopped. No more slippin' & slidin'
905 if (!_zeroFlag)
906 {
907 _zeroFlag = true;
908 _zeroPosition = localpos;
909 }
910 if (m_pidControllerActive)
911 {
912 // We only want to deactivate the PID Controller if we think we want to have our surrogate
913 // react to the physics scene by moving it's position.
914 // Avatar to Avatar collisions
915 // Prim to avatar collisions
916
917 vec.X = -vel.X * PID_D + (_zeroPosition.X - localpos.X) * (PID_P * 2);
918 vec.Y = -vel.Y * PID_D + (_zeroPosition.Y - localpos.Y) * (PID_P * 2);
919 if (flying)
920 {
921 vec.Z += -vel.Z * PID_D + (_zeroPosition.Z - localpos.Z) * PID_P;
922 }
923 }
924 //PidStatus = true;
925 }
926 else
927 {
928 m_pidControllerActive = true;
929 _zeroFlag = false;
930
931 if (m_iscolliding)
932 {
933 if (!flying)
934 {
935 if (_target_velocity.Z > 0.0f)
936 {
937 // We're colliding with something and we're not flying but we're moving
938 // This means we're walking or running. JUMPING
939 vec.Z += (_target_velocity.Z - vel.Z) * PID_D * 1.2f;// +(_zeroPosition.Z - localpos.Z) * PID_P;
940 }
941 // We're standing on something
942 vec.X = ((_target_velocity.X * movementdivisor) - vel.X) * (PID_D);
943 vec.Y = ((_target_velocity.Y * movementdivisor) - vel.Y) * (PID_D);
944 }
945 else
946 {
947 // We're flying and colliding with something
948 vec.X = ((_target_velocity.X * movementdivisor) - vel.X) * (PID_D * 0.0625f);
949 vec.Y = ((_target_velocity.Y * movementdivisor) - vel.Y) * (PID_D * 0.0625f);
950 vec.Z += (_target_velocity.Z - vel.Z) * (PID_D);
951 }
952 }
953 else // ie not colliding
954 {
955 if (flying) //(!m_iscolliding && flying)
956 {
957 // we're in mid air suspended
958 vec.X = ((_target_velocity.X * movementdivisor) - vel.X) * (PID_D * 1.667f);
959 vec.Y = ((_target_velocity.Y * movementdivisor) - vel.Y) * (PID_D * 1.667f);
960 vec.Z += (_target_velocity.Z - vel.Z) * (PID_D);
961 }
962
963 else
964 {
965 // we're not colliding and we're not flying so that means we're falling!
966 // m_iscolliding includes collisions with the ground.
967
968 // d.Vector3 pos = d.BodyGetPosition(Body);
969 vec.X = (_target_velocity.X - vel.X) * PID_D * 0.833f;
970 vec.Y = (_target_velocity.Y - vel.Y) * PID_D * 0.833f;
971 }
972 }
973 }
974
975 if (flying)
976 {
977 vec.Z -= _parent_scene.gravityz * m_mass;
978
979 //Added for auto fly height. Kitto Flora
980 float target_altitude = _parent_scene.GetTerrainHeightAtXY(localpos.X, localpos.Y) + MinimumGroundFlightOffset;
981
982 if (localpos.Z < target_altitude)
983 {
984 vec.Z += (target_altitude - localpos.Z) * PID_P * 5.0f;
985 }
986 // end add Kitto Flora
987 }
988
989 if (vel.X * vel.X + vel.Y * vel.Y + vel.Z * vel.Z > 2500.0f) // 50m/s apply breaks
990 {
991 float breakfactor = 0.16f * m_mass; // will give aprox 60m/s terminal velocity at free fall
992 vec.X -= breakfactor * vel.X;
993 vec.Y -= breakfactor * vel.Y;
994 vec.Z -= breakfactor * vel.Z;
995 }
996
997 if (vec.IsFinite())
998 {
999 if (vec.X != 0 || vec.Y !=0 || vec.Z !=0)
1000 d.BodyAddForce(Body, vec.X, vec.Y, vec.Z);
1001 }
1002 else
1003 {
1004 m_log.Warn("[PHYSICS]: Got a NaN force vector in Move()");
1005 m_log.Warn("[PHYSICS]: Avatar Position is non-finite!");
1006 defects.Add(this);
1007 // _parent_scene.RemoveCharacter(this);
1008 // destroy avatar capsule and related ODE data
1009 AvatarGeomAndBodyDestroy();
1010 return;
1011 }
1012
1013 // update our local ideia of position velocity and aceleration
1014 _position = localpos;
1015 if (_zeroFlag)
1016 {
1017 _velocity = Vector3.Zero;
1018 _acceleration = Vector3.Zero;
1019 }
1020 else
1021 {
1022 _acceleration = _velocity; // previus velocity
1023 _velocity = vel;
1024 _acceleration = (vel - _acceleration) / timeStep;
1025 }
1026
1027 }
1028
1029 /// <summary>
1030 /// Updates the reported position and velocity.
1031 /// Used to copy variables from unmanaged space at heartbeat rate and also trigger scene updates acording
1032 /// also outbounds checking
1033 /// copy and outbounds now done in move(..) at ode rate
1034 ///
1035 /// </summary>
1036 public void UpdatePositionAndVelocity()
1037 {
1038 return;
1039
1040// if (Body == IntPtr.Zero)
1041// return;
1042
1043 }
1044
1045 /// <summary>
1046 /// Cleanup the things we use in the scene.
1047 /// </summary>
1048 public void Destroy()
1049 {
1050 AddChange(changes.Remove, null);
1051 }
1052
1053 public override void CrossingFailure()
1054 {
1055 }
1056
1057 public override Vector3 PIDTarget { set { return; } }
1058 public override bool PIDActive { set { return; } }
1059 public override float PIDTau { set { return; } }
1060
1061 public override float PIDHoverHeight { set { return; } }
1062 public override bool PIDHoverActive { set { return; } }
1063 public override PIDHoverType PIDHoverType { set { return; } }
1064 public override float PIDHoverTau { set { return; } }
1065
1066 public override Quaternion APIDTarget { set { return; } }
1067
1068 public override bool APIDActive { set { return; } }
1069
1070 public override float APIDStrength { set { return; } }
1071
1072 public override float APIDDamping { set { return; } }
1073
1074
1075 public override void SubscribeEvents(int ms)
1076 {
1077 m_requestedUpdateFrequency = ms;
1078 m_eventsubscription = ms;
1079 _parent_scene.AddCollisionEventReporting(this);
1080 m_haseventsubscription = true;
1081 }
1082
1083 public override void UnSubscribeEvents()
1084 {
1085 m_haseventsubscription = false;
1086 _parent_scene.RemoveCollisionEventReporting(this);
1087 m_requestedUpdateFrequency = 0;
1088 m_eventsubscription = 0;
1089 }
1090
1091 public void AddCollisionEvent(uint CollidedWith, ContactPoint contact)
1092 {
1093 if (m_haseventsubscription)
1094 {
1095 // m_log.DebugFormat(
1096 // "[PHYSICS]: Adding collision event for {0}, collidedWith {1}, contact {2}", "", CollidedWith, contact);
1097
1098 CollisionEventsThisFrame.AddCollider(CollidedWith, contact);
1099 }
1100 }
1101
1102 public void SendCollisions()
1103 {
1104 if (m_haseventsubscription && m_eventsubscription > m_requestedUpdateFrequency)
1105 {
1106 if (CollisionEventsThisFrame != null)
1107 {
1108 base.SendCollisionUpdate(CollisionEventsThisFrame);
1109 }
1110 CollisionEventsThisFrame = new CollisionEventUpdate();
1111 m_eventsubscription = 0;
1112 }
1113 }
1114
1115 public override bool SubscribedEvents()
1116 {
1117 return m_haseventsubscription;
1118 }
1119
1120 private void changePhysicsStatus(bool NewStatus)
1121 {
1122 if (NewStatus != m_isPhysical)
1123 {
1124 if (NewStatus)
1125 {
1126 // Create avatar capsule and related ODE data
1127 if ((Shell != IntPtr.Zero))
1128 {
1129 // a lost shell ?
1130 m_log.Warn("[PHYSICS]: re-creating the following avatar ODE data, even though it already exists - "
1131 + (Shell != IntPtr.Zero ? "Shell " : "")
1132 + (Body != IntPtr.Zero ? "Body " : "")
1133 + (Amotor != IntPtr.Zero ? "Amotor " : ""));
1134 AvatarGeomAndBodyDestroy();
1135 }
1136
1137 AvatarGeomAndBodyCreation(_position.X, _position.Y, _position.Z);
1138 _parent_scene.geom_name_map[Shell] = m_name;
1139 _parent_scene.actor_name_map[Shell] = (PhysicsActor)this;
1140 _parent_scene.AddCharacter(this);
1141 }
1142 else
1143 {
1144 _parent_scene.RemoveCharacter(this);
1145 // destroy avatar capsule and related ODE data
1146 AvatarGeomAndBodyDestroy();
1147 }
1148
1149 m_isPhysical = NewStatus;
1150 }
1151 }
1152
1153 private void changeAdd()
1154 {
1155 changePhysicsStatus(true);
1156 }
1157
1158 private void changeRemove()
1159 {
1160 changePhysicsStatus(false);
1161 }
1162
1163 private void changeShape(PrimitiveBaseShape arg)
1164 {
1165 }
1166
1167 private void changeSize(Vector3 Size)
1168 {
1169 if (Size.IsFinite())
1170 {
1171 float caplen = Size.Z;
1172
1173 caplen = caplen * 1.15f - CAPSULE_RADIUS * 2.0f;
1174
1175 if (caplen != CAPSULE_LENGTH)
1176 {
1177 if (Shell != IntPtr.Zero && Body != IntPtr.Zero && Amotor != IntPtr.Zero)
1178 {
1179 AvatarGeomAndBodyDestroy();
1180
1181 float prevCapsule = CAPSULE_LENGTH;
1182 CAPSULE_LENGTH = caplen;
1183
1184 AvatarGeomAndBodyCreation(_position.X, _position.Y,
1185 _position.Z + (CAPSULE_LENGTH - prevCapsule) * 0.5f);
1186
1187 Velocity = Vector3.Zero;
1188
1189 _parent_scene.geom_name_map[Shell] = m_name;
1190 _parent_scene.actor_name_map[Shell] = (PhysicsActor)this;
1191 }
1192 else
1193 {
1194 m_log.Warn("[PHYSICS]: trying to change capsule size, but the following ODE data is missing - "
1195 + (Shell == IntPtr.Zero ? "Shell " : "")
1196 + (Body == IntPtr.Zero ? "Body " : "")
1197 + (Amotor == IntPtr.Zero ? "Amotor " : ""));
1198 }
1199 }
1200
1201 m_pidControllerActive = true;
1202 }
1203 else
1204 {
1205 m_log.Warn("[PHYSICS]: Got a NaN Size from Scene on a Character");
1206 }
1207 }
1208
1209 private void changePosition( Vector3 newPos)
1210 {
1211 if (Body != IntPtr.Zero)
1212 d.BodySetPosition(Body, newPos.X, newPos.Y, newPos.Z);
1213 _position = newPos;
1214 }
1215
1216 private void changeOrientation(Quaternion newOri)
1217 {
1218 }
1219
1220 private void changeVelocity(Vector3 newVel)
1221 {
1222 m_pidControllerActive = true;
1223 _target_velocity = newVel;
1224 }
1225
1226 private void changeSetTorque(Vector3 newTorque)
1227 {
1228 }
1229
1230 private void changeAddForce(Vector3 newForce)
1231 {
1232 }
1233
1234 private void changeAddAngularForce(Vector3 arg)
1235 {
1236 }
1237
1238 private void changeAngularLock(Vector3 arg)
1239 {
1240 }
1241
1242 private void changeFloatOnWater(bool arg)
1243 {
1244 }
1245
1246 private void changeVolumedetetion(bool arg)
1247 {
1248 }
1249
1250 private void changeSelectedStatus(bool arg)
1251 {
1252 }
1253
1254 private void changeDisable(bool arg)
1255 {
1256 }
1257
1258 private void changeBuilding(bool arg)
1259 {
1260 }
1261
1262 private void changeForce(Vector3 newForce)
1263 {
1264 m_pidControllerActive = false;
1265 if (Body != IntPtr.Zero)
1266 {
1267 if (newForce.X != 0f || newForce.Y != 0f || newForce.Z != 0)
1268 d.BodyAddForce(Body, newForce.X, newForce.Y, newForce.Z);
1269 }
1270 }
1271
1272 // for now momentum is actually velocity
1273 private void changeMomentum(Vector3 newmomentum)
1274 {
1275 _velocity = newmomentum;
1276 _target_velocity = newmomentum;
1277 m_pidControllerActive = true;
1278 if (Body != IntPtr.Zero)
1279 d.BodySetLinearVel(Body, newmomentum.X, newmomentum.Y, newmomentum.Z);
1280 }
1281
1282 private void donullchange()
1283 {
1284 }
1285
1286 public bool DoAChange(changes what, object arg)
1287 {
1288 if (Shell == IntPtr.Zero && what != changes.Add && what != changes.Remove)
1289 {
1290 return false;
1291 }
1292
1293 // nasty switch
1294 switch (what)
1295 {
1296 case changes.Add:
1297 changeAdd();
1298 break;
1299 case changes.Remove:
1300 changeRemove();
1301 break;
1302
1303 case changes.Position:
1304 changePosition((Vector3)arg);
1305 break;
1306
1307 case changes.Orientation:
1308 changeOrientation((Quaternion)arg);
1309 break;
1310
1311 case changes.PosOffset:
1312 donullchange();
1313 break;
1314
1315 case changes.OriOffset:
1316 donullchange();
1317 break;
1318
1319 case changes.Velocity:
1320 changeVelocity((Vector3)arg);
1321 break;
1322
1323 // case changes.Acceleration:
1324 // changeacceleration((Vector3)arg);
1325 // break;
1326 // case changes.AngVelocity:
1327 // changeangvelocity((Vector3)arg);
1328 // break;
1329
1330 case changes.Force:
1331 changeForce((Vector3)arg);
1332 break;
1333
1334 case changes.Torque:
1335 changeSetTorque((Vector3)arg);
1336 break;
1337
1338 case changes.AddForce:
1339 changeAddForce((Vector3)arg);
1340 break;
1341
1342 case changes.AddAngForce:
1343 changeAddAngularForce((Vector3)arg);
1344 break;
1345
1346 case changes.AngLock:
1347 changeAngularLock((Vector3)arg);
1348 break;
1349
1350 case changes.Size:
1351 changeSize((Vector3)arg);
1352 break;
1353
1354 case changes.Momentum:
1355 changeMomentum((Vector3)arg);
1356 break;
1357/* not in use for now
1358 case changes.Shape:
1359 changeShape((PrimitiveBaseShape)arg);
1360 break;
1361
1362 case changes.CollidesWater:
1363 changeFloatOnWater((bool)arg);
1364 break;
1365
1366 case changes.VolumeDtc:
1367 changeVolumedetetion((bool)arg);
1368 break;
1369
1370 case changes.Physical:
1371 changePhysicsStatus((bool)arg);
1372 break;
1373
1374 case changes.Selected:
1375 changeSelectedStatus((bool)arg);
1376 break;
1377
1378 case changes.disabled:
1379 changeDisable((bool)arg);
1380 break;
1381
1382 case changes.building:
1383 changeBuilding((bool)arg);
1384 break;
1385*/
1386 case changes.Null:
1387 donullchange();
1388 break;
1389
1390 default:
1391 donullchange();
1392 break;
1393 }
1394 return false;
1395 }
1396
1397 public void AddChange(changes what, object arg)
1398 {
1399 _parent_scene.AddChange((PhysicsActor)this, what, arg);
1400 }
1401
1402
1403 internal void AddCollisionFrameTime(int p)
1404 {
1405 // protect it from overflow crashing
1406 if (m_eventsubscription + p >= int.MaxValue)
1407 m_eventsubscription = 0;
1408 m_eventsubscription += p;
1409 }
1410 }
1411}