BSDynamics.cs 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800
  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. * The quotations from http://wiki.secondlife.com/wiki/Linden_Vehicle_Tutorial
  28. * are Copyright (c) 2009 Linden Research, Inc and are used under their license
  29. * of Creative Commons Attribution-Share Alike 3.0
  30. * (http://creativecommons.org/licenses/by-sa/3.0/).
  31. */
  32. using System;
  33. using System.Collections.Generic;
  34. using System.Reflection;
  35. using System.Runtime.InteropServices;
  36. using OpenMetaverse;
  37. using OpenSim.Framework;
  38. using OpenSim.Region.Physics.Manager;
  39. namespace OpenSim.Region.Physics.BulletSPlugin
  40. {
  41. public sealed class BSDynamics : BSActor
  42. {
  43. #pragma warning disable 414
  44. private static string LogHeader = "[BULLETSIM VEHICLE]";
  45. #pragma warning restore 414
  46. // the prim this dynamic controller belongs to
  47. private BSPrimLinkable ControllingPrim { get; set; }
  48. private bool m_haveRegisteredForSceneEvents;
  49. // mass of the vehicle fetched each time we're calles
  50. private float m_vehicleMass;
  51. // Vehicle properties
  52. public Vehicle Type { get; set; }
  53. // private Quaternion m_referenceFrame = Quaternion.Identity; // Axis modifier
  54. private VehicleFlag m_flags = (VehicleFlag) 0; // Boolean settings:
  55. // HOVER_TERRAIN_ONLY
  56. // HOVER_GLOBAL_HEIGHT
  57. // NO_DEFLECTION_UP
  58. // HOVER_WATER_ONLY
  59. // HOVER_UP_ONLY
  60. // LIMIT_MOTOR_UP
  61. // LIMIT_ROLL_ONLY
  62. private Vector3 m_BlockingEndPoint = Vector3.Zero;
  63. private Quaternion m_RollreferenceFrame = Quaternion.Identity;
  64. private Quaternion m_referenceFrame = Quaternion.Identity;
  65. // Linear properties
  66. private BSVMotor m_linearMotor = new BSVMotor("LinearMotor");
  67. private Vector3 m_linearMotorDirection = Vector3.Zero; // velocity requested by LSL, decayed by time
  68. private Vector3 m_linearMotorOffset = Vector3.Zero; // the point of force can be offset from the center
  69. private Vector3 m_linearMotorDirectionLASTSET = Vector3.Zero; // velocity requested by LSL
  70. private Vector3 m_linearFrictionTimescale = Vector3.Zero;
  71. private float m_linearMotorDecayTimescale = 1;
  72. private float m_linearMotorTimescale = 1;
  73. private Vector3 m_lastLinearVelocityVector = Vector3.Zero;
  74. private Vector3 m_lastPositionVector = Vector3.Zero;
  75. // private bool m_LinearMotorSetLastFrame = false;
  76. // private Vector3 m_linearMotorOffset = Vector3.Zero;
  77. //Angular properties
  78. private BSVMotor m_angularMotor = new BSVMotor("AngularMotor");
  79. private Vector3 m_angularMotorDirection = Vector3.Zero; // angular velocity requested by LSL motor
  80. // private int m_angularMotorApply = 0; // application frame counter
  81. private Vector3 m_angularMotorVelocity = Vector3.Zero; // current angular motor velocity
  82. private float m_angularMotorTimescale = 1; // motor angular velocity ramp up rate
  83. private float m_angularMotorDecayTimescale = 1; // motor angular velocity decay rate
  84. private Vector3 m_angularFrictionTimescale = Vector3.Zero; // body angular velocity decay rate
  85. private Vector3 m_lastAngularVelocity = Vector3.Zero;
  86. private Vector3 m_lastVertAttractor = Vector3.Zero; // what VA was last applied to body
  87. //Deflection properties
  88. private BSVMotor m_angularDeflectionMotor = new BSVMotor("AngularDeflection");
  89. private float m_angularDeflectionEfficiency = 0;
  90. private float m_angularDeflectionTimescale = 0;
  91. private float m_linearDeflectionEfficiency = 0;
  92. private float m_linearDeflectionTimescale = 0;
  93. //Banking properties
  94. private float m_bankingEfficiency = 0;
  95. private float m_bankingMix = 1;
  96. private float m_bankingTimescale = 0;
  97. //Hover and Buoyancy properties
  98. private BSVMotor m_hoverMotor = new BSVMotor("Hover");
  99. private float m_VhoverHeight = 0f;
  100. private float m_VhoverEfficiency = 0f;
  101. private float m_VhoverTimescale = 0f;
  102. private float m_VhoverTargetHeight = -1.0f; // if <0 then no hover, else its the current target height
  103. // Modifies gravity. Slider between -1 (double-gravity) and 1 (full anti-gravity)
  104. private float m_VehicleBuoyancy = 0f;
  105. private Vector3 m_VehicleGravity = Vector3.Zero; // Gravity computed when buoyancy set
  106. //Attractor properties
  107. private BSVMotor m_verticalAttractionMotor = new BSVMotor("VerticalAttraction");
  108. private float m_verticalAttractionEfficiency = 1.0f; // damped
  109. private float m_verticalAttractionCutoff = 500f; // per the documentation
  110. // Timescale > cutoff means no vert attractor.
  111. private float m_verticalAttractionTimescale = 510f;
  112. // Just some recomputed constants:
  113. #pragma warning disable 414
  114. static readonly float TwoPI = ((float)Math.PI) * 2f;
  115. static readonly float FourPI = ((float)Math.PI) * 4f;
  116. static readonly float PIOverFour = ((float)Math.PI) / 4f;
  117. static readonly float PIOverTwo = ((float)Math.PI) / 2f;
  118. #pragma warning restore 414
  119. public BSDynamics(BSScene myScene, BSPrim myPrim, string actorName)
  120. : base(myScene, myPrim, actorName)
  121. {
  122. Type = Vehicle.TYPE_NONE;
  123. m_haveRegisteredForSceneEvents = false;
  124. ControllingPrim = myPrim as BSPrimLinkable;
  125. if (ControllingPrim == null)
  126. {
  127. // THIS CANNOT HAPPEN!!
  128. }
  129. VDetailLog("{0},Creation", ControllingPrim.LocalID);
  130. }
  131. // Return 'true' if this vehicle is doing vehicle things
  132. public bool IsActive
  133. {
  134. get { return (Type != Vehicle.TYPE_NONE && ControllingPrim.IsPhysicallyActive); }
  135. }
  136. // Return 'true' if this a vehicle that should be sitting on the ground
  137. public bool IsGroundVehicle
  138. {
  139. get { return (Type == Vehicle.TYPE_CAR || Type == Vehicle.TYPE_SLED); }
  140. }
  141. #region Vehicle parameter setting
  142. public void ProcessFloatVehicleParam(Vehicle pParam, float pValue)
  143. {
  144. VDetailLog("{0},ProcessFloatVehicleParam,param={1},val={2}", ControllingPrim.LocalID, pParam, pValue);
  145. float clampTemp;
  146. switch (pParam)
  147. {
  148. case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY:
  149. m_angularDeflectionEfficiency = ClampInRange(0f, pValue, 1f);
  150. break;
  151. case Vehicle.ANGULAR_DEFLECTION_TIMESCALE:
  152. m_angularDeflectionTimescale = ClampInRange(0.25f, pValue, 120);
  153. break;
  154. case Vehicle.ANGULAR_MOTOR_DECAY_TIMESCALE:
  155. m_angularMotorDecayTimescale = ClampInRange(0.25f, pValue, 120);
  156. m_angularMotor.TargetValueDecayTimeScale = m_angularMotorDecayTimescale;
  157. break;
  158. case Vehicle.ANGULAR_MOTOR_TIMESCALE:
  159. m_angularMotorTimescale = ClampInRange(0.25f, pValue, 120);
  160. m_angularMotor.TimeScale = m_angularMotorTimescale;
  161. break;
  162. case Vehicle.BANKING_EFFICIENCY:
  163. m_bankingEfficiency = ClampInRange(-1f, pValue, 1f);
  164. break;
  165. case Vehicle.BANKING_MIX:
  166. m_bankingMix = ClampInRange(0.01f, pValue, 1);
  167. break;
  168. case Vehicle.BANKING_TIMESCALE:
  169. m_bankingTimescale = ClampInRange(0.25f, pValue, 120);
  170. break;
  171. case Vehicle.BUOYANCY:
  172. m_VehicleBuoyancy = ClampInRange(-1f, pValue, 1f);
  173. m_VehicleGravity = ControllingPrim.ComputeGravity(m_VehicleBuoyancy);
  174. break;
  175. case Vehicle.HOVER_EFFICIENCY:
  176. m_VhoverEfficiency = ClampInRange(0.01f, pValue, 1f);
  177. break;
  178. case Vehicle.HOVER_HEIGHT:
  179. m_VhoverHeight = ClampInRange(0f, pValue, 1000000f);
  180. break;
  181. case Vehicle.HOVER_TIMESCALE:
  182. m_VhoverTimescale = ClampInRange(0.01f, pValue, 120);
  183. break;
  184. case Vehicle.LINEAR_DEFLECTION_EFFICIENCY:
  185. m_linearDeflectionEfficiency = ClampInRange(0f, pValue, 1f);
  186. break;
  187. case Vehicle.LINEAR_DEFLECTION_TIMESCALE:
  188. m_linearDeflectionTimescale = ClampInRange(0.01f, pValue, 120);
  189. break;
  190. case Vehicle.LINEAR_MOTOR_DECAY_TIMESCALE:
  191. m_linearMotorDecayTimescale = ClampInRange(0.01f, pValue, 120);
  192. m_linearMotor.TargetValueDecayTimeScale = m_linearMotorDecayTimescale;
  193. break;
  194. case Vehicle.LINEAR_MOTOR_TIMESCALE:
  195. m_linearMotorTimescale = ClampInRange(0.01f, pValue, 120);
  196. m_linearMotor.TimeScale = m_linearMotorTimescale;
  197. break;
  198. case Vehicle.VERTICAL_ATTRACTION_EFFICIENCY:
  199. m_verticalAttractionEfficiency = ClampInRange(0.1f, pValue, 1f);
  200. m_verticalAttractionMotor.Efficiency = m_verticalAttractionEfficiency;
  201. break;
  202. case Vehicle.VERTICAL_ATTRACTION_TIMESCALE:
  203. m_verticalAttractionTimescale = ClampInRange(0.01f, pValue, 120);
  204. m_verticalAttractionMotor.TimeScale = m_verticalAttractionTimescale;
  205. break;
  206. // These are vector properties but the engine lets you use a single float value to
  207. // set all of the components to the same value
  208. case Vehicle.ANGULAR_FRICTION_TIMESCALE:
  209. clampTemp = ClampInRange(0.01f, pValue, 120);
  210. m_angularFrictionTimescale = new Vector3(clampTemp, clampTemp, clampTemp);
  211. break;
  212. case Vehicle.ANGULAR_MOTOR_DIRECTION:
  213. clampTemp = ClampInRange(-TwoPI, pValue, TwoPI);
  214. m_angularMotorDirection = new Vector3(clampTemp, clampTemp, clampTemp);
  215. m_angularMotor.Zero();
  216. m_angularMotor.SetTarget(m_angularMotorDirection);
  217. break;
  218. case Vehicle.LINEAR_FRICTION_TIMESCALE:
  219. clampTemp = ClampInRange(0.01f, pValue, 120);
  220. m_linearFrictionTimescale = new Vector3(clampTemp, clampTemp, clampTemp);
  221. break;
  222. case Vehicle.LINEAR_MOTOR_DIRECTION:
  223. clampTemp = ClampInRange(-BSParam.MaxLinearVelocity, pValue, BSParam.MaxLinearVelocity);
  224. m_linearMotorDirection = new Vector3(clampTemp, clampTemp, clampTemp);
  225. m_linearMotorDirectionLASTSET = new Vector3(clampTemp, clampTemp, clampTemp);
  226. m_linearMotor.SetTarget(m_linearMotorDirection);
  227. break;
  228. case Vehicle.LINEAR_MOTOR_OFFSET:
  229. clampTemp = ClampInRange(-1000, pValue, 1000);
  230. m_linearMotorOffset = new Vector3(clampTemp, clampTemp, clampTemp);
  231. break;
  232. }
  233. }//end ProcessFloatVehicleParam
  234. internal void ProcessVectorVehicleParam(Vehicle pParam, Vector3 pValue)
  235. {
  236. VDetailLog("{0},ProcessVectorVehicleParam,param={1},val={2}", ControllingPrim.LocalID, pParam, pValue);
  237. switch (pParam)
  238. {
  239. case Vehicle.ANGULAR_FRICTION_TIMESCALE:
  240. pValue.X = ClampInRange(0.25f, pValue.X, 120);
  241. pValue.Y = ClampInRange(0.25f, pValue.Y, 120);
  242. pValue.Z = ClampInRange(0.25f, pValue.Z, 120);
  243. m_angularFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
  244. break;
  245. case Vehicle.ANGULAR_MOTOR_DIRECTION:
  246. // Limit requested angular speed to 2 rps= 4 pi rads/sec
  247. pValue.X = ClampInRange(-FourPI, pValue.X, FourPI);
  248. pValue.Y = ClampInRange(-FourPI, pValue.Y, FourPI);
  249. pValue.Z = ClampInRange(-FourPI, pValue.Z, FourPI);
  250. m_angularMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
  251. m_angularMotor.Zero();
  252. m_angularMotor.SetTarget(m_angularMotorDirection);
  253. break;
  254. case Vehicle.LINEAR_FRICTION_TIMESCALE:
  255. pValue.X = ClampInRange(0.25f, pValue.X, 120);
  256. pValue.Y = ClampInRange(0.25f, pValue.Y, 120);
  257. pValue.Z = ClampInRange(0.25f, pValue.Z, 120);
  258. m_linearFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
  259. break;
  260. case Vehicle.LINEAR_MOTOR_DIRECTION:
  261. pValue.X = ClampInRange(-BSParam.MaxLinearVelocity, pValue.X, BSParam.MaxLinearVelocity);
  262. pValue.Y = ClampInRange(-BSParam.MaxLinearVelocity, pValue.Y, BSParam.MaxLinearVelocity);
  263. pValue.Z = ClampInRange(-BSParam.MaxLinearVelocity, pValue.Z, BSParam.MaxLinearVelocity);
  264. m_linearMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
  265. m_linearMotorDirectionLASTSET = new Vector3(pValue.X, pValue.Y, pValue.Z);
  266. m_linearMotor.SetTarget(m_linearMotorDirection);
  267. break;
  268. case Vehicle.LINEAR_MOTOR_OFFSET:
  269. // Not sure the correct range to limit this variable
  270. pValue.X = ClampInRange(-1000, pValue.X, 1000);
  271. pValue.Y = ClampInRange(-1000, pValue.Y, 1000);
  272. pValue.Z = ClampInRange(-1000, pValue.Z, 1000);
  273. m_linearMotorOffset = new Vector3(pValue.X, pValue.Y, pValue.Z);
  274. break;
  275. case Vehicle.BLOCK_EXIT:
  276. // Not sure the correct range to limit this variable
  277. pValue.X = ClampInRange(-10000, pValue.X, 10000);
  278. pValue.Y = ClampInRange(-10000, pValue.Y, 10000);
  279. pValue.Z = ClampInRange(-10000, pValue.Z, 10000);
  280. m_BlockingEndPoint = new Vector3(pValue.X, pValue.Y, pValue.Z);
  281. break;
  282. }
  283. }//end ProcessVectorVehicleParam
  284. internal void ProcessRotationVehicleParam(Vehicle pParam, Quaternion pValue)
  285. {
  286. VDetailLog("{0},ProcessRotationalVehicleParam,param={1},val={2}", ControllingPrim.LocalID, pParam, pValue);
  287. switch (pParam)
  288. {
  289. case Vehicle.REFERENCE_FRAME:
  290. m_referenceFrame = pValue;
  291. break;
  292. case Vehicle.ROLL_FRAME:
  293. m_RollreferenceFrame = pValue;
  294. break;
  295. }
  296. }//end ProcessRotationVehicleParam
  297. internal void ProcessVehicleFlags(int pParam, bool remove)
  298. {
  299. VDetailLog("{0},ProcessVehicleFlags,param={1},remove={2}", ControllingPrim.LocalID, pParam, remove);
  300. VehicleFlag parm = (VehicleFlag)pParam;
  301. if (pParam == -1)
  302. m_flags = (VehicleFlag)0;
  303. else
  304. {
  305. if (remove)
  306. m_flags &= ~parm;
  307. else
  308. m_flags |= parm;
  309. }
  310. }
  311. public void ProcessTypeChange(Vehicle pType)
  312. {
  313. VDetailLog("{0},ProcessTypeChange,type={1}", ControllingPrim.LocalID, pType);
  314. // Set Defaults For Type
  315. Type = pType;
  316. switch (pType)
  317. {
  318. case Vehicle.TYPE_NONE:
  319. m_linearMotorDirection = Vector3.Zero;
  320. m_linearMotorTimescale = 0;
  321. m_linearMotorDecayTimescale = 0;
  322. m_linearFrictionTimescale = new Vector3(0, 0, 0);
  323. m_angularMotorDirection = Vector3.Zero;
  324. m_angularMotorDecayTimescale = 0;
  325. m_angularMotorTimescale = 0;
  326. m_angularFrictionTimescale = new Vector3(0, 0, 0);
  327. m_VhoverHeight = 0;
  328. m_VhoverEfficiency = 0;
  329. m_VhoverTimescale = 0;
  330. m_VehicleBuoyancy = 0;
  331. m_linearDeflectionEfficiency = 1;
  332. m_linearDeflectionTimescale = 1;
  333. m_angularDeflectionEfficiency = 0;
  334. m_angularDeflectionTimescale = 1000;
  335. m_verticalAttractionEfficiency = 0;
  336. m_verticalAttractionTimescale = 0;
  337. m_bankingEfficiency = 0;
  338. m_bankingTimescale = 1000;
  339. m_bankingMix = 1;
  340. m_referenceFrame = Quaternion.Identity;
  341. m_flags = (VehicleFlag)0;
  342. break;
  343. case Vehicle.TYPE_SLED:
  344. m_linearMotorDirection = Vector3.Zero;
  345. m_linearMotorTimescale = 1000;
  346. m_linearMotorDecayTimescale = 120;
  347. m_linearFrictionTimescale = new Vector3(30, 1, 1000);
  348. m_angularMotorDirection = Vector3.Zero;
  349. m_angularMotorTimescale = 1000;
  350. m_angularMotorDecayTimescale = 120;
  351. m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
  352. m_VhoverHeight = 0;
  353. m_VhoverEfficiency = 10; // TODO: this looks wrong!!
  354. m_VhoverTimescale = 10;
  355. m_VehicleBuoyancy = 0;
  356. m_linearDeflectionEfficiency = 1;
  357. m_linearDeflectionTimescale = 1;
  358. m_angularDeflectionEfficiency = 1;
  359. m_angularDeflectionTimescale = 1000;
  360. m_verticalAttractionEfficiency = 0;
  361. m_verticalAttractionTimescale = 0;
  362. m_bankingEfficiency = 0;
  363. m_bankingTimescale = 10;
  364. m_bankingMix = 1;
  365. m_referenceFrame = Quaternion.Identity;
  366. m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY
  367. | VehicleFlag.HOVER_TERRAIN_ONLY
  368. | VehicleFlag.HOVER_GLOBAL_HEIGHT
  369. | VehicleFlag.HOVER_UP_ONLY);
  370. m_flags |= (VehicleFlag.NO_DEFLECTION_UP
  371. | VehicleFlag.LIMIT_ROLL_ONLY
  372. | VehicleFlag.LIMIT_MOTOR_UP);
  373. break;
  374. case Vehicle.TYPE_CAR:
  375. m_linearMotorDirection = Vector3.Zero;
  376. m_linearMotorTimescale = 1;
  377. m_linearMotorDecayTimescale = 60;
  378. m_linearFrictionTimescale = new Vector3(100, 2, 1000);
  379. m_angularMotorDirection = Vector3.Zero;
  380. m_angularMotorTimescale = 1;
  381. m_angularMotorDecayTimescale = 0.8f;
  382. m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
  383. m_VhoverHeight = 0;
  384. m_VhoverEfficiency = 0;
  385. m_VhoverTimescale = 1000;
  386. m_VehicleBuoyancy = 0;
  387. m_linearDeflectionEfficiency = 1;
  388. m_linearDeflectionTimescale = 2;
  389. m_angularDeflectionEfficiency = 0;
  390. m_angularDeflectionTimescale = 10;
  391. m_verticalAttractionEfficiency = 1f;
  392. m_verticalAttractionTimescale = 10f;
  393. m_bankingEfficiency = -0.2f;
  394. m_bankingMix = 1;
  395. m_bankingTimescale = 1;
  396. m_referenceFrame = Quaternion.Identity;
  397. m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY
  398. | VehicleFlag.HOVER_TERRAIN_ONLY
  399. | VehicleFlag.HOVER_GLOBAL_HEIGHT);
  400. m_flags |= (VehicleFlag.NO_DEFLECTION_UP
  401. | VehicleFlag.LIMIT_ROLL_ONLY
  402. | VehicleFlag.LIMIT_MOTOR_UP
  403. | VehicleFlag.HOVER_UP_ONLY);
  404. break;
  405. case Vehicle.TYPE_BOAT:
  406. m_linearMotorDirection = Vector3.Zero;
  407. m_linearMotorTimescale = 5;
  408. m_linearMotorDecayTimescale = 60;
  409. m_linearFrictionTimescale = new Vector3(10, 3, 2);
  410. m_angularMotorDirection = Vector3.Zero;
  411. m_angularMotorTimescale = 4;
  412. m_angularMotorDecayTimescale = 4;
  413. m_angularFrictionTimescale = new Vector3(10,10,10);
  414. m_VhoverHeight = 0;
  415. m_VhoverEfficiency = 0.5f;
  416. m_VhoverTimescale = 2;
  417. m_VehicleBuoyancy = 1;
  418. m_linearDeflectionEfficiency = 0.5f;
  419. m_linearDeflectionTimescale = 3;
  420. m_angularDeflectionEfficiency = 0.5f;
  421. m_angularDeflectionTimescale = 5;
  422. m_verticalAttractionEfficiency = 0.5f;
  423. m_verticalAttractionTimescale = 5f;
  424. m_bankingEfficiency = -0.3f;
  425. m_bankingMix = 0.8f;
  426. m_bankingTimescale = 1;
  427. m_referenceFrame = Quaternion.Identity;
  428. m_flags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY
  429. | VehicleFlag.HOVER_GLOBAL_HEIGHT
  430. | VehicleFlag.LIMIT_ROLL_ONLY
  431. | VehicleFlag.HOVER_UP_ONLY);
  432. m_flags |= (VehicleFlag.NO_DEFLECTION_UP
  433. | VehicleFlag.LIMIT_MOTOR_UP
  434. | VehicleFlag.HOVER_WATER_ONLY);
  435. break;
  436. case Vehicle.TYPE_AIRPLANE:
  437. m_linearMotorDirection = Vector3.Zero;
  438. m_linearMotorTimescale = 2;
  439. m_linearMotorDecayTimescale = 60;
  440. m_linearFrictionTimescale = new Vector3(200, 10, 5);
  441. m_angularMotorDirection = Vector3.Zero;
  442. m_angularMotorTimescale = 4;
  443. m_angularMotorDecayTimescale = 4;
  444. m_angularFrictionTimescale = new Vector3(20, 20, 20);
  445. m_VhoverHeight = 0;
  446. m_VhoverEfficiency = 0.5f;
  447. m_VhoverTimescale = 1000;
  448. m_VehicleBuoyancy = 0;
  449. m_linearDeflectionEfficiency = 0.5f;
  450. m_linearDeflectionTimescale = 3;
  451. m_angularDeflectionEfficiency = 1;
  452. m_angularDeflectionTimescale = 2;
  453. m_verticalAttractionEfficiency = 0.9f;
  454. m_verticalAttractionTimescale = 2f;
  455. m_bankingEfficiency = 1;
  456. m_bankingMix = 0.7f;
  457. m_bankingTimescale = 2;
  458. m_referenceFrame = Quaternion.Identity;
  459. m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY
  460. | VehicleFlag.HOVER_TERRAIN_ONLY
  461. | VehicleFlag.HOVER_GLOBAL_HEIGHT
  462. | VehicleFlag.HOVER_UP_ONLY
  463. | VehicleFlag.NO_DEFLECTION_UP
  464. | VehicleFlag.LIMIT_MOTOR_UP);
  465. m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY);
  466. break;
  467. case Vehicle.TYPE_BALLOON:
  468. m_linearMotorDirection = Vector3.Zero;
  469. m_linearMotorTimescale = 5;
  470. m_linearFrictionTimescale = new Vector3(5, 5, 5);
  471. m_linearMotorDecayTimescale = 60;
  472. m_angularMotorDirection = Vector3.Zero;
  473. m_angularMotorTimescale = 6;
  474. m_angularFrictionTimescale = new Vector3(10, 10, 10);
  475. m_angularMotorDecayTimescale = 10;
  476. m_VhoverHeight = 5;
  477. m_VhoverEfficiency = 0.8f;
  478. m_VhoverTimescale = 10;
  479. m_VehicleBuoyancy = 1;
  480. m_linearDeflectionEfficiency = 0;
  481. m_linearDeflectionTimescale = 5;
  482. m_angularDeflectionEfficiency = 0;
  483. m_angularDeflectionTimescale = 5;
  484. m_verticalAttractionEfficiency = 1f;
  485. m_verticalAttractionTimescale = 100f;
  486. m_bankingEfficiency = 0;
  487. m_bankingMix = 0.7f;
  488. m_bankingTimescale = 5;
  489. m_referenceFrame = Quaternion.Identity;
  490. m_referenceFrame = Quaternion.Identity;
  491. m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY
  492. | VehicleFlag.HOVER_TERRAIN_ONLY
  493. | VehicleFlag.HOVER_UP_ONLY
  494. | VehicleFlag.NO_DEFLECTION_UP
  495. | VehicleFlag.LIMIT_MOTOR_UP);
  496. m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY
  497. | VehicleFlag.HOVER_GLOBAL_HEIGHT);
  498. break;
  499. }
  500. m_linearMotor = new BSVMotor("LinearMotor", m_linearMotorTimescale, m_linearMotorDecayTimescale, 1f);
  501. // m_linearMotor.PhysicsScene = m_physicsScene; // DEBUG DEBUG DEBUG (enables detail logging)
  502. m_angularMotor = new BSVMotor("AngularMotor", m_angularMotorTimescale, m_angularMotorDecayTimescale, 1f);
  503. // m_angularMotor.PhysicsScene = m_physicsScene; // DEBUG DEBUG DEBUG (enables detail logging)
  504. /* Not implemented
  505. m_verticalAttractionMotor = new BSVMotor("VerticalAttraction", m_verticalAttractionTimescale,
  506. BSMotor.Infinite, BSMotor.InfiniteVector,
  507. m_verticalAttractionEfficiency);
  508. // Z goes away and we keep X and Y
  509. m_verticalAttractionMotor.PhysicsScene = PhysicsScene; // DEBUG DEBUG DEBUG (enables detail logging)
  510. */
  511. if (this.Type == Vehicle.TYPE_NONE)
  512. {
  513. UnregisterForSceneEvents();
  514. }
  515. else
  516. {
  517. RegisterForSceneEvents();
  518. }
  519. // Update any physical parameters based on this type.
  520. Refresh();
  521. }
  522. #endregion // Vehicle parameter setting
  523. // BSActor.Refresh()
  524. public override void Refresh()
  525. {
  526. // If asking for a refresh, reset the physical parameters before the next simulation step.
  527. // Called whether active or not since the active state may be updated before the next step.
  528. m_physicsScene.PostTaintObject("BSDynamics.Refresh", ControllingPrim.LocalID, delegate()
  529. {
  530. SetPhysicalParameters();
  531. });
  532. }
  533. // Some of the properties of this prim may have changed.
  534. // Do any updating needed for a vehicle
  535. private void SetPhysicalParameters()
  536. {
  537. if (IsActive)
  538. {
  539. // Remember the mass so we don't have to fetch it every step
  540. m_vehicleMass = ControllingPrim.TotalMass;
  541. // Friction affects are handled by this vehicle code
  542. // m_physicsScene.PE.SetFriction(ControllingPrim.PhysBody, BSParam.VehicleFriction);
  543. // m_physicsScene.PE.SetRestitution(ControllingPrim.PhysBody, BSParam.VehicleRestitution);
  544. ControllingPrim.Linkset.SetPhysicalFriction(BSParam.VehicleFriction);
  545. ControllingPrim.Linkset.SetPhysicalRestitution(BSParam.VehicleRestitution);
  546. // Moderate angular movement introduced by Bullet.
  547. // TODO: possibly set AngularFactor and LinearFactor for the type of vehicle.
  548. // Maybe compute linear and angular factor and damping from params.
  549. m_physicsScene.PE.SetAngularDamping(ControllingPrim.PhysBody, BSParam.VehicleAngularDamping);
  550. m_physicsScene.PE.SetLinearFactor(ControllingPrim.PhysBody, BSParam.VehicleLinearFactor);
  551. m_physicsScene.PE.SetAngularFactorV(ControllingPrim.PhysBody, BSParam.VehicleAngularFactor);
  552. // Vehicles report collision events so we know when it's on the ground
  553. // m_physicsScene.PE.AddToCollisionFlags(ControllingPrim.PhysBody, CollisionFlags.BS_VEHICLE_COLLISIONS);
  554. ControllingPrim.Linkset.AddToPhysicalCollisionFlags(CollisionFlags.BS_VEHICLE_COLLISIONS);
  555. // Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(ControllingPrim.PhysShape.physShapeInfo, m_vehicleMass);
  556. // ControllingPrim.Inertia = inertia * BSParam.VehicleInertiaFactor;
  557. // m_physicsScene.PE.SetMassProps(ControllingPrim.PhysBody, m_vehicleMass, ControllingPrim.Inertia);
  558. // m_physicsScene.PE.UpdateInertiaTensor(ControllingPrim.PhysBody);
  559. ControllingPrim.Linkset.ComputeAndSetLocalInertia(BSParam.VehicleInertiaFactor, m_vehicleMass);
  560. // Set the gravity for the vehicle depending on the buoyancy
  561. // TODO: what should be done if prim and vehicle buoyancy differ?
  562. m_VehicleGravity = ControllingPrim.ComputeGravity(m_VehicleBuoyancy);
  563. // The actual vehicle gravity is set to zero in Bullet so we can do all the application of same.
  564. // m_physicsScene.PE.SetGravity(ControllingPrim.PhysBody, Vector3.Zero);
  565. ControllingPrim.Linkset.SetPhysicalGravity(Vector3.Zero);
  566. VDetailLog("{0},BSDynamics.SetPhysicalParameters,mass={1},inert={2},vehGrav={3},aDamp={4},frict={5},rest={6},lFact={7},aFact={8}",
  567. ControllingPrim.LocalID, m_vehicleMass, ControllingPrim.Inertia, m_VehicleGravity,
  568. BSParam.VehicleAngularDamping, BSParam.VehicleFriction, BSParam.VehicleRestitution,
  569. BSParam.VehicleLinearFactor, BSParam.VehicleAngularFactor
  570. );
  571. }
  572. else
  573. {
  574. if (ControllingPrim.PhysBody.HasPhysicalBody)
  575. m_physicsScene.PE.RemoveFromCollisionFlags(ControllingPrim.PhysBody, CollisionFlags.BS_VEHICLE_COLLISIONS);
  576. // ControllingPrim.Linkset.RemoveFromPhysicalCollisionFlags(CollisionFlags.BS_VEHICLE_COLLISIONS);
  577. }
  578. }
  579. // BSActor.RemoveBodyDependencies
  580. public override void RemoveDependencies()
  581. {
  582. Refresh();
  583. }
  584. // BSActor.Release()
  585. public override void Dispose()
  586. {
  587. VDetailLog("{0},Dispose", ControllingPrim.LocalID);
  588. UnregisterForSceneEvents();
  589. Type = Vehicle.TYPE_NONE;
  590. Enabled = false;
  591. return;
  592. }
  593. private void RegisterForSceneEvents()
  594. {
  595. if (!m_haveRegisteredForSceneEvents)
  596. {
  597. m_physicsScene.BeforeStep += this.Step;
  598. m_physicsScene.AfterStep += this.PostStep;
  599. ControllingPrim.OnPreUpdateProperty += this.PreUpdateProperty;
  600. m_haveRegisteredForSceneEvents = true;
  601. }
  602. }
  603. private void UnregisterForSceneEvents()
  604. {
  605. if (m_haveRegisteredForSceneEvents)
  606. {
  607. m_physicsScene.BeforeStep -= this.Step;
  608. m_physicsScene.AfterStep -= this.PostStep;
  609. ControllingPrim.OnPreUpdateProperty -= this.PreUpdateProperty;
  610. m_haveRegisteredForSceneEvents = false;
  611. }
  612. }
  613. private void PreUpdateProperty(ref EntityProperties entprop)
  614. {
  615. // A temporary kludge to suppress the rotational effects introduced on vehicles by Bullet
  616. // TODO: handle physics introduced by Bullet with computed vehicle physics.
  617. if (IsActive)
  618. {
  619. entprop.RotationalVelocity = Vector3.Zero;
  620. }
  621. }
  622. #region Known vehicle value functions
  623. // Vehicle physical parameters that we buffer from constant getting and setting.
  624. // The "m_known*" values are unknown until they are fetched and the m_knownHas flag is set.
  625. // Changing is remembered and the parameter is stored back into the physics engine only if updated.
  626. // This does two things: 1) saves continuious calls into unmanaged code, and
  627. // 2) signals when a physics property update must happen back to the simulator
  628. // to update values modified for the vehicle.
  629. private int m_knownChanged;
  630. private int m_knownHas;
  631. private float m_knownTerrainHeight;
  632. private float m_knownWaterLevel;
  633. private Vector3 m_knownPosition;
  634. private Vector3 m_knownVelocity;
  635. private Vector3 m_knownForce;
  636. private Vector3 m_knownForceImpulse;
  637. private Quaternion m_knownOrientation;
  638. private Vector3 m_knownRotationalVelocity;
  639. private Vector3 m_knownRotationalForce;
  640. private Vector3 m_knownRotationalImpulse;
  641. private const int m_knownChangedPosition = 1 << 0;
  642. private const int m_knownChangedVelocity = 1 << 1;
  643. private const int m_knownChangedForce = 1 << 2;
  644. private const int m_knownChangedForceImpulse = 1 << 3;
  645. private const int m_knownChangedOrientation = 1 << 4;
  646. private const int m_knownChangedRotationalVelocity = 1 << 5;
  647. private const int m_knownChangedRotationalForce = 1 << 6;
  648. private const int m_knownChangedRotationalImpulse = 1 << 7;
  649. private const int m_knownChangedTerrainHeight = 1 << 8;
  650. private const int m_knownChangedWaterLevel = 1 << 9;
  651. public void ForgetKnownVehicleProperties()
  652. {
  653. m_knownHas = 0;
  654. m_knownChanged = 0;
  655. }
  656. // Push all the changed values back into the physics engine
  657. public void PushKnownChanged()
  658. {
  659. if (m_knownChanged != 0)
  660. {
  661. if ((m_knownChanged & m_knownChangedPosition) != 0)
  662. ControllingPrim.ForcePosition = m_knownPosition;
  663. if ((m_knownChanged & m_knownChangedOrientation) != 0)
  664. ControllingPrim.ForceOrientation = m_knownOrientation;
  665. if ((m_knownChanged & m_knownChangedVelocity) != 0)
  666. {
  667. ControllingPrim.ForceVelocity = m_knownVelocity;
  668. // Fake out Bullet by making it think the velocity is the same as last time.
  669. // Bullet does a bunch of smoothing for changing parameters.
  670. // Since the vehicle is demanding this setting, we override Bullet's smoothing
  671. // by telling Bullet the value was the same last time.
  672. // PhysicsScene.PE.SetInterpolationLinearVelocity(Prim.PhysBody, m_knownVelocity);
  673. }
  674. if ((m_knownChanged & m_knownChangedForce) != 0)
  675. ControllingPrim.AddForce((Vector3)m_knownForce, false /*pushForce*/, true /*inTaintTime*/);
  676. if ((m_knownChanged & m_knownChangedForceImpulse) != 0)
  677. ControllingPrim.AddForceImpulse((Vector3)m_knownForceImpulse, false /*pushforce*/, true /*inTaintTime*/);
  678. if ((m_knownChanged & m_knownChangedRotationalVelocity) != 0)
  679. {
  680. ControllingPrim.ForceRotationalVelocity = m_knownRotationalVelocity;
  681. // PhysicsScene.PE.SetInterpolationAngularVelocity(Prim.PhysBody, m_knownRotationalVelocity);
  682. }
  683. if ((m_knownChanged & m_knownChangedRotationalImpulse) != 0)
  684. ControllingPrim.ApplyTorqueImpulse((Vector3)m_knownRotationalImpulse, true /*inTaintTime*/);
  685. if ((m_knownChanged & m_knownChangedRotationalForce) != 0)
  686. {
  687. ControllingPrim.AddAngularForce((Vector3)m_knownRotationalForce, false /*pushForce*/, true /*inTaintTime*/);
  688. }
  689. // If we set one of the values (ie, the physics engine didn't do it) we must force
  690. // an UpdateProperties event to send the changes up to the simulator.
  691. m_physicsScene.PE.PushUpdate(ControllingPrim.PhysBody);
  692. }
  693. m_knownChanged = 0;
  694. }
  695. // Since the computation of terrain height can be a little involved, this routine
  696. // is used to fetch the height only once for each vehicle simulation step.
  697. Vector3 lastRememberedHeightPos = new Vector3(-1, -1, -1);
  698. private float GetTerrainHeight(Vector3 pos)
  699. {
  700. if ((m_knownHas & m_knownChangedTerrainHeight) == 0 || pos != lastRememberedHeightPos)
  701. {
  702. lastRememberedHeightPos = pos;
  703. m_knownTerrainHeight = ControllingPrim.PhysScene.TerrainManager.GetTerrainHeightAtXYZ(pos);
  704. m_knownHas |= m_knownChangedTerrainHeight;
  705. }
  706. return m_knownTerrainHeight;
  707. }
  708. // Since the computation of water level can be a little involved, this routine
  709. // is used ot fetch the level only once for each vehicle simulation step.
  710. Vector3 lastRememberedWaterHeightPos = new Vector3(-1, -1, -1);
  711. private float GetWaterLevel(Vector3 pos)
  712. {
  713. if ((m_knownHas & m_knownChangedWaterLevel) == 0 || pos != lastRememberedWaterHeightPos)
  714. {
  715. lastRememberedWaterHeightPos = pos;
  716. m_knownWaterLevel = ControllingPrim.PhysScene.TerrainManager.GetWaterLevelAtXYZ(pos);
  717. m_knownHas |= m_knownChangedWaterLevel;
  718. }
  719. return m_knownWaterLevel;
  720. }
  721. private Vector3 VehiclePosition
  722. {
  723. get
  724. {
  725. if ((m_knownHas & m_knownChangedPosition) == 0)
  726. {
  727. m_knownPosition = ControllingPrim.ForcePosition;
  728. m_knownHas |= m_knownChangedPosition;
  729. }
  730. return m_knownPosition;
  731. }
  732. set
  733. {
  734. m_knownPosition = value;
  735. m_knownChanged |= m_knownChangedPosition;
  736. m_knownHas |= m_knownChangedPosition;
  737. }
  738. }
  739. private Quaternion VehicleOrientation
  740. {
  741. get
  742. {
  743. if ((m_knownHas & m_knownChangedOrientation) == 0)
  744. {
  745. m_knownOrientation = ControllingPrim.ForceOrientation;
  746. m_knownHas |= m_knownChangedOrientation;
  747. }
  748. return m_knownOrientation;
  749. }
  750. set
  751. {
  752. m_knownOrientation = value;
  753. m_knownChanged |= m_knownChangedOrientation;
  754. m_knownHas |= m_knownChangedOrientation;
  755. }
  756. }
  757. private Vector3 VehicleVelocity
  758. {
  759. get
  760. {
  761. if ((m_knownHas & m_knownChangedVelocity) == 0)
  762. {
  763. m_knownVelocity = ControllingPrim.ForceVelocity;
  764. m_knownHas |= m_knownChangedVelocity;
  765. }
  766. return m_knownVelocity;
  767. }
  768. set
  769. {
  770. m_knownVelocity = value;
  771. m_knownChanged |= m_knownChangedVelocity;
  772. m_knownHas |= m_knownChangedVelocity;
  773. }
  774. }
  775. private void VehicleAddForce(Vector3 pForce)
  776. {
  777. if ((m_knownHas & m_knownChangedForce) == 0)
  778. {
  779. m_knownForce = Vector3.Zero;
  780. m_knownHas |= m_knownChangedForce;
  781. }
  782. m_knownForce += pForce;
  783. m_knownChanged |= m_knownChangedForce;
  784. }
  785. private void VehicleAddForceImpulse(Vector3 pImpulse)
  786. {
  787. if ((m_knownHas & m_knownChangedForceImpulse) == 0)
  788. {
  789. m_knownForceImpulse = Vector3.Zero;
  790. m_knownHas |= m_knownChangedForceImpulse;
  791. }
  792. m_knownForceImpulse += pImpulse;
  793. m_knownChanged |= m_knownChangedForceImpulse;
  794. }
  795. private Vector3 VehicleRotationalVelocity
  796. {
  797. get
  798. {
  799. if ((m_knownHas & m_knownChangedRotationalVelocity) == 0)
  800. {
  801. m_knownRotationalVelocity = ControllingPrim.ForceRotationalVelocity;
  802. m_knownHas |= m_knownChangedRotationalVelocity;
  803. }
  804. return (Vector3)m_knownRotationalVelocity;
  805. }
  806. set
  807. {
  808. m_knownRotationalVelocity = value;
  809. m_knownChanged |= m_knownChangedRotationalVelocity;
  810. m_knownHas |= m_knownChangedRotationalVelocity;
  811. }
  812. }
  813. private void VehicleAddAngularForce(Vector3 aForce)
  814. {
  815. if ((m_knownHas & m_knownChangedRotationalForce) == 0)
  816. {
  817. m_knownRotationalForce = Vector3.Zero;
  818. }
  819. m_knownRotationalForce += aForce;
  820. m_knownChanged |= m_knownChangedRotationalForce;
  821. m_knownHas |= m_knownChangedRotationalForce;
  822. }
  823. private void VehicleAddRotationalImpulse(Vector3 pImpulse)
  824. {
  825. if ((m_knownHas & m_knownChangedRotationalImpulse) == 0)
  826. {
  827. m_knownRotationalImpulse = Vector3.Zero;
  828. m_knownHas |= m_knownChangedRotationalImpulse;
  829. }
  830. m_knownRotationalImpulse += pImpulse;
  831. m_knownChanged |= m_knownChangedRotationalImpulse;
  832. }
  833. // Vehicle relative forward velocity
  834. private Vector3 VehicleForwardVelocity
  835. {
  836. get
  837. {
  838. return VehicleVelocity * Quaternion.Inverse(Quaternion.Normalize(VehicleFrameOrientation));
  839. }
  840. }
  841. private float VehicleForwardSpeed
  842. {
  843. get
  844. {
  845. return VehicleForwardVelocity.X;
  846. }
  847. }
  848. private Quaternion VehicleFrameOrientation
  849. {
  850. get
  851. {
  852. return VehicleOrientation * m_referenceFrame;
  853. }
  854. }
  855. #endregion // Known vehicle value functions
  856. // One step of the vehicle properties for the next 'pTimestep' seconds.
  857. internal void Step(float pTimestep)
  858. {
  859. if (!IsActive) return;
  860. ForgetKnownVehicleProperties();
  861. MoveLinear(pTimestep);
  862. MoveAngular(pTimestep);
  863. LimitRotation(pTimestep);
  864. // remember the position so next step we can limit absolute movement effects
  865. m_lastPositionVector = VehiclePosition;
  866. // If we forced the changing of some vehicle parameters, update the values and
  867. // for the physics engine to note the changes so an UpdateProperties event will happen.
  868. PushKnownChanged();
  869. if (m_physicsScene.VehiclePhysicalLoggingEnabled)
  870. m_physicsScene.PE.DumpRigidBody(m_physicsScene.World, ControllingPrim.PhysBody);
  871. VDetailLog("{0},BSDynamics.Step,done,pos={1}, force={2},velocity={3},angvel={4}",
  872. ControllingPrim.LocalID, VehiclePosition, m_knownForce, VehicleVelocity, VehicleRotationalVelocity);
  873. }
  874. // Called after the simulation step
  875. internal void PostStep(float pTimestep)
  876. {
  877. if (!IsActive) return;
  878. if (m_physicsScene.VehiclePhysicalLoggingEnabled)
  879. m_physicsScene.PE.DumpRigidBody(m_physicsScene.World, ControllingPrim.PhysBody);
  880. }
  881. // Apply the effect of the linear motor and other linear motions (like hover and float).
  882. private void MoveLinear(float pTimestep)
  883. {
  884. ComputeLinearVelocity(pTimestep);
  885. ComputeLinearDeflection(pTimestep);
  886. ComputeLinearTerrainHeightCorrection(pTimestep);
  887. ComputeLinearHover(pTimestep);
  888. ComputeLinearBlockingEndPoint(pTimestep);
  889. ComputeLinearMotorUp(pTimestep);
  890. ApplyGravity(pTimestep);
  891. // If not changing some axis, reduce out velocity
  892. if ((m_flags & (VehicleFlag.NO_X | VehicleFlag.NO_Y | VehicleFlag.NO_Z)) != 0)
  893. {
  894. Vector3 vel = VehicleVelocity;
  895. if ((m_flags & (VehicleFlag.NO_X)) != 0)
  896. {
  897. vel.X = 0;
  898. }
  899. if ((m_flags & (VehicleFlag.NO_Y)) != 0)
  900. {
  901. vel.Y = 0;
  902. }
  903. if ((m_flags & (VehicleFlag.NO_Z)) != 0)
  904. {
  905. vel.Z = 0;
  906. }
  907. VehicleVelocity = vel;
  908. }
  909. // ==================================================================
  910. // Clamp high or low velocities
  911. float newVelocityLengthSq = VehicleVelocity.LengthSquared();
  912. if (newVelocityLengthSq > BSParam.VehicleMaxLinearVelocitySquared)
  913. {
  914. Vector3 origVelW = VehicleVelocity; // DEBUG DEBUG
  915. VehicleVelocity /= VehicleVelocity.Length();
  916. VehicleVelocity *= BSParam.VehicleMaxLinearVelocity;
  917. VDetailLog("{0}, MoveLinear,clampMax,origVelW={1},lenSq={2},maxVelSq={3},,newVelW={4}",
  918. ControllingPrim.LocalID, origVelW, newVelocityLengthSq, BSParam.VehicleMaxLinearVelocitySquared, VehicleVelocity);
  919. }
  920. else if (newVelocityLengthSq < BSParam.VehicleMinLinearVelocitySquared)
  921. {
  922. Vector3 origVelW = VehicleVelocity; // DEBUG DEBUG
  923. VDetailLog("{0}, MoveLinear,clampMin,origVelW={1},lenSq={2}",
  924. ControllingPrim.LocalID, origVelW, newVelocityLengthSq);
  925. VehicleVelocity = Vector3.Zero;
  926. }
  927. VDetailLog("{0}, MoveLinear,done,isColl={1},newVel={2}", ControllingPrim.LocalID, ControllingPrim.HasSomeCollision, VehicleVelocity );
  928. } // end MoveLinear()
  929. public void ComputeLinearVelocity(float pTimestep)
  930. {
  931. // Step the motor from the current value. Get the correction needed this step.
  932. Vector3 origVelW = VehicleVelocity; // DEBUG
  933. Vector3 currentVelV = VehicleForwardVelocity;
  934. Vector3 linearMotorCorrectionV = m_linearMotor.Step(pTimestep, currentVelV);
  935. // Friction reduces vehicle motion based on absolute speed. Slow vehicle down by friction.
  936. Vector3 frictionFactorV = ComputeFrictionFactor(m_linearFrictionTimescale, pTimestep);
  937. linearMotorCorrectionV -= (currentVelV * frictionFactorV);
  938. // Motor is vehicle coordinates. Rotate it to world coordinates
  939. Vector3 linearMotorVelocityW = linearMotorCorrectionV * VehicleFrameOrientation;
  940. // If we're a ground vehicle, don't add any upward Z movement
  941. if ((m_flags & VehicleFlag.LIMIT_MOTOR_UP) != 0)
  942. {
  943. if (linearMotorVelocityW.Z > 0f)
  944. linearMotorVelocityW.Z = 0f;
  945. }
  946. // Add this correction to the velocity to make it faster/slower.
  947. VehicleVelocity += linearMotorVelocityW;
  948. VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},tgt={3},correctV={4},correctW={5},newVelW={6},fricFact={7}",
  949. ControllingPrim.LocalID, origVelW, currentVelV, m_linearMotor.TargetValue, linearMotorCorrectionV,
  950. linearMotorVelocityW, VehicleVelocity, frictionFactorV);
  951. }
  952. //Given a Deflection Effiency and a Velocity, Returns a Velocity that is Partially Deflected onto the X Axis
  953. //Clamped so that a DeflectionTimescale of less then 1 does not increase force over original velocity
  954. private void ComputeLinearDeflection(float pTimestep)
  955. {
  956. Vector3 linearDeflectionV = Vector3.Zero;
  957. Vector3 velocityV = VehicleForwardVelocity;
  958. if (BSParam.VehicleEnableLinearDeflection)
  959. {
  960. // Velocity in Y and Z dimensions is movement to the side or turning.
  961. // Compute deflection factor from the to the side and rotational velocity
  962. linearDeflectionV.Y = SortedClampInRange(0, (velocityV.Y * m_linearDeflectionEfficiency) / m_linearDeflectionTimescale, velocityV.Y);
  963. linearDeflectionV.Z = SortedClampInRange(0, (velocityV.Z * m_linearDeflectionEfficiency) / m_linearDeflectionTimescale, velocityV.Z);
  964. // Velocity to the side and around is corrected and moved into the forward direction
  965. linearDeflectionV.X += Math.Abs(linearDeflectionV.Y);
  966. linearDeflectionV.X += Math.Abs(linearDeflectionV.Z);
  967. // Scale the deflection to the fractional simulation time
  968. linearDeflectionV *= pTimestep;
  969. // Subtract the sideways and rotational velocity deflection factors while adding the correction forward
  970. linearDeflectionV *= new Vector3(1, -1, -1);
  971. // Correction is vehicle relative. Convert to world coordinates.
  972. Vector3 linearDeflectionW = linearDeflectionV * VehicleFrameOrientation;
  973. // Optionally, if not colliding, don't effect world downward velocity. Let falling things fall.
  974. if (BSParam.VehicleLinearDeflectionNotCollidingNoZ && !m_controllingPrim.HasSomeCollision)
  975. {
  976. linearDeflectionW.Z = 0f;
  977. }
  978. VehicleVelocity += linearDeflectionW;
  979. VDetailLog("{0}, MoveLinear,LinearDeflection,linDefEff={1},linDefTS={2},linDeflectionV={3}",
  980. ControllingPrim.LocalID, m_linearDeflectionEfficiency, m_linearDeflectionTimescale, linearDeflectionV);
  981. }
  982. }
  983. public void ComputeLinearTerrainHeightCorrection(float pTimestep)
  984. {
  985. // If below the terrain, move us above the ground a little.
  986. // TODO: Consider taking the rotated size of the object or possibly casting a ray.
  987. if (VehiclePosition.Z < GetTerrainHeight(VehiclePosition))
  988. {
  989. // Force position because applying force won't get the vehicle through the terrain
  990. Vector3 newPosition = VehiclePosition;
  991. newPosition.Z = GetTerrainHeight(VehiclePosition) + 1f;
  992. VehiclePosition = newPosition;
  993. VDetailLog("{0}, MoveLinear,terrainHeight,terrainHeight={1},pos={2}",
  994. ControllingPrim.LocalID, GetTerrainHeight(VehiclePosition), VehiclePosition);
  995. }
  996. }
  997. public void ComputeLinearHover(float pTimestep)
  998. {
  999. // m_VhoverEfficiency: 0=bouncy, 1=totally damped
  1000. // m_VhoverTimescale: time to achieve height
  1001. if ((m_flags & (VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT)) != 0 && (m_VhoverHeight > 0) && (m_VhoverTimescale < 300))
  1002. {
  1003. // We should hover, get the target height
  1004. if ((m_flags & VehicleFlag.HOVER_WATER_ONLY) != 0)
  1005. {
  1006. m_VhoverTargetHeight = GetWaterLevel(VehiclePosition) + m_VhoverHeight;
  1007. }
  1008. if ((m_flags & VehicleFlag.HOVER_TERRAIN_ONLY) != 0)
  1009. {
  1010. m_VhoverTargetHeight = GetTerrainHeight(VehiclePosition) + m_VhoverHeight;
  1011. }
  1012. if ((m_flags & VehicleFlag.HOVER_GLOBAL_HEIGHT) != 0)
  1013. {
  1014. m_VhoverTargetHeight = m_VhoverHeight;
  1015. }
  1016. if ((m_flags & VehicleFlag.HOVER_UP_ONLY) != 0)
  1017. {
  1018. // If body is already heigher, use its height as target height
  1019. if (VehiclePosition.Z > m_VhoverTargetHeight)
  1020. {
  1021. m_VhoverTargetHeight = VehiclePosition.Z;
  1022. // A 'misfeature' of this flag is that if the vehicle is above it's hover height,
  1023. // the vehicle's buoyancy goes away. This is an SL bug that got used by so many
  1024. // scripts that it could not be changed.
  1025. // So, if above the height, reapply gravity if buoyancy had it turned off.
  1026. if (m_VehicleBuoyancy != 0)
  1027. {
  1028. Vector3 appliedGravity = ControllingPrim.ComputeGravity(ControllingPrim.Buoyancy) * m_vehicleMass;
  1029. VehicleAddForce(appliedGravity);
  1030. }
  1031. }
  1032. }
  1033. if ((m_flags & VehicleFlag.LOCK_HOVER_HEIGHT) != 0)
  1034. {
  1035. if (Math.Abs(VehiclePosition.Z - m_VhoverTargetHeight) > 0.2f)
  1036. {
  1037. Vector3 pos = VehiclePosition;
  1038. pos.Z = m_VhoverTargetHeight;
  1039. VehiclePosition = pos;
  1040. VDetailLog("{0}, MoveLinear,hover,pos={1},lockHoverHeight", ControllingPrim.LocalID, pos);
  1041. }
  1042. }
  1043. else
  1044. {
  1045. // Error is positive if below the target and negative if above.
  1046. Vector3 hpos = VehiclePosition;
  1047. float verticalError = m_VhoverTargetHeight - hpos.Z;
  1048. float verticalCorrection = verticalError / m_VhoverTimescale;
  1049. verticalCorrection *= m_VhoverEfficiency;
  1050. hpos.Z += verticalCorrection;
  1051. VehiclePosition = hpos;
  1052. // Since we are hovering, we need to do the opposite of falling -- get rid of world Z
  1053. Vector3 vel = VehicleVelocity;
  1054. vel.Z = 0f;
  1055. VehicleVelocity = vel;
  1056. /*
  1057. float verticalCorrectionVelocity = verticalError / m_VhoverTimescale;
  1058. Vector3 verticalCorrection = new Vector3(0f, 0f, verticalCorrectionVelocity);
  1059. verticalCorrection *= m_vehicleMass;
  1060. // TODO: implement m_VhoverEfficiency correctly
  1061. VehicleAddForceImpulse(verticalCorrection);
  1062. */
  1063. VDetailLog("{0}, MoveLinear,hover,pos={1},eff={2},hoverTS={3},height={4},target={5},err={6},corr={7}",
  1064. ControllingPrim.LocalID, VehiclePosition, m_VhoverEfficiency,
  1065. m_VhoverTimescale, m_VhoverHeight, m_VhoverTargetHeight,
  1066. verticalError, verticalCorrection);
  1067. }
  1068. }
  1069. }
  1070. public bool ComputeLinearBlockingEndPoint(float pTimestep)
  1071. {
  1072. bool changed = false;
  1073. Vector3 pos = VehiclePosition;
  1074. Vector3 posChange = pos - m_lastPositionVector;
  1075. if (m_BlockingEndPoint != Vector3.Zero)
  1076. {
  1077. if (pos.X >= (m_BlockingEndPoint.X - (float)1))
  1078. {
  1079. pos.X -= posChange.X + 1;
  1080. changed = true;
  1081. }
  1082. if (pos.Y >= (m_BlockingEndPoint.Y - (float)1))
  1083. {
  1084. pos.Y -= posChange.Y + 1;
  1085. changed = true;
  1086. }
  1087. if (pos.Z >= (m_BlockingEndPoint.Z - (float)1))
  1088. {
  1089. pos.Z -= posChange.Z + 1;
  1090. changed = true;
  1091. }
  1092. if (pos.X <= 0)
  1093. {
  1094. pos.X += posChange.X + 1;
  1095. changed = true;
  1096. }
  1097. if (pos.Y <= 0)
  1098. {
  1099. pos.Y += posChange.Y + 1;
  1100. changed = true;
  1101. }
  1102. if (changed)
  1103. {
  1104. VehiclePosition = pos;
  1105. VDetailLog("{0}, MoveLinear,blockingEndPoint,block={1},origPos={2},pos={3}",
  1106. ControllingPrim.LocalID, m_BlockingEndPoint, posChange, pos);
  1107. }
  1108. }
  1109. return changed;
  1110. }
  1111. // From http://wiki.secondlife.com/wiki/LlSetVehicleFlags :
  1112. // Prevent ground vehicles from motoring into the sky. This flag has a subtle effect when
  1113. // used with conjunction with banking: the strength of the banking will decay when the
  1114. // vehicle no longer experiences collisions. The decay timescale is the same as
  1115. // VEHICLE_BANKING_TIMESCALE. This is to help prevent ground vehicles from steering
  1116. // when they are in mid jump.
  1117. // TODO: this code is wrong. Also, what should it do for boats (height from water)?
  1118. // This is just using the ground and a general collision check. Should really be using
  1119. // a downward raycast to find what is below.
  1120. public void ComputeLinearMotorUp(float pTimestep)
  1121. {
  1122. if ((m_flags & (VehicleFlag.LIMIT_MOTOR_UP)) != 0)
  1123. {
  1124. // This code tries to decide if the object is not on the ground and then pushing down
  1125. /*
  1126. float targetHeight = Type == Vehicle.TYPE_BOAT ? GetWaterLevel(VehiclePosition) : GetTerrainHeight(VehiclePosition);
  1127. distanceAboveGround = VehiclePosition.Z - targetHeight;
  1128. // Not colliding if the vehicle is off the ground
  1129. if (!Prim.HasSomeCollision)
  1130. {
  1131. // downForce = new Vector3(0, 0, -distanceAboveGround / m_bankingTimescale);
  1132. VehicleVelocity += new Vector3(0, 0, -distanceAboveGround);
  1133. }
  1134. // TODO: this calculation is wrong. From the description at
  1135. // (http://wiki.secondlife.com/wiki/Category:LSL_Vehicle), the downForce
  1136. // has a decay factor. This says this force should
  1137. // be computed with a motor.
  1138. // TODO: add interaction with banking.
  1139. VDetailLog("{0}, MoveLinear,limitMotorUp,distAbove={1},colliding={2},ret={3}",
  1140. Prim.LocalID, distanceAboveGround, Prim.HasSomeCollision, ret);
  1141. */
  1142. // Another approach is to measure if we're going up. If going up and not colliding,
  1143. // the vehicle is in the air. Fix that by pushing down.
  1144. if (!ControllingPrim.HasSomeCollision && VehicleVelocity.Z > 0.1)
  1145. {
  1146. // Get rid of any of the velocity vector that is pushing us up.
  1147. float upVelocity = VehicleVelocity.Z;
  1148. VehicleVelocity += new Vector3(0, 0, -upVelocity);
  1149. /*
  1150. // If we're pointed up into the air, we should nose down
  1151. Vector3 pointingDirection = Vector3.UnitX * VehicleOrientation;
  1152. // The rotation around the Y axis is pitch up or down
  1153. if (pointingDirection.Y > 0.01f)
  1154. {
  1155. float angularCorrectionForce = -(float)Math.Asin(pointingDirection.Y);
  1156. Vector3 angularCorrectionVector = new Vector3(0f, angularCorrectionForce, 0f);
  1157. // Rotate into world coordinates and apply to vehicle
  1158. angularCorrectionVector *= VehicleOrientation;
  1159. VehicleAddAngularForce(angularCorrectionVector);
  1160. VDetailLog("{0}, MoveLinear,limitMotorUp,newVel={1},pntDir={2},corrFrc={3},aCorr={4}",
  1161. Prim.LocalID, VehicleVelocity, pointingDirection, angularCorrectionForce, angularCorrectionVector);
  1162. }
  1163. */
  1164. VDetailLog("{0}, MoveLinear,limitMotorUp,collide={1},upVel={2},newVel={3}",
  1165. ControllingPrim.LocalID, ControllingPrim.HasSomeCollision, upVelocity, VehicleVelocity);
  1166. }
  1167. }
  1168. }
  1169. private void ApplyGravity(float pTimeStep)
  1170. {
  1171. Vector3 appliedGravity = m_VehicleGravity * m_vehicleMass;
  1172. // Hack to reduce downward force if the vehicle is probably sitting on the ground
  1173. if (ControllingPrim.HasSomeCollision && IsGroundVehicle)
  1174. appliedGravity *= BSParam.VehicleGroundGravityFudge;
  1175. VehicleAddForce(appliedGravity);
  1176. VDetailLog("{0}, MoveLinear,applyGravity,vehGrav={1},collid={2},fudge={3},mass={4},appliedForce={5}",
  1177. ControllingPrim.LocalID, m_VehicleGravity,
  1178. ControllingPrim.HasSomeCollision, BSParam.VehicleGroundGravityFudge, m_vehicleMass, appliedGravity);
  1179. }
  1180. // =======================================================================
  1181. // =======================================================================
  1182. // Apply the effect of the angular motor.
  1183. // The 'contribution' is how much angular correction velocity each function wants.
  1184. // All the contributions are added together and the resulting velocity is
  1185. // set directly on the vehicle.
  1186. private void MoveAngular(float pTimestep)
  1187. {
  1188. ComputeAngularTurning(pTimestep);
  1189. ComputeAngularVerticalAttraction();
  1190. ComputeAngularDeflection();
  1191. ComputeAngularBanking();
  1192. // ==================================================================
  1193. if (VehicleRotationalVelocity.ApproxEquals(Vector3.Zero, 0.0001f))
  1194. {
  1195. // The vehicle is not adding anything angular wise.
  1196. VehicleRotationalVelocity = Vector3.Zero;
  1197. VDetailLog("{0}, MoveAngular,done,zero", ControllingPrim.LocalID);
  1198. }
  1199. else
  1200. {
  1201. VDetailLog("{0}, MoveAngular,done,nonZero,angVel={1}", ControllingPrim.LocalID, VehicleRotationalVelocity);
  1202. }
  1203. // ==================================================================
  1204. //Offset section
  1205. if (m_linearMotorOffset != Vector3.Zero)
  1206. {
  1207. //Offset of linear velocity doesn't change the linear velocity,
  1208. // but causes a torque to be applied, for example...
  1209. //
  1210. // IIIII >>> IIIII
  1211. // IIIII >>> IIIII
  1212. // IIIII >>> IIIII
  1213. // ^
  1214. // | Applying a force at the arrow will cause the object to move forward, but also rotate
  1215. //
  1216. //
  1217. // The torque created is the linear velocity crossed with the offset
  1218. // TODO: this computation should be in the linear section
  1219. // because that is where we know the impulse being applied.
  1220. Vector3 torqueFromOffset = Vector3.Zero;
  1221. // torqueFromOffset = Vector3.Cross(m_linearMotorOffset, appliedImpulse);
  1222. if (float.IsNaN(torqueFromOffset.X))
  1223. torqueFromOffset.X = 0;
  1224. if (float.IsNaN(torqueFromOffset.Y))
  1225. torqueFromOffset.Y = 0;
  1226. if (float.IsNaN(torqueFromOffset.Z))
  1227. torqueFromOffset.Z = 0;
  1228. VehicleAddAngularForce(torqueFromOffset * m_vehicleMass);
  1229. VDetailLog("{0}, BSDynamic.MoveAngular,motorOffset,applyTorqueImpulse={1}", ControllingPrim.LocalID, torqueFromOffset);
  1230. }
  1231. }
  1232. private void ComputeAngularTurning(float pTimestep)
  1233. {
  1234. // The user wants this many radians per second angular change?
  1235. Vector3 origVehicleRotationalVelocity = VehicleRotationalVelocity; // DEBUG DEBUG
  1236. Vector3 currentAngularV = VehicleRotationalVelocity * Quaternion.Inverse(VehicleFrameOrientation);
  1237. Vector3 angularMotorContributionV = m_angularMotor.Step(pTimestep, currentAngularV);
  1238. // ==================================================================
  1239. // From http://wiki.secondlife.com/wiki/LlSetVehicleFlags :
  1240. // This flag prevents linear deflection parallel to world z-axis. This is useful
  1241. // for preventing ground vehicles with large linear deflection, like bumper cars,
  1242. // from climbing their linear deflection into the sky.
  1243. // That is, NO_DEFLECTION_UP says angular motion should not add any pitch or roll movement
  1244. // TODO: This is here because this is where ODE put it but documentation says it
  1245. // is a linear effect. Where should this check go?
  1246. //if ((m_flags & (VehicleFlag.NO_DEFLECTION_UP)) != 0)
  1247. // {
  1248. // angularMotorContributionV.X = 0f;
  1249. // angularMotorContributionV.Y = 0f;
  1250. // }
  1251. // Reduce any velocity by friction.
  1252. Vector3 frictionFactorW = ComputeFrictionFactor(m_angularFrictionTimescale, pTimestep);
  1253. angularMotorContributionV -= (currentAngularV * frictionFactorW);
  1254. Vector3 angularMotorContributionW = angularMotorContributionV * VehicleFrameOrientation;
  1255. VehicleRotationalVelocity += angularMotorContributionW;
  1256. VDetailLog("{0}, MoveAngular,angularTurning,curAngVelV={1},origVehRotVel={2},vehRotVel={3},frictFact={4}, angContribV={5},angContribW={6}",
  1257. ControllingPrim.LocalID, currentAngularV, origVehicleRotationalVelocity, VehicleRotationalVelocity, frictionFactorW, angularMotorContributionV, angularMotorContributionW);
  1258. }
  1259. // From http://wiki.secondlife.com/wiki/Linden_Vehicle_Tutorial:
  1260. // Some vehicles, like boats, should always keep their up-side up. This can be done by
  1261. // enabling the "vertical attractor" behavior that springs the vehicle's local z-axis to
  1262. // the world z-axis (a.k.a. "up"). To take advantage of this feature you would set the
  1263. // VEHICLE_VERTICAL_ATTRACTION_TIMESCALE to control the period of the spring frequency,
  1264. // and then set the VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY to control the damping. An
  1265. // efficiency of 0.0 will cause the spring to wobble around its equilibrium, while an
  1266. // efficiency of 1.0 will cause the spring to reach its equilibrium with exponential decay.
  1267. public void ComputeAngularVerticalAttraction()
  1268. {
  1269. // If vertical attaction timescale is reasonable
  1270. if (BSParam.VehicleEnableAngularVerticalAttraction && m_verticalAttractionTimescale < m_verticalAttractionCutoff)
  1271. {
  1272. Vector3 vehicleUpAxis = Vector3.UnitZ * VehicleFrameOrientation;
  1273. switch (BSParam.VehicleAngularVerticalAttractionAlgorithm)
  1274. {
  1275. case 0:
  1276. {
  1277. //Another formula to try got from :
  1278. //http://answers.unity3d.com/questions/10425/how-to-stabilize-angular-motion-alignment-of-hover.html
  1279. // Flipping what was originally a timescale into a speed variable and then multiplying it by 2
  1280. // since only computing half the distance between the angles.
  1281. float verticalAttractionSpeed = (1 / m_verticalAttractionTimescale) * 2.0f;
  1282. // Make a prediction of where the up axis will be when this is applied rather then where it is now as
  1283. // this makes for a smoother adjustment and less fighting between the various forces.
  1284. Vector3 predictedUp = vehicleUpAxis * Quaternion.CreateFromAxisAngle(VehicleRotationalVelocity, 0f);
  1285. // This is only half the distance to the target so it will take 2 seconds to complete the turn.
  1286. Vector3 torqueVector = Vector3.Cross(predictedUp, Vector3.UnitZ);
  1287. if ((m_flags & VehicleFlag.LIMIT_ROLL_ONLY) != 0)
  1288. {
  1289. Vector3 vehicleForwardAxis = Vector3.UnitX * VehicleFrameOrientation;
  1290. torqueVector = ProjectVector(torqueVector, vehicleForwardAxis);
  1291. }
  1292. // Scale vector by our timescale since it is an acceleration it is r/s^2 or radians a timescale squared
  1293. Vector3 vertContributionV = torqueVector * verticalAttractionSpeed * verticalAttractionSpeed;
  1294. VehicleRotationalVelocity += vertContributionV;
  1295. VDetailLog("{0}, MoveAngular,verticalAttraction,vertAttrSpeed={1},upAxis={2},PredictedUp={3},torqueVector={4},contrib={5}",
  1296. ControllingPrim.LocalID,
  1297. verticalAttractionSpeed,
  1298. vehicleUpAxis,
  1299. predictedUp,
  1300. torqueVector,
  1301. vertContributionV);
  1302. break;
  1303. }
  1304. case 1:
  1305. {
  1306. // Possible solution derived from a discussion at:
  1307. // http://stackoverflow.com/questions/14939657/computing-vector-from-quaternion-works-computing-quaternion-from-vector-does-no
  1308. // Create a rotation that is only the vehicle's rotation around Z
  1309. Vector3 currentEulerW = Vector3.Zero;
  1310. VehicleFrameOrientation.GetEulerAngles(out currentEulerW.X, out currentEulerW.Y, out currentEulerW.Z);
  1311. Quaternion justZOrientation = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, currentEulerW.Z);
  1312. // Create the axis that is perpendicular to the up vector and the rotated up vector.
  1313. Vector3 differenceAxisW = Vector3.Cross(Vector3.UnitZ * justZOrientation, Vector3.UnitZ * VehicleFrameOrientation);
  1314. // Compute the angle between those to vectors.
  1315. double differenceAngle = Math.Acos((double)Vector3.Dot(Vector3.UnitZ, Vector3.Normalize(Vector3.UnitZ * VehicleFrameOrientation)));
  1316. // 'differenceAngle' is the angle to rotate and 'differenceAxis' is the plane to rotate in to get the vehicle vertical
  1317. // Reduce the change by the time period it is to change in. Timestep is handled when velocity is applied.
  1318. // TODO: add 'efficiency'.
  1319. // differenceAngle /= m_verticalAttractionTimescale;
  1320. // Create the quaterian representing the correction angle
  1321. Quaternion correctionRotationW = Quaternion.CreateFromAxisAngle(differenceAxisW, (float)differenceAngle);
  1322. // Turn that quaternion into Euler values to make it into velocities to apply.
  1323. Vector3 vertContributionW = Vector3.Zero;
  1324. correctionRotationW.GetEulerAngles(out vertContributionW.X, out vertContributionW.Y, out vertContributionW.Z);
  1325. vertContributionW *= -1f;
  1326. vertContributionW /= m_verticalAttractionTimescale;
  1327. VehicleRotationalVelocity += vertContributionW;
  1328. VDetailLog("{0}, MoveAngular,verticalAttraction,upAxis={1},diffAxis={2},diffAng={3},corrRot={4},contrib={5}",
  1329. ControllingPrim.LocalID,
  1330. vehicleUpAxis,
  1331. differenceAxisW,
  1332. differenceAngle,
  1333. correctionRotationW,
  1334. vertContributionW);
  1335. break;
  1336. }
  1337. case 2:
  1338. {
  1339. Vector3 vertContributionV = Vector3.Zero;
  1340. Vector3 origRotVelW = VehicleRotationalVelocity; // DEBUG DEBUG
  1341. // Take a vector pointing up and convert it from world to vehicle relative coords.
  1342. Vector3 verticalError = Vector3.Normalize(Vector3.UnitZ * VehicleFrameOrientation);
  1343. // If vertical attraction correction is needed, the vector that was pointing up (UnitZ)
  1344. // is now:
  1345. // leaning to one side: rotated around the X axis with the Y value going
  1346. // from zero (nearly straight up) to one (completely to the side)) or
  1347. // leaning front-to-back: rotated around the Y axis with the value of X being between
  1348. // zero and one.
  1349. // The value of Z is how far the rotation is off with 1 meaning none and 0 being 90 degrees.
  1350. // Y error means needed rotation around X axis and visa versa.
  1351. // Since the error goes from zero to one, the asin is the corresponding angle.
  1352. vertContributionV.X = (float)Math.Asin(verticalError.Y);
  1353. // (Tilt forward (positive X) needs to tilt back (rotate negative) around Y axis.)
  1354. vertContributionV.Y = -(float)Math.Asin(verticalError.X);
  1355. // If verticalError.Z is negative, the vehicle is upside down. Add additional push.
  1356. if (verticalError.Z < 0f)
  1357. {
  1358. vertContributionV.X += Math.Sign(vertContributionV.X) * PIOverFour;
  1359. // vertContribution.Y -= PIOverFour;
  1360. }
  1361. // 'vertContrbution' is now the necessary angular correction to correct tilt in one second.
  1362. // Correction happens over a number of seconds.
  1363. Vector3 unscaledContribVerticalErrorV = vertContributionV; // DEBUG DEBUG
  1364. // The correction happens over the user's time period
  1365. vertContributionV /= m_verticalAttractionTimescale;
  1366. // Rotate the vehicle rotation to the world coordinates.
  1367. VehicleRotationalVelocity += (vertContributionV * VehicleFrameOrientation);
  1368. VDetailLog("{0}, MoveAngular,verticalAttraction,,upAxis={1},origRotVW={2},vertError={3},unscaledV={4},eff={5},ts={6},vertContribV={7}",
  1369. ControllingPrim.LocalID,
  1370. vehicleUpAxis,
  1371. origRotVelW,
  1372. verticalError,
  1373. unscaledContribVerticalErrorV,
  1374. m_verticalAttractionEfficiency,
  1375. m_verticalAttractionTimescale,
  1376. vertContributionV);
  1377. break;
  1378. }
  1379. default:
  1380. {
  1381. break;
  1382. }
  1383. }
  1384. }
  1385. }
  1386. // Angular correction to correct the direction the vehicle is pointing to be
  1387. // the direction is should want to be pointing.
  1388. // The vehicle is moving in some direction and correct its orientation to it is pointing
  1389. // in that direction.
  1390. // TODO: implement reference frame.
  1391. public void ComputeAngularDeflection()
  1392. {
  1393. if (BSParam.VehicleEnableAngularDeflection && m_angularDeflectionEfficiency != 0 && VehicleForwardSpeed > 0.2)
  1394. {
  1395. Vector3 deflectContributionV = Vector3.Zero;
  1396. // The direction the vehicle is moving
  1397. Vector3 movingDirection = VehicleVelocity;
  1398. movingDirection.Normalize();
  1399. // If the vehicle is going backward, it is still pointing forward
  1400. movingDirection *= Math.Sign(VehicleForwardSpeed);
  1401. // The direction the vehicle is pointing
  1402. Vector3 pointingDirection = Vector3.UnitX * VehicleFrameOrientation;
  1403. //Predict where the Vehicle will be pointing after AngularVelocity change is applied. This will keep
  1404. // from overshooting and allow this correction to merge with the Vertical Attraction peacefully.
  1405. Vector3 predictedPointingDirection = pointingDirection * Quaternion.CreateFromAxisAngle(VehicleRotationalVelocity, 0f);
  1406. predictedPointingDirection.Normalize();
  1407. // The difference between what is and what should be.
  1408. // Vector3 deflectionError = movingDirection - predictedPointingDirection;
  1409. Vector3 deflectionError = Vector3.Cross(movingDirection, predictedPointingDirection);
  1410. // Don't try to correct very large errors (not our job)
  1411. // if (Math.Abs(deflectionError.X) > PIOverFour) deflectionError.X = PIOverTwo * Math.Sign(deflectionError.X);
  1412. // if (Math.Abs(deflectionError.Y) > PIOverFour) deflectionError.Y = PIOverTwo * Math.Sign(deflectionError.Y);
  1413. // if (Math.Abs(deflectionError.Z) > PIOverFour) deflectionError.Z = PIOverTwo * Math.Sign(deflectionError.Z);
  1414. if (Math.Abs(deflectionError.X) > PIOverFour) deflectionError.X = 0f;
  1415. if (Math.Abs(deflectionError.Y) > PIOverFour) deflectionError.Y = 0f;
  1416. if (Math.Abs(deflectionError.Z) > PIOverFour) deflectionError.Z = 0f;
  1417. // ret = m_angularDeflectionCorrectionMotor(1f, deflectionError);
  1418. // Scale the correction by recovery timescale and efficiency
  1419. // Not modeling a spring so clamp the scale to no more then the arc
  1420. deflectContributionV = (-deflectionError) * ClampInRange(0, m_angularDeflectionEfficiency/m_angularDeflectionTimescale,1f);
  1421. //deflectContributionV /= m_angularDeflectionTimescale;
  1422. VehicleRotationalVelocity += deflectContributionV;
  1423. VDetailLog("{0}, MoveAngular,Deflection,movingDir={1},pointingDir={2},deflectError={3},ret={4}",
  1424. ControllingPrim.LocalID, movingDirection, pointingDirection, deflectionError, deflectContributionV);
  1425. VDetailLog("{0}, MoveAngular,Deflection,fwdSpd={1},defEff={2},defTS={3},PredictedPointingDir={4}",
  1426. ControllingPrim.LocalID, VehicleForwardSpeed, m_angularDeflectionEfficiency, m_angularDeflectionTimescale, predictedPointingDirection);
  1427. }
  1428. }
  1429. // Angular change to rotate the vehicle around the Z axis when the vehicle
  1430. // is tipped around the X axis.
  1431. // From http://wiki.secondlife.com/wiki/Linden_Vehicle_Tutorial:
  1432. // The vertical attractor feature must be enabled in order for the banking behavior to
  1433. // function. The way banking works is this: a rotation around the vehicle's roll-axis will
  1434. // produce a angular velocity around the yaw-axis, causing the vehicle to turn. The magnitude
  1435. // of the yaw effect will be proportional to the
  1436. // VEHICLE_BANKING_EFFICIENCY, the angle of the roll rotation, and sometimes the vehicle's
  1437. // velocity along its preferred axis of motion.
  1438. // The VEHICLE_BANKING_EFFICIENCY can vary between -1 and +1. When it is positive then any
  1439. // positive rotation (by the right-hand rule) about the roll-axis will effect a
  1440. // (negative) torque around the yaw-axis, making it turn to the right--that is the
  1441. // vehicle will lean into the turn, which is how real airplanes and motorcycle's work.
  1442. // Negating the banking coefficient will make it so that the vehicle leans to the
  1443. // outside of the turn (not very "physical" but might allow interesting vehicles so why not?).
  1444. // The VEHICLE_BANKING_MIX is a fake (i.e. non-physical) parameter that is useful for making
  1445. // banking vehicles do what you want rather than what the laws of physics allow.
  1446. // For example, consider a real motorcycle...it must be moving forward in order for
  1447. // it to turn while banking, however video-game motorcycles are often configured
  1448. // to turn in place when at a dead stop--because they are often easier to control
  1449. // that way using the limited interface of the keyboard or game controller. The
  1450. // VEHICLE_BANKING_MIX enables combinations of both realistic and non-realistic
  1451. // banking by functioning as a slider between a banking that is correspondingly
  1452. // totally static (0.0) and totally dynamic (1.0). By "static" we mean that the
  1453. // banking effect depends only on the vehicle's rotation about its roll-axis compared
  1454. // to "dynamic" where the banking is also proportional to its velocity along its
  1455. // roll-axis. Finding the best value of the "mixture" will probably require trial and error.
  1456. // The time it takes for the banking behavior to defeat a preexisting angular velocity about the
  1457. // world z-axis is determined by the VEHICLE_BANKING_TIMESCALE. So if you want the vehicle to
  1458. // bank quickly then give it a banking timescale of about a second or less, otherwise you can
  1459. // make a sluggish vehicle by giving it a timescale of several seconds.
  1460. public void ComputeAngularBanking()
  1461. {
  1462. if (BSParam.VehicleEnableAngularBanking && m_bankingEfficiency != 0 && m_verticalAttractionTimescale < m_verticalAttractionCutoff)
  1463. {
  1464. Vector3 bankingContributionV = Vector3.Zero;
  1465. // Rotate a UnitZ vector (pointing up) to how the vehicle is oriented.
  1466. // As the vehicle rolls to the right or left, the Y value will increase from
  1467. // zero (straight up) to 1 or -1 (full tilt right or left)
  1468. Vector3 rollComponents = Vector3.UnitZ * VehicleFrameOrientation;
  1469. // Figure out the yaw value for this much roll.
  1470. float yawAngle = m_angularMotorDirection.X * m_bankingEfficiency;
  1471. // actual error = static turn error + dynamic turn error
  1472. float mixedYawAngle =(yawAngle * (1f - m_bankingMix)) + ((yawAngle * m_bankingMix) * VehicleForwardSpeed);
  1473. // TODO: the banking effect should not go to infinity but what to limit it to?
  1474. // And what should happen when this is being added to a user defined yaw that is already PI*4?
  1475. mixedYawAngle = ClampInRange(-FourPI, mixedYawAngle, FourPI);
  1476. // Build the force vector to change rotation from what it is to what it should be
  1477. bankingContributionV.Z = -mixedYawAngle;
  1478. // Don't do it all at once. Fudge because 1 second is too fast with most user defined roll as PI*4.
  1479. bankingContributionV /= m_bankingTimescale * BSParam.VehicleAngularBankingTimescaleFudge;
  1480. VehicleRotationalVelocity += bankingContributionV;
  1481. VDetailLog("{0}, MoveAngular,Banking,rollComp={1},speed={2},rollComp={3},yAng={4},mYAng={5},ret={6}",
  1482. ControllingPrim.LocalID, rollComponents, VehicleForwardSpeed, rollComponents, yawAngle, mixedYawAngle, bankingContributionV);
  1483. }
  1484. }
  1485. // This is from previous instantiations of XXXDynamics.cs.
  1486. // Applies roll reference frame.
  1487. // TODO: is this the right way to separate the code to do this operation?
  1488. // Should this be in MoveAngular()?
  1489. internal void LimitRotation(float timestep)
  1490. {
  1491. Quaternion rotq = VehicleOrientation;
  1492. Quaternion m_rot = rotq;
  1493. if (m_RollreferenceFrame != Quaternion.Identity)
  1494. {
  1495. if (rotq.X >= m_RollreferenceFrame.X)
  1496. {
  1497. m_rot.X = rotq.X - (m_RollreferenceFrame.X / 2);
  1498. }
  1499. if (rotq.Y >= m_RollreferenceFrame.Y)
  1500. {
  1501. m_rot.Y = rotq.Y - (m_RollreferenceFrame.Y / 2);
  1502. }
  1503. if (rotq.X <= -m_RollreferenceFrame.X)
  1504. {
  1505. m_rot.X = rotq.X + (m_RollreferenceFrame.X / 2);
  1506. }
  1507. if (rotq.Y <= -m_RollreferenceFrame.Y)
  1508. {
  1509. m_rot.Y = rotq.Y + (m_RollreferenceFrame.Y / 2);
  1510. }
  1511. }
  1512. if ((m_flags & VehicleFlag.LOCK_ROTATION) != 0)
  1513. {
  1514. m_rot.X = 0;
  1515. m_rot.Y = 0;
  1516. }
  1517. if (rotq != m_rot)
  1518. {
  1519. VehicleOrientation = m_rot;
  1520. VDetailLog("{0}, LimitRotation,done,orig={1},new={2}", ControllingPrim.LocalID, rotq, m_rot);
  1521. }
  1522. }
  1523. // Given a friction vector (reduction in seconds) and a timestep, return the factor to reduce
  1524. // some value by to apply this friction.
  1525. private Vector3 ComputeFrictionFactor(Vector3 friction, float pTimestep)
  1526. {
  1527. Vector3 frictionFactor = Vector3.Zero;
  1528. if (friction != BSMotor.InfiniteVector)
  1529. {
  1530. // frictionFactor = (Vector3.One / FrictionTimescale) * timeStep;
  1531. // Individual friction components can be 'infinite' so compute each separately.
  1532. frictionFactor.X = (friction.X == BSMotor.Infinite) ? 0f : (1f / friction.X);
  1533. frictionFactor.Y = (friction.Y == BSMotor.Infinite) ? 0f : (1f / friction.Y);
  1534. frictionFactor.Z = (friction.Z == BSMotor.Infinite) ? 0f : (1f / friction.Z);
  1535. frictionFactor *= pTimestep;
  1536. }
  1537. return frictionFactor;
  1538. }
  1539. private float SortedClampInRange(float clampa, float val, float clampb)
  1540. {
  1541. if (clampa > clampb)
  1542. {
  1543. float temp = clampa;
  1544. clampa = clampb;
  1545. clampb = temp;
  1546. }
  1547. return ClampInRange(clampa, val, clampb);
  1548. }
  1549. //Given a Vector and a unit vector will return the amount of the vector is on the same axis as the unit.
  1550. private Vector3 ProjectVector(Vector3 vector, Vector3 onNormal)
  1551. {
  1552. float vectorDot = Vector3.Dot(vector, onNormal);
  1553. return onNormal * vectorDot;
  1554. }
  1555. private float ClampInRange(float low, float val, float high)
  1556. {
  1557. return Math.Max(low, Math.Min(val, high));
  1558. // return Utils.Clamp(val, low, high);
  1559. }
  1560. // Invoke the detailed logger and output something if it's enabled.
  1561. private void VDetailLog(string msg, params Object[] args)
  1562. {
  1563. if (ControllingPrim.PhysScene.VehicleLoggingEnabled)
  1564. ControllingPrim.PhysScene.DetailLog(msg, args);
  1565. }
  1566. }
  1567. }