Matrix4x4.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418
  1. #region --- License ---
  2. /*
  3. Copyright (c) 2006 - 2008 The Open Toolkit library.
  4. Permission is hereby granted, free of charge, to any person obtaining a copy of
  5. this software and associated documentation files (the "Software"), to deal in
  6. the Software without restriction, including without limitation the rights to
  7. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  8. of the Software, and to permit persons to whom the Software is furnished to do
  9. so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. */
  20. /*
  21. Copyright (c) 2014, Lars Brubaker
  22. All rights reserved.
  23. Redistribution and use in source and binary forms, with or without
  24. modification, are permitted provided that the following conditions are met:
  25. 1. Redistributions of source code must retain the above copyright notice, this
  26. list of conditions and the following disclaimer.
  27. 2. Redistributions in binary form must reproduce the above copyright notice,
  28. this list of conditions and the following disclaimer in the documentation
  29. and/or other materials provided with the distribution.
  30. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  31. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  32. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  33. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
  34. ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  35. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  36. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  37. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  38. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  39. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  40. The views and conclusions contained in the software and documentation are those
  41. of the authors and should not be interpreted as representing official policies,
  42. either expressed or implied, of the FreeBSD Project.
  43. */
  44. #endregion --- License ---
  45. using System;
  46. using System.Runtime.InteropServices;
  47. namespace MatterHackers.VectorMath
  48. {
  49. #if true
  50. /// <summary>
  51. /// Represents a 4x4 Matrix with double-precision components.
  52. /// </summary>
  53. [Serializable]
  54. [StructLayout(LayoutKind.Sequential)]
  55. public struct Matrix4X4 : IEquatable<Matrix4X4>
  56. {
  57. #region Fields
  58. /// <summary>
  59. /// Top row of the matrix
  60. /// </summary>
  61. public Vector4 Row0;
  62. /// <summary>
  63. /// 2nd row of the matrix
  64. /// </summary>
  65. public Vector4 Row1;
  66. /// <summary>
  67. /// 3rd row of the matrix
  68. /// </summary>
  69. public Vector4 Row2;
  70. /// <summary>
  71. /// Bottom row of the matrix
  72. /// </summary>
  73. public Vector4 Row3;
  74. /// <summary>
  75. /// The identity matrix
  76. /// </summary>
  77. public static readonly Matrix4X4 Identity = new Matrix4X4(Vector4.UnitX, Vector4.UnitY, Vector4.UnitZ, Vector4.UnitW);
  78. #endregion Fields
  79. #region Constructors
  80. /// <summary>
  81. /// Constructs a new instance.
  82. /// </summary>
  83. /// <param name="row0">Top row of the matrix</param>
  84. /// <param name="row1">Second row of the matrix</param>
  85. /// <param name="row2">Third row of the matrix</param>
  86. /// <param name="row3">Bottom row of the matrix</param>
  87. public Matrix4X4(Vector4 row0, Vector4 row1, Vector4 row2, Vector4 row3)
  88. {
  89. Row0 = row0;
  90. Row1 = row1;
  91. Row2 = row2;
  92. Row3 = row3;
  93. }
  94. /// <summary>
  95. /// Constructs a new instance.
  96. /// </summary>
  97. /// <param name="m00">First item of the first row.</param>
  98. /// <param name="m01">Second item of the first row.</param>
  99. /// <param name="m02">Third item of the first row.</param>
  100. /// <param name="m03">Fourth item of the first row.</param>
  101. /// <param name="m10">First item of the second row.</param>
  102. /// <param name="m11">Second item of the second row.</param>
  103. /// <param name="m12">Third item of the second row.</param>
  104. /// <param name="m13">Fourth item of the second row.</param>
  105. /// <param name="m20">First item of the third row.</param>
  106. /// <param name="m21">Second item of the third row.</param>
  107. /// <param name="m22">Third item of the third row.</param>
  108. /// <param name="m23">First item of the third row.</param>
  109. /// <param name="m30">Fourth item of the fourth row.</param>
  110. /// <param name="m31">Second item of the fourth row.</param>
  111. /// <param name="m32">Third item of the fourth row.</param>
  112. /// <param name="m33">Fourth item of the fourth row.</param>
  113. public Matrix4X4(
  114. double m00, double m01, double m02, double m03,
  115. double m10, double m11, double m12, double m13,
  116. double m20, double m21, double m22, double m23,
  117. double m30, double m31, double m32, double m33)
  118. {
  119. Row0 = new Vector4(m00, m01, m02, m03);
  120. Row1 = new Vector4(m10, m11, m12, m13);
  121. Row2 = new Vector4(m20, m21, m22, m23);
  122. Row3 = new Vector4(m30, m31, m32, m33);
  123. }
  124. public Matrix4X4(double[] double16)
  125. {
  126. Row0 = new Vector4(double16[0], double16[1], double16[2], double16[3]);
  127. Row1 = new Vector4(double16[4], double16[5], double16[6], double16[7]);
  128. Row2 = new Vector4(double16[8], double16[9], double16[10], double16[11]);
  129. Row3 = new Vector4(double16[12], double16[13], double16[14], double16[15]);
  130. }
  131. public Matrix4X4(float[] float16)
  132. {
  133. Row0 = new Vector4(float16[0], float16[1], float16[2], float16[3]);
  134. Row1 = new Vector4(float16[4], float16[5], float16[6], float16[7]);
  135. Row2 = new Vector4(float16[8], float16[9], float16[10], float16[11]);
  136. Row3 = new Vector4(float16[12], float16[13], float16[14], float16[15]);
  137. }
  138. #endregion Constructors
  139. #region Public Members
  140. #region Properties
  141. /// <summary>
  142. /// The determinant of this matrix
  143. /// </summary>
  144. public double Determinant
  145. {
  146. get
  147. {
  148. return
  149. Row0.X * Row1.Y * Row2.Z * Row3.W - Row0.X * Row1.Y * Row2.W * Row3.Z + Row0.X * Row1.Z * Row2.W * Row3.Y - Row0.X * Row1.Z * Row2.Y * Row3.W
  150. + Row0.X * Row1.W * Row2.Y * Row3.Z - Row0.X * Row1.W * Row2.Z * Row3.Y - Row0.Y * Row1.Z * Row2.W * Row3.X + Row0.Y * Row1.Z * Row2.X * Row3.W
  151. - Row0.Y * Row1.W * Row2.X * Row3.Z + Row0.Y * Row1.W * Row2.Z * Row3.X - Row0.Y * Row1.X * Row2.Z * Row3.W + Row0.Y * Row1.X * Row2.W * Row3.Z
  152. + Row0.Z * Row1.W * Row2.X * Row3.Y - Row0.Z * Row1.W * Row2.Y * Row3.X + Row0.Z * Row1.X * Row2.Y * Row3.W - Row0.Z * Row1.X * Row2.W * Row3.Y
  153. + Row0.Z * Row1.Y * Row2.W * Row3.X - Row0.Z * Row1.Y * Row2.X * Row3.W - Row0.W * Row1.X * Row2.Y * Row3.Z + Row0.W * Row1.X * Row2.Z * Row3.Y
  154. - Row0.W * Row1.Y * Row2.Z * Row3.X + Row0.W * Row1.Y * Row2.X * Row3.Z - Row0.W * Row1.Z * Row2.X * Row3.Y + Row0.W * Row1.Z * Row2.Y * Row3.X;
  155. }
  156. }
  157. /// <summary>
  158. /// Get just the position out of the matrix.
  159. /// </summary>
  160. public Vector3 Position
  161. {
  162. get { return new Vector3(Row3); }
  163. }
  164. /// <summary>
  165. /// The first column of this matrix
  166. /// </summary>
  167. public Vector4 Column0
  168. {
  169. get { return new Vector4(Row0.X, Row1.X, Row2.X, Row3.X); }
  170. }
  171. /// <summary>
  172. /// The second column of this matrix
  173. /// </summary>
  174. public Vector4 Column1
  175. {
  176. get { return new Vector4(Row0.Y, Row1.Y, Row2.Y, Row3.Y); }
  177. }
  178. /// <summary>
  179. /// The third column of this matrix
  180. /// </summary>
  181. public Vector4 Column2
  182. {
  183. get { return new Vector4(Row0.Z, Row1.Z, Row2.Z, Row3.Z); }
  184. }
  185. /// <summary>
  186. /// The fourth column of this matrix
  187. /// </summary>
  188. public Vector4 Column3
  189. {
  190. get { return new Vector4(Row0.W, Row1.W, Row2.W, Row3.W); }
  191. }
  192. /// <summary>
  193. /// Gets or sets the value at row 1, column 1 of this instance.
  194. /// </summary>
  195. public double M11 { get { return Row0.X; } set { Row0.X = value; } }
  196. /// <summary>
  197. /// Gets or sets the value at row 1, column 2 of this instance.
  198. /// </summary>
  199. public double M12 { get { return Row0.Y; } set { Row0.Y = value; } }
  200. /// <summary>
  201. /// Gets or sets the value at row 1, column 3 of this instance.
  202. /// </summary>
  203. public double M13 { get { return Row0.Z; } set { Row0.Z = value; } }
  204. /// <summary>
  205. /// Gets or sets the value at row 1, column 4 of this instance.
  206. /// </summary>
  207. public double M14 { get { return Row0.W; } set { Row0.W = value; } }
  208. /// <summary>
  209. /// Gets or sets the value at row 2, column 1 of this instance.
  210. /// </summary>
  211. public double M21 { get { return Row1.X; } set { Row1.X = value; } }
  212. /// <summary>
  213. /// Gets or sets the value at row 2, column 2 of this instance.
  214. /// </summary>
  215. public double M22 { get { return Row1.Y; } set { Row1.Y = value; } }
  216. /// <summary>
  217. /// Gets or sets the value at row 2, column 3 of this instance.
  218. /// </summary>
  219. public double M23 { get { return Row1.Z; } set { Row1.Z = value; } }
  220. /// <summary>
  221. /// Gets or sets the value at row 2, column 4 of this instance.
  222. /// </summary>
  223. public double M24 { get { return Row1.W; } set { Row1.W = value; } }
  224. /// <summary>
  225. /// Gets or sets the value at row 3, column 1 of this instance.
  226. /// </summary>
  227. public double M31 { get { return Row2.X; } set { Row2.X = value; } }
  228. /// <summary>
  229. /// Gets or sets the value at row 3, column 2 of this instance.
  230. /// </summary>
  231. public double M32 { get { return Row2.Y; } set { Row2.Y = value; } }
  232. /// <summary>
  233. /// Gets or sets the value at row 3, column 3 of this instance.
  234. /// </summary>
  235. public double M33 { get { return Row2.Z; } set { Row2.Z = value; } }
  236. /// <summary>
  237. /// Gets or sets the value at row 3, column 4 of this instance.
  238. /// </summary>
  239. public double M34 { get { return Row2.W; } set { Row2.W = value; } }
  240. /// <summary>
  241. /// Gets or sets the value at row 4, column 1 of this instance.
  242. /// </summary>
  243. public double M41 { get { return Row3.X; } set { Row3.X = value; } }
  244. /// <summary>
  245. /// Gets or sets the value at row 4, column 2 of this instance.
  246. /// </summary>
  247. public double M42 { get { return Row3.Y; } set { Row3.Y = value; } }
  248. /// <summary>
  249. /// Gets or sets the value at row 4, column 3 of this instance.
  250. /// </summary>
  251. public double M43 { get { return Row3.Z; } set { Row3.Z = value; } }
  252. /// <summary>
  253. /// Gets or sets the value at row 4, column 4 of this instance.
  254. /// </summary>
  255. public double M44 { get { return Row3.W; } set { Row3.W = value; } }
  256. #endregion Properties
  257. #region Instance
  258. public double this[int row, int column]
  259. {
  260. get
  261. {
  262. switch (row)
  263. {
  264. case 0:
  265. return Row0[column];
  266. case 1:
  267. return Row1[column];
  268. case 2:
  269. return Row2[column];
  270. case 3:
  271. return Row3[column];
  272. default:
  273. throw new IndexOutOfRangeException();
  274. }
  275. }
  276. set
  277. {
  278. switch (row)
  279. {
  280. case 0:
  281. Row0[column] = value;
  282. break;
  283. case 1:
  284. Row1[column] = value;
  285. break;
  286. case 2:
  287. Row2[column] = value;
  288. break;
  289. case 3:
  290. Row3[column] = value;
  291. break;
  292. default:
  293. throw new IndexOutOfRangeException();
  294. }
  295. }
  296. }
  297. public Quaternion GetRotation()
  298. {
  299. Quaternion rotation = Quaternion.Identity;
  300. double tr = M11 + M22 + M33;
  301. if (tr > 0)
  302. {
  303. double S = Math.Sqrt(tr + 1.0) * 2; // S=4*qw
  304. rotation.W = 0.25 * S;
  305. rotation.X = (M32 - M23) / S;
  306. rotation.Y = (M13 - M31) / S;
  307. rotation.Z = (M21 - M12) / S;
  308. }
  309. else if ((M11 > M22) & (M11 > M33))
  310. {
  311. double S = Math.Sqrt(1.0 + M11 - M22 - M33) * 2; // S=4*qx
  312. rotation.W = (M32 - M23) / S;
  313. rotation.X = 0.25 * S;
  314. rotation.Y = (M12 + M21) / S;
  315. rotation.Z = (M13 + M31) / S;
  316. }
  317. else if (M22 > M33)
  318. {
  319. double S = Math.Sqrt(1.0 + M22 - M11 - M33) * 2; // S=4*qy
  320. rotation.W = (M13 - M31) / S;
  321. rotation.X = (M12 + M21) / S;
  322. rotation.Y = 0.25 * S;
  323. rotation.Z = (M23 + M32) / S;
  324. }
  325. else
  326. {
  327. double S = Math.Sqrt(1.0 + M33 - M11 - M22) * 2; // S=4*qz
  328. rotation.W = (M21 - M12) / S;
  329. rotation.X = (M13 + M31) / S;
  330. rotation.Y = (M23 + M32) / S;
  331. rotation.Z = 0.25 * S;
  332. }
  333. return rotation;
  334. #if false
  335. double trace = m[0,0] + m[1, 1] + m[2, 2];
  336. if (trace > 0)
  337. {
  338. double s = 0.5 / Math.Sqrt(trace + 1.0);
  339. this.w = 0.25 / s;
  340. this.X = (m[2, 1] - m[1, 2]) * s;
  341. this.Y = (m[0, 2] - m[2, 0]) * s;
  342. this.Z = (m[1, 0] - m[0, 1]) * s;
  343. }
  344. else
  345. {
  346. if (m[0, 0] > m[1, 1] && m[0, 0] > m[2, 2])
  347. {
  348. double s = 2.0 * Math.Sqrt(1.0 + m[0, 0] - m[1, 1] - m[2, 2]);
  349. this.w = (m[2, 1] - m[1, 2]) / s;
  350. this.X = 0.25 * s;
  351. this.Y = (m[0, 1] + m[1, 0]) / s;
  352. this.Z = (m[0, 2] + m[2, 0]) / s;
  353. }
  354. else if (m[1, 1] > m[2, 2])
  355. {
  356. double s = 2.0 * Math.Sqrt(1.0 + m[1, 1] - m[0, 0] - m[2, 2]);
  357. this.w = (m[0, 2] - m[2, 0]) / s;
  358. this.X = (m[0, 1] + m[1, 0]) / s;
  359. this.Y = 0.25 * s;
  360. this.Z = (m[1, 2] + m[2, 1]) / s;
  361. }
  362. else
  363. {
  364. double s = 2.0 * Math.Sqrt(1.0 + m[2, 2] - m[0, 0] - m[1, 1]);
  365. this.w = (m[1, 0] - m[0, 1]) / s;
  366. this.X = (m[0, 2] + m[2, 0]) / s;
  367. this.Y = (m[1, 2] + m[2, 1]) / s;
  368. this.Z = 0.25 * s;
  369. }
  370. }
  371. #endif
  372. #if false
  373. Quaternion Q = new Quaternion();
  374. Q.w = Math.Sqrt(Math.Max(0, 1 + m[0, 0] + m[1, 1] + m[2, 2])) / 2;
  375. Q.X = Math.Sqrt(Math.Max(0, 1 + m[0, 0] - m[1, 1] - m[2, 2])) / 2;
  376. Q.Y = Math.Sqrt(Math.Max(0, 1 - m[0, 0] + m[1, 1] - m[2, 2])) / 2;
  377. Q.Z = Math.Sqrt(Math.Max(0, 1 - m[0, 0] - m[1, 1] + m[2, 2])) / 2;
  378. Q.X = CopySign(Q.X, m[2, 1] - m[1, 2]);
  379. Q.Y = CopySign(Q.Y, m[0, 2] - m[2, 0]);
  380. Q.Z = CopySign(Q.Z, m[1, 0] - m[0, 1]);
  381. #endif
  382. }
  383. #region public void Invert()
  384. /// <summary>
  385. /// Converts this instance into its inverse.
  386. /// </summary>
  387. public void Invert()
  388. {
  389. this = Matrix4X4.Invert(this);
  390. }
  391. public Matrix4X4 Inverted
  392. {
  393. get
  394. {
  395. var inverted = this;
  396. inverted.Invert();
  397. return inverted;
  398. }
  399. }
  400. #endregion public void Invert()
  401. #region public void Transpose()
  402. /// <summary>
  403. /// Converts this instance into its transpose.
  404. /// </summary>
  405. public void Transpose()
  406. {
  407. this = Matrix4X4.Transpose(this);
  408. }
  409. #endregion public void Transpose()
  410. public bool IsValid()
  411. {
  412. return Row0.IsValid()
  413. && Row1.IsValid()
  414. && Row2.IsValid()
  415. && Row3.IsValid();
  416. }
  417. #endregion Instance
  418. #region Static
  419. #region CreateFromAxisAngle
  420. /// <summary>
  421. /// Build a rotation matrix from the specified axis/angle rotation.
  422. /// </summary>
  423. /// <param name="axis">The axis to rotate about.</param>
  424. /// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param>
  425. /// <param name="result">A matrix instance.</param>
  426. public static void CreateFromAxisAngle(Vector3 axis, double angle, out Matrix4X4 result)
  427. {
  428. double cos = System.Math.Cos(-angle);
  429. double sin = System.Math.Sin(-angle);
  430. double t = 1.0 - cos;
  431. axis.Normalize();
  432. result = new Matrix4X4(t * axis.X * axis.X + cos, t * axis.X * axis.Y - sin * axis.Z, t * axis.X * axis.Z + sin * axis.Y, 0.0,
  433. t * axis.X * axis.Y + sin * axis.Z, t * axis.Y * axis.Y + cos, t * axis.Y * axis.Z - sin * axis.X, 0.0,
  434. t * axis.X * axis.Z - sin * axis.Y, t * axis.Y * axis.Z + sin * axis.X, t * axis.Z * axis.Z + cos, 0.0,
  435. 0, 0, 0, 1);
  436. }
  437. /// <summary>
  438. /// Build a rotation matrix from the specified axis/angle rotation.
  439. /// </summary>
  440. /// <param name="axis">The axis to rotate about.</param>
  441. /// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param>
  442. /// <returns>A matrix instance.</returns>
  443. public static Matrix4X4 CreateFromAxisAngle(Vector3 axis, double angle)
  444. {
  445. Matrix4X4 result;
  446. CreateFromAxisAngle(axis, angle, out result);
  447. return result;
  448. }
  449. #endregion CreateFromAxisAngle
  450. #region CreateRotation[XYZ]
  451. public static Matrix4X4 CreateRotation(Vector3 radians)
  452. {
  453. return Matrix4X4.CreateRotation(Quaternion.FromEulerAngles(radians));
  454. }
  455. /// <summary>
  456. /// Builds a rotation matrix for a rotation around the x-axis.
  457. /// </summary>
  458. /// <param name="angle">The counter-clockwise angle in radians.</param>
  459. /// <param name="result">The resulting Matrix4 instance.</param>
  460. public static void CreateRotationX(double angle, out Matrix4X4 result)
  461. {
  462. double cos = System.Math.Cos(angle);
  463. double sin = System.Math.Sin(angle);
  464. result.Row0 = Vector4.UnitX;
  465. result.Row1 = new Vector4(0, cos, sin, 0);
  466. result.Row2 = new Vector4(0, -sin, cos, 0);
  467. result.Row3 = Vector4.UnitW;
  468. }
  469. /// <summary>
  470. /// Builds a rotation matrix for a rotation around the x-axis.
  471. /// </summary>
  472. /// <param name="angle">The counter-clockwise angle in radians.</param>
  473. /// <returns>The resulting Matrix4 instance.</returns>
  474. public static Matrix4X4 CreateRotationX(double angle)
  475. {
  476. Matrix4X4 result;
  477. CreateRotationX(angle, out result);
  478. return result;
  479. }
  480. /// <summary>
  481. /// Builds a rotation matrix for a rotation around the y-axis.
  482. /// </summary>
  483. /// <param name="angle">The counter-clockwise angle in radians.</param>
  484. /// <param name="result">The resulting Matrix4 instance.</param>
  485. public static void CreateRotationY(double angle, out Matrix4X4 result)
  486. {
  487. double cos = System.Math.Cos(angle);
  488. double sin = System.Math.Sin(angle);
  489. result.Row0 = new Vector4(cos, 0, -sin, 0);
  490. result.Row1 = Vector4.UnitY;
  491. result.Row2 = new Vector4(sin, 0, cos, 0);
  492. result.Row3 = Vector4.UnitW;
  493. }
  494. /// <summary>
  495. /// Builds a rotation matrix for a rotation around the y-axis.
  496. /// </summary>
  497. /// <param name="angle">The counter-clockwise angle in radians.</param>
  498. /// <returns>The resulting Matrix4 instance.</returns>
  499. public static Matrix4X4 CreateRotationY(double angle)
  500. {
  501. Matrix4X4 result;
  502. CreateRotationY(angle, out result);
  503. return result;
  504. }
  505. /// <summary>
  506. /// Builds a rotation matrix for a rotation around the z-axis.
  507. /// </summary>
  508. /// <param name="angle">The counter-clockwise angle in radians.</param>
  509. /// <param name="result">The resulting Matrix4 instance.</param>
  510. public static void CreateRotationZ(double angle, out Matrix4X4 result)
  511. {
  512. double cos = System.Math.Cos(angle);
  513. double sin = System.Math.Sin(angle);
  514. result.Row0 = new Vector4(cos, sin, 0, 0);
  515. result.Row1 = new Vector4(-sin, cos, 0, 0);
  516. result.Row2 = Vector4.UnitZ;
  517. result.Row3 = Vector4.UnitW;
  518. }
  519. /// <summary>
  520. /// Builds a rotation matrix for a rotation around the z-axis.
  521. /// </summary>
  522. /// <param name="angle">The counter-clockwise angle in radians.</param>
  523. /// <returns>The resulting Matrix4 instance.</returns>
  524. public static Matrix4X4 CreateRotationZ(double angle)
  525. {
  526. Matrix4X4 result;
  527. CreateRotationZ(angle, out result);
  528. return result;
  529. }
  530. /// <summary>
  531. /// Build a rotation matrix to rotate about the given axis
  532. /// </summary>
  533. /// <param name="axis">the axis to rotate about</param>
  534. /// <param name="angle">angle in radians to rotate counter-clockwise (looking in the direction of the given axis)</param>
  535. /// <returns>A rotation matrix</returns>
  536. public static Matrix4X4 CreateRotation(Vector3 axis, double angle)
  537. {
  538. double cos = System.Math.Cos(angle);
  539. double sin = System.Math.Sin(angle);
  540. double t = 1.0 - cos;
  541. axis.Normalize();
  542. Matrix4X4 result;
  543. result.Row0 = new Vector4(t * axis.X * axis.X + cos, t * axis.X * axis.Y - sin * axis.Z, t * axis.X * axis.Z + sin * axis.Y, 0.0);
  544. result.Row1 = new Vector4(t * axis.X * axis.Y + sin * axis.Z, t * axis.Y * axis.Y + cos, t * axis.Y * axis.Z - sin * axis.X, 0.0);
  545. result.Row2 = new Vector4(t * axis.X * axis.Z - sin * axis.Y, t * axis.Y * axis.Z + sin * axis.X, t * axis.Z * axis.Z + cos, 0.0);
  546. result.Row3 = Vector4.UnitW;
  547. return result;
  548. }
  549. /// <summary>
  550. /// Build a rotation matrix from a quaternion
  551. /// </summary>
  552. /// <param name="q">the quaternion</param>
  553. /// <returns>A rotation matrix</returns>
  554. public static Matrix4X4 CreateRotation(Quaternion q)
  555. {
  556. Vector3 axis;
  557. double angle;
  558. q.ToAxisAngle(out axis, out angle);
  559. return CreateRotation(axis, angle);
  560. }
  561. /// <summary>
  562. /// Build a rotation matrix that will rotate from one direction to another
  563. /// </summary>
  564. /// <param name="startingDirection"></param>
  565. /// <param name="endingDirection"></param>
  566. /// <returns></returns>
  567. public static Matrix4X4 CreateRotation(Vector3 startingDirection, Vector3 endingDirection)
  568. {
  569. Quaternion q = new Quaternion(startingDirection, endingDirection);
  570. return CreateRotation(q);
  571. }
  572. #endregion CreateRotation[XYZ]
  573. #region CreateTranslation
  574. /// <summary>
  575. /// Creates a translation matrix.
  576. /// </summary>
  577. /// <param name="x">X translation.</param>
  578. /// <param name="y">Y translation.</param>
  579. /// <param name="z">Z translation.</param>
  580. /// <param name="result">The resulting Matrix4d instance.</param>
  581. public static void CreateTranslation(double x, double y, double z, out Matrix4X4 result)
  582. {
  583. result = Identity;
  584. result.Row3 = new Vector4(x, y, z, 1);
  585. }
  586. /// <summary>
  587. /// Creates a translation matrix.
  588. /// </summary>
  589. /// <param name="vector">The translation vector.</param>
  590. /// <param name="result">The resulting Matrix4d instance.</param>
  591. public static void CreateTranslation(ref Vector3 vector, out Matrix4X4 result)
  592. {
  593. result = Identity;
  594. result.Row3 = new Vector4(vector.X, vector.Y, vector.Z, 1);
  595. }
  596. /// <summary>
  597. /// Creates a translation matrix.
  598. /// </summary>
  599. /// <param name="x">X translation.</param>
  600. /// <param name="y">Y translation.</param>
  601. /// <param name="z">Z translation.</param>
  602. /// <returns>The resulting Matrix4d instance.</returns>
  603. public static Matrix4X4 CreateTranslation(double x, double y, double z)
  604. {
  605. Matrix4X4 result;
  606. CreateTranslation(x, y, z, out result);
  607. return result;
  608. }
  609. /// <summary>
  610. /// Creates a translation matrix.
  611. /// </summary>
  612. /// <param name="vector">The translation vector.</param>
  613. /// <returns>The resulting Matrix4d instance.</returns>
  614. public static Matrix4X4 CreateTranslation(Vector3 vector)
  615. {
  616. Matrix4X4 result;
  617. CreateTranslation(vector.X, vector.Y, vector.Z, out result);
  618. return result;
  619. }
  620. #endregion CreateTranslation
  621. #region CreateOrthographic
  622. /// <summary>
  623. /// Creates an orthographic projection matrix.
  624. /// </summary>
  625. /// <param name="width">The width of the projection volume.</param>
  626. /// <param name="height">The height of the projection volume.</param>
  627. /// <param name="zNear">The near edge of the projection volume.</param>
  628. /// <param name="zFar">The far edge of the projection volume.</param>
  629. /// <param name="result">The resulting Matrix4d instance.</param>
  630. public static void CreateOrthographic(double width, double height, double zNear, double zFar, out Matrix4X4 result)
  631. {
  632. CreateOrthographicOffCenter(-width / 2, width / 2, -height / 2, height / 2, zNear, zFar, out result);
  633. }
  634. /// <summary>
  635. /// Creates an orthographic projection matrix.
  636. /// </summary>
  637. /// <param name="width">The width of the projection volume.</param>
  638. /// <param name="height">The height of the projection volume.</param>
  639. /// <param name="zNear">The near edge of the projection volume.</param>
  640. /// <param name="zFar">The far edge of the projection volume.</param>
  641. /// <rereturns>The resulting Matrix4d instance.</rereturns>
  642. public static Matrix4X4 CreateOrthographic(double width, double height, double zNear, double zFar)
  643. {
  644. Matrix4X4 result;
  645. CreateOrthographicOffCenter(-width / 2, width / 2, -height / 2, height / 2, zNear, zFar, out result);
  646. return result;
  647. }
  648. #endregion CreateOrthographic
  649. #region CreateOrthographicOffCenter
  650. /// <summary>
  651. /// Creates an orthographic projection matrix.
  652. /// </summary>
  653. /// <param name="left">The left edge of the projection volume.</param>
  654. /// <param name="right">The right edge of the projection volume.</param>
  655. /// <param name="bottom">The bottom edge of the projection volume.</param>
  656. /// <param name="top">The top edge of the projection volume.</param>
  657. /// <param name="zNear">The near edge of the projection volume.</param>
  658. /// <param name="zFar">The far edge of the projection volume.</param>
  659. /// <param name="result">The resulting Matrix4d instance.</param>
  660. public static void CreateOrthographicOffCenter(double left, double right, double bottom, double top, double zNear, double zFar, out Matrix4X4 result)
  661. {
  662. result = new Matrix4X4();
  663. double invRL = 1 / (right - left);
  664. double invTB = 1 / (top - bottom);
  665. double invFN = 1 / (zFar - zNear);
  666. result.M11 = 2 * invRL;
  667. result.M22 = 2 * invTB;
  668. result.M33 = -2 * invFN;
  669. result.M41 = -(right + left) * invRL;
  670. result.M42 = -(top + bottom) * invTB;
  671. result.M43 = -(zFar + zNear) * invFN;
  672. result.M44 = 1;
  673. }
  674. /// <summary>
  675. /// Creates an orthographic projection matrix.
  676. /// </summary>
  677. /// <param name="left">The left edge of the projection volume.</param>
  678. /// <param name="right">The right edge of the projection volume.</param>
  679. /// <param name="bottom">The bottom edge of the projection volume.</param>
  680. /// <param name="top">The top edge of the projection volume.</param>
  681. /// <param name="zNear">The near edge of the projection volume.</param>
  682. /// <param name="zFar">The far edge of the projection volume.</param>
  683. /// <returns>The resulting Matrix4d instance.</returns>
  684. public static Matrix4X4 CreateOrthographicOffCenter(double left, double right, double bottom, double top, double zNear, double zFar)
  685. {
  686. Matrix4X4 result;
  687. CreateOrthographicOffCenter(left, right, bottom, top, zNear, zFar, out result);
  688. return result;
  689. }
  690. #endregion CreateOrthographicOffCenter
  691. #region CreatePerspectiveFieldOfView
  692. /// <summary>
  693. /// Creates a perspective projection matrix.
  694. /// </summary>
  695. /// <param name="fovYRadians">Angle of the field of view in the y direction (in radians)</param>
  696. /// <param name="aspectWidthOverHeight">Aspect ratio of the view (width / height)</param>
  697. /// <param name="zNear">Distance to the near clip plane</param>
  698. /// <param name="zFar">Distance to the far clip plane</param>
  699. /// <param name="result">A projection matrix that transforms camera space to raster space</param>
  700. /// <exception cref="System.ArgumentOutOfRangeException">
  701. /// Thrown under the following conditions:
  702. /// <list type="bullet">
  703. /// <item>fovy is zero, less than zero or larger than Math.PI</item>
  704. /// <item>aspect is negative or zero</item>
  705. /// <item>zNear is negative or zero</item>
  706. /// <item>zFar is negative or zero</item>
  707. /// <item>zNear is larger than zFar</item>
  708. /// </list>
  709. /// </exception>
  710. public static void CreatePerspectiveFieldOfView(double fovYRadians, double aspectWidthOverHeight, double zNear, double zFar, out Matrix4X4 result)
  711. {
  712. if (fovYRadians <= 0 || fovYRadians > Math.PI)
  713. throw new ArgumentOutOfRangeException("fovy");
  714. if (aspectWidthOverHeight <= 0)
  715. throw new ArgumentOutOfRangeException("aspect");
  716. if (zNear <= 0)
  717. throw new ArgumentOutOfRangeException("zNear");
  718. if (zFar <= 0)
  719. throw new ArgumentOutOfRangeException("zFar");
  720. if (zNear >= zFar)
  721. throw new ArgumentOutOfRangeException("zNear");
  722. double yMax = zNear * System.Math.Tan(0.5 * fovYRadians);
  723. double yMin = -yMax;
  724. double xMin = yMin * aspectWidthOverHeight;
  725. double xMax = yMax * aspectWidthOverHeight;
  726. CreatePerspectiveOffCenter(xMin, xMax, yMin, yMax, zNear, zFar, out result);
  727. }
  728. /// <summary>
  729. /// Creates a perspective projection matrix.
  730. /// </summary>
  731. /// <param name="fovYRadians">Angle of the field of view in the y direction (in radians)</param>
  732. /// <param name="aspectWidthOverHeight">Aspect ratio of the view (width / height)</param>
  733. /// <param name="zNear">Distance to the near clip plane</param>
  734. /// <param name="zFar">Distance to the far clip plane</param>
  735. /// <returns>A projection matrix that transforms camera space to raster space</returns>
  736. /// <exception cref="System.ArgumentOutOfRangeException">
  737. /// Thrown under the following conditions:
  738. /// <list type="bullet">
  739. /// <item>fovYRadians is zero, less than zero or larger than Math.PI</item>
  740. /// <item>aspect is negative or zero</item>
  741. /// <item>zNear is negative or zero</item>
  742. /// <item>zFar is negative or zero</item>
  743. /// <item>zNear is larger than zFar</item>
  744. /// </list>
  745. /// </exception>
  746. public static Matrix4X4 CreatePerspectiveFieldOfView(double fovYRadians, double aspectWidthOverHeight, double zNear, double zFar)
  747. {
  748. Matrix4X4 result;
  749. CreatePerspectiveFieldOfView(fovYRadians, aspectWidthOverHeight, zNear, zFar, out result);
  750. return result;
  751. }
  752. #endregion CreatePerspectiveFieldOfView
  753. #region CreatePerspectiveOffCenter
  754. /// <summary>
  755. /// Creates an perspective projection matrix.
  756. /// </summary>
  757. /// <param name="left">Left edge of the view frustum</param>
  758. /// <param name="right">Right edge of the view frustum</param>
  759. /// <param name="bottom">Bottom edge of the view frustum</param>
  760. /// <param name="top">Top edge of the view frustum</param>
  761. /// <param name="zNear">Distance to the near clip plane</param>
  762. /// <param name="zFar">Distance to the far clip plane</param>
  763. /// <param name="result">A projection matrix that transforms camera space to raster space</param>
  764. /// <exception cref="System.ArgumentOutOfRangeException">
  765. /// Thrown under the following conditions:
  766. /// <list type="bullet">
  767. /// <item>zNear is negative or zero</item>
  768. /// <item>zFar is negative or zero</item>
  769. /// <item>zNear is larger than zFar</item>
  770. /// </list>
  771. /// </exception>
  772. public static void CreatePerspectiveOffCenter(double left, double right, double bottom, double top, double zNear, double zFar, out Matrix4X4 result)
  773. {
  774. if (zNear <= 0)
  775. {
  776. throw new ArgumentOutOfRangeException("zNear");
  777. }
  778. if (zFar <= 0)
  779. {
  780. throw new ArgumentOutOfRangeException("zFar");
  781. }
  782. if (zNear >= zFar)
  783. {
  784. throw new ArgumentOutOfRangeException("zNear");
  785. }
  786. double x = (2.0 * zNear) / (right - left);
  787. double y = (2.0 * zNear) / (top - bottom);
  788. double a = (right + left) / (right - left);
  789. double b = (top + bottom) / (top - bottom);
  790. double c = -(zFar + zNear) / (zFar - zNear);
  791. double d = -(2.0 * zFar * zNear) / (zFar - zNear);
  792. result = new Matrix4X4(x, 0, 0, 0,
  793. 0, y, 0, 0,
  794. a, b, c, -1,
  795. 0, 0, d, 0);
  796. }
  797. /// <summary>
  798. /// Creates an perspective projection matrix.
  799. /// </summary>
  800. /// <param name="left">Left edge of the view frustum</param>
  801. /// <param name="right">Right edge of the view frustum</param>
  802. /// <param name="bottom">Bottom edge of the view frustum</param>
  803. /// <param name="top">Top edge of the view frustum</param>
  804. /// <param name="zNear">Distance to the near clip plane</param>
  805. /// <param name="zFar">Distance to the far clip plane</param>
  806. /// <returns>A projection matrix that transforms camera space to raster space</returns>
  807. /// <exception cref="System.ArgumentOutOfRangeException">
  808. /// Thrown under the following conditions:
  809. /// <list type="bullet">
  810. /// <item>zNear is negative or zero</item>
  811. /// <item>zFar is negative or zero</item>
  812. /// <item>zNear is larger than zFar</item>
  813. /// </list>
  814. /// </exception>
  815. public static Matrix4X4 CreatePerspectiveOffCenter(double left, double right, double bottom, double top, double zNear, double zFar)
  816. {
  817. Matrix4X4 result;
  818. CreatePerspectiveOffCenter(left, right, bottom, top, zNear, zFar, out result);
  819. return result;
  820. }
  821. #endregion CreatePerspectiveOffCenter
  822. #region CreateScale
  823. /// <summary>
  824. /// Build a scaling matrix
  825. /// </summary>
  826. /// <param name="scale">Single scale factor for x,y and z axes</param>
  827. /// <returns>A scaling matrix</returns>
  828. public static Matrix4X4 CreateScale(double scale)
  829. {
  830. return CreateScale(scale, scale, scale);
  831. }
  832. /// <summary>
  833. /// Build a scaling matrix
  834. /// </summary>
  835. /// <param name="scale">Scale factors for x,y and z axes</param>
  836. /// <returns>A scaling matrix</returns>
  837. public static Matrix4X4 CreateScale(Vector3 scale)
  838. {
  839. return CreateScale(scale.X, scale.Y, scale.Z);
  840. }
  841. /// <summary>
  842. /// Build a scaling matrix
  843. /// </summary>
  844. /// <param name="x">Scale factor for x-axis</param>
  845. /// <param name="y">Scale factor for y-axis</param>
  846. /// <param name="z">Scale factor for z-axis</param>
  847. /// <returns>A scaling matrix</returns>
  848. public static Matrix4X4 CreateScale(double x, double y, double z)
  849. {
  850. Matrix4X4 result;
  851. result.Row0 = Vector4.UnitX * x;
  852. result.Row1 = Vector4.UnitY * y;
  853. result.Row2 = Vector4.UnitZ * z;
  854. result.Row3 = Vector4.UnitW;
  855. return result;
  856. }
  857. #endregion CreateScale
  858. #region Camera Helper Functions
  859. /// <summary>
  860. /// Build a world space to camera space matrix
  861. /// </summary>
  862. /// <param name="eye">Eye (camera) position in world space</param>
  863. /// <param name="target">Target position in world space</param>
  864. /// <param name="up">Up vector in world space (should not be parallel to the camera direction, that is target - eye)</param>
  865. /// <returns>A Matrix that transforms world space to camera space</returns>
  866. public static Matrix4X4 LookAt(Vector3 eye, Vector3 target, Vector3 up)
  867. {
  868. // There are lots of examples of look at code on the internet that don't do all these normalizes and also find the position
  869. // through several dot products. The problem with them is that they have a bit of error in that all the vectors aren't normal and need to be.
  870. Vector3 z = Vector3.Normalize(eye - target);
  871. Vector3 x = Vector3.Normalize(up.Cross(z));
  872. Vector3 y = Vector3.Normalize(z.Cross(x));
  873. Matrix4X4 rot = new Matrix4X4(new Vector4(x.X, y.X, z.X, 0.0),
  874. new Vector4(x.Y, y.Y, z.Y, 0.0),
  875. new Vector4(x.Z, y.Z, z.Z, 0.0),
  876. Vector4.UnitW);
  877. Matrix4X4 trans = Matrix4X4.CreateTranslation(-eye);
  878. return trans * rot;
  879. }
  880. /// <summary>
  881. /// Build a world space to camera space matrix
  882. /// </summary>
  883. /// <param name="eyeX">Eye (camera) position in world space</param>
  884. /// <param name="eyeY">Eye (camera) position in world space</param>
  885. /// <param name="eyeZ">Eye (camera) position in world space</param>
  886. /// <param name="targetX">Target position in world space</param>
  887. /// <param name="targetY">Target position in world space</param>
  888. /// <param name="targetZ">Target position in world space</param>
  889. /// <param name="upX">Up vector in world space (should not be parallel to the camera direction, that is target - eye)</param>
  890. /// <param name="upY">Up vector in world space (should not be parallel to the camera direction, that is target - eye)</param>
  891. /// <param name="upZ">Up vector in world space (should not be parallel to the camera direction, that is target - eye)</param>
  892. /// <returns>A Matrix4 that transforms world space to camera space</returns>
  893. public static Matrix4X4 LookAt(double eyeX, double eyeY, double eyeZ, double targetX, double targetY, double targetZ, double upX, double upY, double upZ)
  894. {
  895. return LookAt(new Vector3(eyeX, eyeY, eyeZ), new Vector3(targetX, targetY, targetZ), new Vector3(upX, upY, upZ));
  896. }
  897. /// <summary>
  898. /// Build a projection matrix
  899. /// </summary>
  900. /// <param name="left">Left edge of the view frustum</param>
  901. /// <param name="right">Right edge of the view frustum</param>
  902. /// <param name="bottom">Bottom edge of the view frustum</param>
  903. /// <param name="top">Top edge of the view frustum</param>
  904. /// <param name="near">Distance to the near clip plane</param>
  905. /// <param name="far">Distance to the far clip plane</param>
  906. /// <returns>A projection matrix that transforms camera space to raster space</returns>
  907. public static Matrix4X4 Frustum(double left, double right, double bottom, double top, double near, double far)
  908. {
  909. double invRL = 1.0 / (right - left);
  910. double invTB = 1.0 / (top - bottom);
  911. double invFN = 1.0 / (far - near);
  912. return new Matrix4X4(new Vector4(2.0 * near * invRL, 0.0, 0.0, 0.0),
  913. new Vector4(0.0, 2.0 * near * invTB, 0.0, 0.0),
  914. new Vector4((right + left) * invRL, (top + bottom) * invTB, -(far + near) * invFN, -1.0),
  915. new Vector4(0.0, 0.0, -2.0 * far * near * invFN, 0.0));
  916. }
  917. /// <summary>
  918. /// Build a projection matrix
  919. /// </summary>
  920. /// <param name="fovy">Angle of the field of view in the y direction (in radians)</param>
  921. /// <param name="aspect">Aspect ratio of the view (width / height)</param>
  922. /// <param name="near">Distance to the near clip plane</param>
  923. /// <param name="far">Distance to the far clip plane</param>
  924. /// <returns>A projection matrix that transforms camera space to raster space</returns>
  925. public static Matrix4X4 Perspective(double fovy, double aspect, double near, double far)
  926. {
  927. double yMax = near * System.Math.Tan(0.5f * fovy);
  928. double yMin = -yMax;
  929. double xMin = yMin * aspect;
  930. double xMax = yMax * aspect;
  931. return Frustum(xMin, xMax, yMin, yMax, near, far);
  932. }
  933. #endregion Camera Helper Functions
  934. #region Multiply Functions
  935. /// <summary>
  936. /// Multiplies two instances.
  937. /// </summary>
  938. /// <param name="left">The left operand of the multiplication.</param>
  939. /// <param name="right">The right operand of the multiplication.</param>
  940. /// <returns>A new instance that is the result of the multiplication</returns>
  941. public static Matrix4X4 Mult(Matrix4X4 left, Matrix4X4 right)
  942. {
  943. Matrix4X4 result;
  944. Mult(ref left, ref right, out result);
  945. return result;
  946. }
  947. /// <summary>
  948. /// Multiplies two instances.
  949. /// </summary>
  950. /// <param name="left">The left operand of the multiplication.</param>
  951. /// <param name="right">The right operand of the multiplication.</param>
  952. /// <param name="result">A new instance that is the result of the multiplication</param>
  953. public static void Mult(ref Matrix4X4 left, ref Matrix4X4 right, out Matrix4X4 result)
  954. {
  955. result = new Matrix4X4();
  956. result.M11 = left.M11 * right.M11 + left.M12 * right.M21 + left.M13 * right.M31 + left.M14 * right.M41;
  957. result.M12 = left.M11 * right.M12 + left.M12 * right.M22 + left.M13 * right.M32 + left.M14 * right.M42;
  958. result.M13 = left.M11 * right.M13 + left.M12 * right.M23 + left.M13 * right.M33 + left.M14 * right.M43;
  959. result.M14 = left.M11 * right.M14 + left.M12 * right.M24 + left.M13 * right.M34 + left.M14 * right.M44;
  960. result.M21 = left.M21 * right.M11 + left.M22 * right.M21 + left.M23 * right.M31 + left.M24 * right.M41;
  961. result.M22 = left.M21 * right.M12 + left.M22 * right.M22 + left.M23 * right.M32 + left.M24 * right.M42;
  962. result.M23 = left.M21 * right.M13 + left.M22 * right.M23 + left.M23 * right.M33 + left.M24 * right.M43;
  963. result.M24 = left.M21 * right.M14 + left.M22 * right.M24 + left.M23 * right.M34 + left.M24 * right.M44;
  964. result.M31 = left.M31 * right.M11 + left.M32 * right.M21 + left.M33 * right.M31 + left.M34 * right.M41;
  965. result.M32 = left.M31 * right.M12 + left.M32 * right.M22 + left.M33 * right.M32 + left.M34 * right.M42;
  966. result.M33 = left.M31 * right.M13 + left.M32 * right.M23 + left.M33 * right.M33 + left.M34 * right.M43;
  967. result.M34 = left.M31 * right.M14 + left.M32 * right.M24 + left.M33 * right.M34 + left.M34 * right.M44;
  968. result.M41 = left.M41 * right.M11 + left.M42 * right.M21 + left.M43 * right.M31 + left.M44 * right.M41;
  969. result.M42 = left.M41 * right.M12 + left.M42 * right.M22 + left.M43 * right.M32 + left.M44 * right.M42;
  970. result.M43 = left.M41 * right.M13 + left.M42 * right.M23 + left.M43 * right.M33 + left.M44 * right.M43;
  971. result.M44 = left.M41 * right.M14 + left.M42 * right.M24 + left.M43 * right.M34 + left.M44 * right.M44;
  972. }
  973. #endregion Multiply Functions
  974. #region Invert Functions
  975. /// <summary>
  976. /// Calculate the inverse of the given matrix
  977. /// </summary>
  978. /// <param name="mat">The matrix to invert</param>
  979. /// <returns>The inverse of the given matrix if it has one, or the input if it is singular</returns>
  980. /// <exception cref="InvalidOperationException">Thrown if the Matrix4d is singular.</exception>
  981. public static Matrix4X4 Invert(Matrix4X4 mat)
  982. {
  983. // Original implementation can be found here:
  984. // https://github.com/dotnet/runtime/blob/79ae74f5ca5c8a6fe3a48935e85bd7374959c570/src/libraries/System.Private.CoreLib/src/System/Numerics/Matrix4x4.cs#L1556
  985. #pragma warning disable SA1407 // Arithmetic expressions should declare precedence
  986. double a = mat.M11, b = mat.M21, c = mat.M31, d = mat.M41;
  987. double e = mat.M12, f = mat.M22, g = mat.M32, h = mat.M42;
  988. double i = mat.M13, j = mat.M23, k = mat.M33, l = mat.M43;
  989. double m = mat.M14, n = mat.M24, o = mat.M34, p = mat.M44;
  990. double kp_lo = k * p - l * o;
  991. double jp_ln = j * p - l * n;
  992. double jo_kn = j * o - k * n;
  993. double ip_lm = i * p - l * m;
  994. double io_km = i * o - k * m;
  995. double in_jm = i * n - j * m;
  996. double a11 = +(f * kp_lo - g * jp_ln + h * jo_kn);
  997. double a12 = -(e * kp_lo - g * ip_lm + h * io_km);
  998. double a13 = +(e * jp_ln - f * ip_lm + h * in_jm);
  999. double a14 = -(e * jo_kn - f * io_km + g * in_jm);
  1000. double det = a * a11 + b * a12 + c * a13 + d * a14;
  1001. if (Math.Abs(det) < double.Epsilon)
  1002. {
  1003. #if DEBUG
  1004. throw new InvalidOperationException("Matrix is singular and cannot be inverted.");
  1005. #else
  1006. // return the input matrix rather than throw an exception (release only)
  1007. return mat;
  1008. #endif
  1009. }
  1010. double invDet = 1.0f / det;
  1011. var result = default(Matrix4X4);
  1012. result.Row0 = new Vector4(a11, a12, a13, a14) * invDet;
  1013. result.Row1 = new Vector4(
  1014. -(b * kp_lo - c * jp_ln + d * jo_kn),
  1015. +(a * kp_lo - c * ip_lm + d * io_km),
  1016. -(a * jp_ln - b * ip_lm + d * in_jm),
  1017. +(a * jo_kn - b * io_km + c * in_jm)) * invDet;
  1018. double gp_ho = g * p - h * o;
  1019. double fp_hn = f * p - h * n;
  1020. double fo_gn = f * o - g * n;
  1021. double ep_hm = e * p - h * m;
  1022. double eo_gm = e * o - g * m;
  1023. double en_fm = e * n - f * m;
  1024. result.Row2 = new Vector4(
  1025. +(b * gp_ho - c * fp_hn + d * fo_gn),
  1026. -(a * gp_ho - c * ep_hm + d * eo_gm),
  1027. +(a * fp_hn - b * ep_hm + d * en_fm),
  1028. -(a * fo_gn - b * eo_gm + c * en_fm)) * invDet;
  1029. double gl_hk = g * l - h * k;
  1030. double fl_hj = f * l - h * j;
  1031. double fk_gj = f * k - g * j;
  1032. double el_hi = e * l - h * i;
  1033. double ek_gi = e * k - g * i;
  1034. double ej_fi = e * j - f * i;
  1035. result.Row3 = new Vector4(
  1036. -(b * gl_hk - c * fl_hj + d * fk_gj),
  1037. +(a * gl_hk - c * el_hi + d * ek_gi),
  1038. -(a * fl_hj - b * el_hi + d * ej_fi),
  1039. +(a * fk_gj - b * ek_gi + c * ej_fi)) * invDet;
  1040. #pragma warning restore SA1407 // Arithmetic expressions should declare precedence
  1041. return result;
  1042. }
  1043. #endregion Invert Functions
  1044. #region Transpose
  1045. /// <summary>
  1046. /// Calculate the transpose of the given matrix
  1047. /// </summary>
  1048. /// <param name="mat">The matrix to transpose</param>
  1049. /// <returns>The transpose of the given matrix</returns>
  1050. public static Matrix4X4 Transpose(Matrix4X4 mat)
  1051. {
  1052. return new Matrix4X4(mat.Column0, mat.Column1, mat.Column2, mat.Column3);
  1053. }
  1054. /// <summary>
  1055. /// Calculate the transpose of the given matrix
  1056. /// </summary>
  1057. /// <param name="mat">The matrix to transpose</param>
  1058. /// <param name="result">The result of the calculation</param>
  1059. public static void Transpose(ref Matrix4X4 mat, out Matrix4X4 result)
  1060. {
  1061. result.Row0 = mat.Column0;
  1062. result.Row1 = mat.Column1;
  1063. result.Row2 = mat.Column2;
  1064. result.Row3 = mat.Column3;
  1065. }
  1066. #endregion Transpose
  1067. #endregion Static
  1068. #region Operators
  1069. /// <summary>
  1070. /// Matrix multiplication
  1071. /// </summary>
  1072. /// <param name="left">left-hand operand</param>
  1073. /// <param name="right">right-hand operand</param>
  1074. /// <returns>A new Matrix44 which holds the result of the multiplication</returns>
  1075. public static Matrix4X4 operator *(Matrix4X4 left, Matrix4X4 right)
  1076. {
  1077. return Matrix4X4.Mult(left, right);
  1078. }
  1079. /// <summary>
  1080. /// Compares two instances for equality.
  1081. /// </summary>
  1082. /// <param name="left">The first instance.</param>
  1083. /// <param name="right">The second instance.</param>
  1084. /// <returns>True, if left equals right; false otherwise.</returns>
  1085. public static bool operator ==(Matrix4X4 left, Matrix4X4 right)
  1086. {
  1087. return left.Equals(right);
  1088. }
  1089. /// <summary>
  1090. /// Compares two instances for inequality.
  1091. /// </summary>
  1092. /// <param name="left">The first instance.</param>
  1093. /// <param name="right">The second instance.</param>
  1094. /// <returns>True, if left does not equal right; false otherwise.</returns>
  1095. public static bool operator !=(Matrix4X4 left, Matrix4X4 right)
  1096. {
  1097. return !left.Equals(right);
  1098. }
  1099. #endregion Operators
  1100. #region Overrides
  1101. #region public override string ToString()
  1102. /// <summary>
  1103. /// Returns a System.String that represents the current Matrix44.
  1104. /// </summary>
  1105. /// <returns></returns>
  1106. public override string ToString()
  1107. {
  1108. return String.Format("{0}, \n{1}, \n{2}, \n{3}", Row0, Row1, Row2, Row3);
  1109. }
  1110. public static Matrix4X4 FromString(string values)
  1111. {
  1112. throw new NotImplementedException();
  1113. }
  1114. #endregion public override string ToString()
  1115. #region public override int GetHashCode()
  1116. /// <summary>
  1117. /// Returns the hashcode for this instance.
  1118. /// </summary>
  1119. /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns>
  1120. public override int GetHashCode()
  1121. {
  1122. return new { Row0, Row1, Row2, Row3 }.GetHashCode();
  1123. }
  1124. /// <summary>
  1125. /// return a 64 bit hash code proposed by Jon Skeet
  1126. // http://stackoverflow.com/questions/8094867/good-gethashcode-override-for-list-of-foo-objects-respecting-the-order
  1127. /// </summary>
  1128. /// <returns></returns>
  1129. public ulong GetLongHashCode(ulong hash = 14695981039346656037)
  1130. {
  1131. hash = Row0.GetLongHashCode(hash);
  1132. hash = Row1.GetLongHashCode(hash);
  1133. hash = Row2.GetLongHashCode(hash);
  1134. hash = Row3.GetLongHashCode(hash);
  1135. return hash;
  1136. }
  1137. #endregion public override int GetHashCode()
  1138. #region public override bool Equals(object obj)
  1139. /// <summary>
  1140. /// Indicates whether this instance and a specified object are equal.
  1141. /// </summary>
  1142. /// <param name="obj">The object to compare to.</param>
  1143. /// <returns>True if the instances are equal; false otherwise.</returns>
  1144. public override bool Equals(object obj)
  1145. {
  1146. if (!(obj is Matrix4X4))
  1147. return false;
  1148. return this.Equals((Matrix4X4)obj);
  1149. }
  1150. #endregion public override bool Equals(object obj)
  1151. #endregion Overrides
  1152. #endregion Public Members
  1153. #region IEquatable<Matrix4d> Members
  1154. /// <summary>Indicates whether the current matrix is equal to another matrix.</summary>
  1155. /// <param name="other">An matrix to compare with this matrix.</param>
  1156. /// <returns>true if the current matrix is equal to the matrix parameter; otherwise, false.</returns>
  1157. public bool Equals(Matrix4X4 other)
  1158. {
  1159. return
  1160. Row0 == other.Row0 &&
  1161. Row1 == other.Row1 &&
  1162. Row2 == other.Row2 &&
  1163. Row3 == other.Row3;
  1164. }
  1165. /// <summary>
  1166. /// Indicates whether this instance and a specified object are equal within an error range.
  1167. /// </summary>
  1168. /// <param name="other"></param>
  1169. /// <param name="errorRange"></param>
  1170. /// <returns></returns>
  1171. public bool Equals(Matrix4X4 other, double errorRange)
  1172. {
  1173. return
  1174. Row0.Equals(other.Row0, errorRange) &&
  1175. Row1.Equals(other.Row1, errorRange) &&
  1176. Row2.Equals(other.Row2, errorRange) &&
  1177. Row3.Equals(other.Row3, errorRange);
  1178. }
  1179. #endregion IEquatable<Matrix4d> Members
  1180. public float[] GetAsFloatArray()
  1181. {
  1182. float[] contents = new float[16];
  1183. contents[0] = (float)Row0[0]; contents[1] = (float)Row0[1]; contents[2] = (float)Row0[2]; contents[3] = (float)Row0[3];
  1184. contents[4] = (float)Row1[0]; contents[5] = (float)Row1[1]; contents[6] = (float)Row1[2]; contents[7] = (float)Row1[3];
  1185. contents[8] = (float)Row2[0]; contents[9] = (float)Row2[1]; contents[10] = (float)Row2[2]; contents[11] = (float)Row2[3];
  1186. contents[12] = (float)Row3[0]; contents[13] = (float)Row3[1]; contents[14] = (float)Row3[2]; contents[15] = (float)Row3[3];
  1187. return contents;
  1188. }
  1189. public double[] GetAsDoubleArray()
  1190. {
  1191. double[] contents = new double[16];
  1192. contents[0] = Row0[0]; contents[1] = Row0[1]; contents[2] = Row0[2]; contents[3] = Row0[3];
  1193. contents[4] = Row1[0]; contents[5] = Row1[1]; contents[6] = Row1[2]; contents[7] = Row1[3];
  1194. contents[8] = Row2[0]; contents[9] = Row2[1]; contents[10] = Row2[2]; contents[11] = Row2[3];
  1195. contents[12] = Row3[0]; contents[13] = Row3[1]; contents[14] = Row3[2]; contents[15] = Row3[3];
  1196. return contents;
  1197. }
  1198. }
  1199. #endif
  1200. }