BSDynamics.cs 86 KB

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