BSDynamics.cs 87 KB

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