BSMotors.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. using System;
  29. using System.Collections.Generic;
  30. using System.Text;
  31. using OpenMetaverse;
  32. using OpenSim.Framework;
  33. namespace OpenSim.Region.Physics.BulletSNPlugin
  34. {
  35. public abstract class BSMotor
  36. {
  37. // Timescales and other things can be turned off by setting them to 'infinite'.
  38. public const float Infinite = 12345.6f;
  39. public readonly static Vector3 InfiniteVector = new Vector3(BSMotor.Infinite, BSMotor.Infinite, BSMotor.Infinite);
  40. public BSMotor(string useName)
  41. {
  42. UseName = useName;
  43. PhysicsScene = null;
  44. Enabled = true;
  45. }
  46. public virtual bool Enabled { get; set; }
  47. public virtual void Reset() { }
  48. public virtual void Zero() { }
  49. public virtual void GenerateTestOutput(float timeStep) { }
  50. // A name passed at motor creation for easily identifyable debugging messages.
  51. public string UseName { get; private set; }
  52. // Used only for outputting debug information. Might not be set so check for null.
  53. public BSScene PhysicsScene { get; set; }
  54. protected void MDetailLog(string msg, params Object[] parms)
  55. {
  56. if (PhysicsScene != null)
  57. {
  58. if (PhysicsScene.VehicleLoggingEnabled)
  59. {
  60. PhysicsScene.DetailLog(msg, parms);
  61. }
  62. }
  63. }
  64. }
  65. // Motor which moves CurrentValue to TargetValue over TimeScale seconds.
  66. // The TargetValue decays in TargetValueDecayTimeScale and
  67. // the CurrentValue will be held back by FrictionTimeScale.
  68. // This motor will "zero itself" over time in that the targetValue will
  69. // decay to zero and the currentValue will follow it to that zero.
  70. // The overall effect is for the returned correction value to go from large
  71. // values (the total difference between current and target minus friction)
  72. // to small and eventually zero values.
  73. // TimeScale and TargetDelayTimeScale may be 'infinite' which means no decay.
  74. // For instance, if something is moving at speed X and the desired speed is Y,
  75. // CurrentValue is X and TargetValue is Y. As the motor is stepped, new
  76. // values of CurrentValue are returned that approach the TargetValue.
  77. // The feature of decaying TargetValue is so vehicles will eventually
  78. // come to a stop rather than run forever. This can be disabled by
  79. // setting TargetValueDecayTimescale to 'infinite'.
  80. // The change from CurrentValue to TargetValue is linear over TimeScale seconds.
  81. public class BSVMotor : BSMotor
  82. {
  83. // public Vector3 FrameOfReference { get; set; }
  84. // public Vector3 Offset { get; set; }
  85. public virtual float TimeScale { get; set; }
  86. public virtual float TargetValueDecayTimeScale { get; set; }
  87. public virtual Vector3 FrictionTimescale { get; set; }
  88. public virtual float Efficiency { get; set; }
  89. public virtual float ErrorZeroThreshold { get; set; }
  90. public virtual Vector3 TargetValue { get; protected set; }
  91. public virtual Vector3 CurrentValue { get; protected set; }
  92. public virtual Vector3 LastError { get; protected set; }
  93. public virtual bool ErrorIsZero
  94. { get {
  95. return (LastError == Vector3.Zero || LastError.LengthSquared() <= ErrorZeroThreshold);
  96. }
  97. }
  98. public BSVMotor(string useName)
  99. : base(useName)
  100. {
  101. TimeScale = TargetValueDecayTimeScale = BSMotor.Infinite;
  102. Efficiency = 1f;
  103. FrictionTimescale = BSMotor.InfiniteVector;
  104. CurrentValue = TargetValue = Vector3.Zero;
  105. ErrorZeroThreshold = 0.001f;
  106. }
  107. public BSVMotor(string useName, float timeScale, float decayTimeScale, Vector3 frictionTimeScale, float efficiency)
  108. : this(useName)
  109. {
  110. TimeScale = timeScale;
  111. TargetValueDecayTimeScale = decayTimeScale;
  112. FrictionTimescale = frictionTimeScale;
  113. Efficiency = efficiency;
  114. CurrentValue = TargetValue = Vector3.Zero;
  115. }
  116. public void SetCurrent(Vector3 current)
  117. {
  118. CurrentValue = current;
  119. }
  120. public void SetTarget(Vector3 target)
  121. {
  122. TargetValue = target;
  123. }
  124. public override void Zero()
  125. {
  126. base.Zero();
  127. CurrentValue = TargetValue = Vector3.Zero;
  128. }
  129. // Compute the next step and return the new current value
  130. public virtual Vector3 Step(float timeStep)
  131. {
  132. if (!Enabled) return TargetValue;
  133. Vector3 origTarget = TargetValue; // DEBUG
  134. Vector3 origCurrVal = CurrentValue; // DEBUG
  135. Vector3 correction = Vector3.Zero;
  136. Vector3 error = TargetValue - CurrentValue;
  137. if (!error.ApproxEquals(Vector3.Zero, ErrorZeroThreshold))
  138. {
  139. correction = Step(timeStep, error);
  140. CurrentValue += correction;
  141. // The desired value reduces to zero which also reduces the difference with current.
  142. // If the decay time is infinite, don't decay at all.
  143. float decayFactor = 0f;
  144. if (TargetValueDecayTimeScale != BSMotor.Infinite)
  145. {
  146. decayFactor = (1.0f / TargetValueDecayTimeScale) * timeStep;
  147. TargetValue *= (1f - decayFactor);
  148. }
  149. // The amount we can correct the error is reduced by the friction
  150. Vector3 frictionFactor = Vector3.Zero;
  151. if (FrictionTimescale != BSMotor.InfiniteVector)
  152. {
  153. // frictionFactor = (Vector3.One / FrictionTimescale) * timeStep;
  154. // Individual friction components can be 'infinite' so compute each separately.
  155. frictionFactor.X = (FrictionTimescale.X == BSMotor.Infinite) ? 0f : (1f / FrictionTimescale.X);
  156. frictionFactor.Y = (FrictionTimescale.Y == BSMotor.Infinite) ? 0f : (1f / FrictionTimescale.Y);
  157. frictionFactor.Z = (FrictionTimescale.Z == BSMotor.Infinite) ? 0f : (1f / FrictionTimescale.Z);
  158. frictionFactor *= timeStep;
  159. CurrentValue *= (Vector3.One - frictionFactor);
  160. }
  161. MDetailLog("{0}, BSVMotor.Step,nonZero,{1},origCurr={2},origTarget={3},timeStep={4},err={5},corr={6}",
  162. BSScene.DetailLogZero, UseName, origCurrVal, origTarget,
  163. timeStep, error, correction);
  164. MDetailLog("{0}, BSVMotor.Step,nonZero,{1},tgtDecayTS={2},decayFact={3},frictTS={4},frictFact={5},tgt={6},curr={7}",
  165. BSScene.DetailLogZero, UseName,
  166. TargetValueDecayTimeScale, decayFactor, FrictionTimescale, frictionFactor,
  167. TargetValue, CurrentValue);
  168. }
  169. else
  170. {
  171. // Difference between what we have and target is small. Motor is done.
  172. CurrentValue = TargetValue;
  173. MDetailLog("{0}, BSVMotor.Step,zero,{1},origTgt={2},origCurr={3},ret={4}",
  174. BSScene.DetailLogZero, UseName, origCurrVal, origTarget, CurrentValue);
  175. }
  176. return CurrentValue;
  177. }
  178. public virtual Vector3 Step(float timeStep, Vector3 error)
  179. {
  180. if (!Enabled) return Vector3.Zero;
  181. LastError = error;
  182. Vector3 returnCorrection = Vector3.Zero;
  183. if (!error.ApproxEquals(Vector3.Zero, ErrorZeroThreshold))
  184. {
  185. // correction = error / secondsItShouldTakeToCorrect
  186. Vector3 correctionAmount;
  187. if (TimeScale == 0f || TimeScale == BSMotor.Infinite)
  188. correctionAmount = error * timeStep;
  189. else
  190. correctionAmount = error / TimeScale * timeStep;
  191. returnCorrection = correctionAmount;
  192. MDetailLog("{0}, BSVMotor.Step,nonZero,{1},timeStep={2},timeScale={3},err={4},corr={5}",
  193. BSScene.DetailLogZero, UseName, timeStep, TimeScale, error, correctionAmount);
  194. }
  195. return returnCorrection;
  196. }
  197. // The user sets all the parameters and calls this which outputs values until error is zero.
  198. public override void GenerateTestOutput(float timeStep)
  199. {
  200. // maximum number of outputs to generate.
  201. int maxOutput = 50;
  202. MDetailLog("{0},BSVMotor.Test,{1},===================================== BEGIN Test Output", BSScene.DetailLogZero, UseName);
  203. MDetailLog("{0},BSVMotor.Test,{1},timeScale={2},targDlyTS={3},frictTS={4},eff={5},curr={6},tgt={7}",
  204. BSScene.DetailLogZero, UseName,
  205. TimeScale, TargetValueDecayTimeScale, FrictionTimescale, Efficiency,
  206. CurrentValue, TargetValue);
  207. LastError = BSMotor.InfiniteVector;
  208. while (maxOutput-- > 0 && !LastError.ApproxEquals(Vector3.Zero, ErrorZeroThreshold))
  209. {
  210. Vector3 lastStep = Step(timeStep);
  211. MDetailLog("{0},BSVMotor.Test,{1},cur={2},tgt={3},lastError={4},lastStep={5}",
  212. BSScene.DetailLogZero, UseName, CurrentValue, TargetValue, LastError, lastStep);
  213. }
  214. MDetailLog("{0},BSVMotor.Test,{1},===================================== END Test Output", BSScene.DetailLogZero, UseName);
  215. }
  216. public override string ToString()
  217. {
  218. return String.Format("<{0},curr={1},targ={2},decayTS={3},frictTS={4}>",
  219. UseName, CurrentValue, TargetValue, TargetValueDecayTimeScale, FrictionTimescale);
  220. }
  221. }
  222. public class BSFMotor : BSMotor
  223. {
  224. public float TimeScale { get; set; }
  225. public float DecayTimeScale { get; set; }
  226. public float Friction { get; set; }
  227. public float Efficiency { get; set; }
  228. public float Target { get; private set; }
  229. public float CurrentValue { get; private set; }
  230. public BSFMotor(string useName, float timeScale, float decayTimescale, float friction, float efficiency)
  231. : base(useName)
  232. {
  233. }
  234. public void SetCurrent(float target)
  235. {
  236. }
  237. public void SetTarget(float target)
  238. {
  239. }
  240. public virtual float Step(float timeStep)
  241. {
  242. return 0f;
  243. }
  244. }
  245. // Proportional, Integral, Derivitive Motor
  246. // Good description at http://www.answers.com/topic/pid-controller . Includes processes for choosing p, i and d factors.
  247. public class BSPIDVMotor : BSVMotor
  248. {
  249. // Larger makes more overshoot, smaller means converge quicker. Range of 0.1 to 10.
  250. public Vector3 proportionFactor { get; set; }
  251. public Vector3 integralFactor { get; set; }
  252. public Vector3 derivFactor { get; set; }
  253. // Arbritrary factor range.
  254. // EfficiencyHigh means move quickly to the correct number. EfficiencyLow means might over correct.
  255. public float EfficiencyHigh = 0.4f;
  256. public float EfficiencyLow = 4.0f;
  257. // Running integration of the error
  258. Vector3 RunningIntegration { get; set; }
  259. public BSPIDVMotor(string useName)
  260. : base(useName)
  261. {
  262. proportionFactor = new Vector3(1.00f, 1.00f, 1.00f);
  263. integralFactor = new Vector3(1.00f, 1.00f, 1.00f);
  264. derivFactor = new Vector3(1.00f, 1.00f, 1.00f);
  265. RunningIntegration = Vector3.Zero;
  266. LastError = Vector3.Zero;
  267. }
  268. public override void Zero()
  269. {
  270. base.Zero();
  271. }
  272. public override float Efficiency
  273. {
  274. get { return base.Efficiency; }
  275. set
  276. {
  277. base.Efficiency = Util.Clamp(value, 0f, 1f);
  278. // Compute factors based on efficiency.
  279. // If efficiency is high (1f), use a factor value that moves the error value to zero with little overshoot.
  280. // If efficiency is low (0f), use a factor value that overcorrects.
  281. // TODO: might want to vary contribution of different factor depending on efficiency.
  282. float factor = ((1f - this.Efficiency) * EfficiencyHigh + EfficiencyLow) / 3f;
  283. // float factor = (1f - this.Efficiency) * EfficiencyHigh + EfficiencyLow;
  284. proportionFactor = new Vector3(factor, factor, factor);
  285. integralFactor = new Vector3(factor, factor, factor);
  286. derivFactor = new Vector3(factor, factor, factor);
  287. }
  288. }
  289. // Ignore Current and Target Values and just advance the PID computation on this error.
  290. public override Vector3 Step(float timeStep, Vector3 error)
  291. {
  292. if (!Enabled) return Vector3.Zero;
  293. // Add up the error so we can integrate over the accumulated errors
  294. RunningIntegration += error * timeStep;
  295. // A simple derivitive is the rate of change from the last error.
  296. Vector3 derivFactor = (error - LastError) * timeStep;
  297. LastError = error;
  298. // Correction = -(proportionOfPresentError + accumulationOfPastError + rateOfChangeOfError)
  299. Vector3 ret = -(
  300. error * proportionFactor
  301. + RunningIntegration * integralFactor
  302. + derivFactor * derivFactor
  303. );
  304. return ret;
  305. }
  306. }
  307. }