CubismRaycaster.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /**
  2. * Copyright(c) Live2D Inc. All rights reserved.
  3. *
  4. * Use of this source code is governed by the Live2D Open Software license
  5. * that can be found at https://www.live2d.com/eula/live2d-open-software-license-agreement_en.html.
  6. */
  7. using Live2D.Cubism.Core;
  8. using Live2D.Cubism.Rendering;
  9. using System.Collections.Generic;
  10. using UnityEngine;
  11. namespace Live2D.Cubism.Framework.Raycasting
  12. {
  13. /// <summary>
  14. /// Allows casting rays against <see cref="CubismRaycastable"/>s.
  15. /// </summary>
  16. public sealed class CubismRaycaster : MonoBehaviour
  17. {
  18. /// <summary>
  19. /// <see cref="CubismRenderer"/>s with <see cref="CubismRaycastable"/>s attached.
  20. /// </summary>
  21. private CubismRenderer[] Raycastables { get; set; }
  22. /// <summary>
  23. /// <see cref="CubismRaycastablePrecision"/>s with <see cref="CubismRaycastable"/>s attached.
  24. /// </summary>
  25. private CubismRaycastablePrecision[] RaycastablePrecisions { get; set; }
  26. /// <summary>
  27. /// Refreshes the controller. Call this method after adding and/or removing <see cref="CubismRaycastable"/>.
  28. /// </summary>
  29. private void Refresh()
  30. {
  31. var candidates = this
  32. .FindCubismModel()
  33. .Drawables;
  34. // Find raycastable drawables.
  35. var raycastables = new List<CubismRenderer>();
  36. var raycastablePrecisions = new List<CubismRaycastablePrecision>();
  37. for (var i = 0; i < candidates.Length; i++)
  38. {
  39. // Skip non-raycastables.
  40. if (candidates[i].GetComponent<CubismRaycastable>() == null)
  41. {
  42. continue;
  43. }
  44. raycastables.Add(candidates[i].GetComponent<CubismRenderer>());
  45. raycastablePrecisions.Add(candidates[i].GetComponent<CubismRaycastable>().Precision);
  46. }
  47. // Cache raycastables.
  48. Raycastables = raycastables.ToArray();
  49. RaycastablePrecisions = raycastablePrecisions.ToArray();
  50. }
  51. #region Unity Event Handling
  52. /// <summary>
  53. /// Called by Unity. Makes sure cache is initialized.
  54. /// </summary>
  55. private void Start()
  56. {
  57. // Initialize cache.
  58. Refresh();
  59. }
  60. #endregion
  61. /// <summary>
  62. /// Casts a ray.
  63. /// </summary>
  64. /// <param name="origin">The origin of the ray.</param>
  65. /// <param name="direction">The direction of the ray.</param>
  66. /// <param name="result">The result of the cast.</param>
  67. /// <param name="maximumDistance">[Optional] The maximum distance of the ray.</param>
  68. /// <returns><see langword="true"/> in case of a hit; <see langword="false"/> otherwise.</returns>
  69. /// <returns>The numbers of drawables had hit</returns>
  70. public int Raycast(Vector3 origin, Vector3 direction, CubismRaycastHit[] result, float maximumDistance = 10000.0f)
  71. {
  72. return Raycast(new Ray(origin, direction), result, maximumDistance);
  73. }
  74. /// <summary>
  75. /// Casts a ray.
  76. /// </summary>
  77. /// <param name="ray"></param>
  78. /// <param name="result">The result of the cast.</param>
  79. /// <param name="maximumDistance">[Optional] The maximum distance of the ray.</param>
  80. /// <returns><see langword="true"/> in case of a hit; <see langword="false"/> otherwise.</returns>
  81. /// <returns>The numbers of drawables had hit</returns>
  82. public int Raycast(Ray ray, CubismRaycastHit[] result, float maximumDistance = 10000.0f)
  83. {
  84. var origin = ray.origin;
  85. for (var i = 0; i < result.Length; i++)
  86. {
  87. result[i] = new CubismRaycastHit();
  88. }
  89. // Cast against each raycastable.
  90. var hitCount = 0;
  91. for (var i = 0; i < Raycastables.Length; i++)
  92. {
  93. var raycastable = Raycastables[i];
  94. var precision = RaycastablePrecisions[i];
  95. if (!raycastable.enabled)
  96. {
  97. continue;
  98. }
  99. if (RaycastDrawable(origin, ray.direction.normalized, maximumDistance, precision, raycastable, out var hitPosition, out var hitNormal, out var hitTime))
  100. {
  101. CubismRaycastHit raycastHit;
  102. raycastHit.Drawable = raycastable.GetComponent<CubismDrawable>();
  103. raycastHit.Distance = hitTime * maximumDistance;
  104. raycastHit.WorldPosition = hitPosition;
  105. raycastHit.LocalPosition = transform.InverseTransformPoint(hitPosition);
  106. result[hitCount] = raycastHit;
  107. ++hitCount;
  108. // Exit if result buffer is full.
  109. if (hitCount == result.Length)
  110. {
  111. break;
  112. }
  113. }
  114. }
  115. return hitCount;
  116. }
  117. /// <summary>
  118. /// The function to perform the raycast on the drawable.
  119. /// </summary>
  120. /// <param name="origin">The origin vector of the ray.</param>
  121. /// <param name="normalizedDirection">The direction vector of the ray.</param>
  122. /// <param name="length">The max length of the ray from the origin.</param>
  123. /// <param name="precision">The precision of the raycast.</param>
  124. /// <param name="renderer">The renderer to perform the raycast.</param>
  125. /// <param name="hitPosition">The hit position of the ray.</param>
  126. /// <param name="hitNormal">The hit normal of the ray.</param>
  127. /// <param name="hitTime">The [0, 1] parameter of the ray where the hit point is between `Origin` and `Origin + Direction`.</param>
  128. /// <returns>Did the Intersection Occur.</returns>
  129. private bool RaycastDrawable(Vector3 origin, Vector3 normalizedDirection, float length, CubismRaycastablePrecision precision, CubismRenderer renderer, out Vector3 hitPosition, out Vector3 hitNormal, out float hitTime)
  130. {
  131. var bounds = renderer.Mesh.bounds;
  132. // Transform the ray into the coordinate system of the bounds to account for bounds rotation.
  133. var start = renderer.transform.InverseTransformPoint(origin);
  134. var end = renderer.transform.InverseTransformPoint(origin + normalizedDirection * length);
  135. if (!LineExtentBoxIntersection(bounds, start, end, Vector3.zero, out hitPosition, out hitNormal, out hitTime))
  136. {
  137. return false;
  138. }
  139. // Convert the hit location back to the global coordinate system.
  140. hitPosition = renderer.transform.TransformPoint(hitPosition);
  141. switch (precision)
  142. {
  143. case CubismRaycastablePrecision.BoundingBox:
  144. {
  145. // already checked
  146. break;
  147. }
  148. case CubismRaycastablePrecision.Triangles:
  149. {
  150. var indices = renderer.Mesh.triangles;
  151. var positions = new Vector3[renderer.Mesh.vertices.Length];
  152. for (var i = 0; i < renderer.Mesh.vertices.Length; i++)
  153. {
  154. positions[i] = renderer.transform.TransformPoint(renderer.Mesh.vertices[i]);
  155. }
  156. if (!RayIntersectMesh(origin, normalizedDirection, length, positions, indices, out hitPosition, out hitTime))
  157. {
  158. return false;
  159. }
  160. break;
  161. }
  162. default:
  163. {
  164. return false;
  165. }
  166. }
  167. return true;
  168. }
  169. /// <summary>
  170. /// The function to check the intersection between the ray and the mesh.
  171. /// </summary>
  172. /// <param name="origin">The origin vector of the ray.</param>
  173. /// <param name="direction">The direction vector of the ray.</param>
  174. /// <param name="length">The max length of the ray from the origin.</param>
  175. /// <param name="positions">The vertex positions of the mesh.</param>
  176. /// <param name="indices">The vertex indices of the mesh.</param>
  177. /// <param name="hitPosition">The hit position of the ray.</param>
  178. /// <param name="hitTime">The [0, 1] parameter of the ray where the hit point is between `Start` and `End`.</param>
  179. /// <returns>Did the Intersection Occur.</returns>
  180. private bool RayIntersectMesh(Vector3 origin, Vector3 direction, float length, IReadOnlyList<Vector3> positions, int[] indices, out Vector3 hitPosition, out float hitTime)
  181. {
  182. hitPosition = Vector3.zero;
  183. hitTime = 0.0f;
  184. for (var i = 0; i < indices.Length; i += 3)
  185. {
  186. var t0 = positions[indices[i]];
  187. var t1 = positions[indices[i + 1]];
  188. var t2 = positions[indices[i + 2]];
  189. if (RayIntersectTriangle(origin, direction, length, t0, t1, t2, out hitPosition, out hitTime))
  190. {
  191. return true;
  192. }
  193. }
  194. return false;
  195. }
  196. /// <summary>
  197. /// The function to check the intersection between the ray and the triangle.
  198. /// </summary>
  199. /// <param name="origin">The origin vector of the ray.</param>
  200. /// <param name="direction">The direction vector of the ray.</param>
  201. /// <param name="length">The max length of the ray from the origin.</param>
  202. /// <param name="t0">The first vertex of the triangle.</param>
  203. /// <param name="t1">The second vertex of the triangle.</param>
  204. /// <param name="t2">The third vertex of the triangle.</param>
  205. /// <param name="hitPosition">The hit position of the ray.</param>
  206. /// <param name="hitTime">The [0, 1] parameter of the ray where the hit point is between `Start` and `End`.</param>
  207. /// <returns>Did the Intersection Occur.</returns>
  208. private bool RayIntersectTriangle(Vector3 origin, Vector3 direction, float length, Vector3 t0, Vector3 t1, Vector3 t2, out Vector3 hitPosition, out float hitTime)
  209. {
  210. hitPosition = Vector3.zero;
  211. hitTime = 0.0f;
  212. var e1 = t1 - t0;
  213. var e2 = t2 - t0;
  214. var p = Vector3.Cross(direction, e2);
  215. var det = Vector3.Dot(e1, p);
  216. if (Mathf.Approximately(det, 0))
  217. {
  218. return false;
  219. }
  220. var invDet = 1.0f / det;
  221. var t = origin - t0;
  222. var u = Vector3.Dot(t, p) * invDet;
  223. if (u < 0.0f || u > 1.0f)
  224. {
  225. return false;
  226. }
  227. var q = Vector3.Cross(t, e1);
  228. var v = Vector3.Dot(direction, q) * invDet;
  229. if (v < 0.0f || u + v > 1.0f)
  230. {
  231. return false;
  232. }
  233. var w = Vector3.Dot(e2, q) * invDet;
  234. hitTime = w / length;
  235. if (hitTime < 0.0f || hitTime > 1.0f)
  236. {
  237. return false;
  238. }
  239. hitPosition = origin + direction * w;
  240. return true;
  241. }
  242. /// <summary>
  243. /// Line-extent/Box Test Util
  244. /// </summary>
  245. /// <param name="inBox">The box bounds.</param>
  246. /// <param name="start">Start of line segment.</param>
  247. /// <param name="end">End of line segment.</param>
  248. /// <param name="extent">The box bounds extent.</param>
  249. /// <param name="hitLocation">The hit position of the ray.</param>
  250. /// <param name="hitNormal">The hit normal of the ray.</param>
  251. /// <param name="hitTime">The [0, 1] parameter of the ray where the hit point is between `Origin` and `Origin + Direction`.</param>
  252. /// <returns></returns>
  253. private static bool LineExtentBoxIntersection(Bounds inBox, Vector3 start, Vector3 end, Vector3 extent, out Vector3 hitLocation, out Vector3 hitNormal, out float hitTime)
  254. {
  255. hitLocation = Vector3.zero;
  256. hitNormal = Vector3.zero;
  257. hitTime = 0.0f;
  258. var box = inBox;
  259. box.max += extent;
  260. box.min -= extent;
  261. var direction = (end - start);
  262. Vector3 time;
  263. var inside = true;
  264. var faceDirection = Vector3.one;
  265. if (start.x < box.min.x)
  266. {
  267. if (direction.x <= 0.0f)
  268. {
  269. return false;
  270. }
  271. else
  272. {
  273. inside = false;
  274. faceDirection[0] = -1;
  275. time.x = (box.min.x - start.x) / direction.x;
  276. }
  277. }
  278. else if (start.x > box.max.x)
  279. {
  280. if (direction.x >= 0.0f)
  281. {
  282. return false;
  283. }
  284. else
  285. {
  286. inside = false;
  287. time.x = (box.max.x - start.x) / direction.x;
  288. }
  289. }
  290. else
  291. {
  292. time.x = 0.0f;
  293. }
  294. if (start.y < box.min.y)
  295. {
  296. if (direction.y <= 0.0f)
  297. {
  298. return false;
  299. }
  300. else
  301. {
  302. inside = false;
  303. faceDirection[1] = -1;
  304. time.y = (box.min.y - start.y) / direction.y;
  305. }
  306. }
  307. else if (start.y > box.max.y)
  308. {
  309. if (direction.y >= 0.0f)
  310. {
  311. return false;
  312. }
  313. else
  314. {
  315. inside = false;
  316. time.y = (box.max.y - start.y) / direction.y;
  317. }
  318. }
  319. else
  320. {
  321. time.y = 0.0f;
  322. }
  323. if (start.z < box.min.z)
  324. {
  325. if (direction.z <= 0.0f)
  326. {
  327. return false;
  328. }
  329. else
  330. {
  331. inside = false;
  332. faceDirection[2] = -1;
  333. time.z = (box.min.z - start.z) / direction.z;
  334. }
  335. }
  336. else if (start.z > box.max.z)
  337. {
  338. if (direction.z >= 0.0f)
  339. {
  340. return false;
  341. }
  342. else
  343. {
  344. inside = false;
  345. time.z = (box.max.z - start.z) / direction.z;
  346. }
  347. }
  348. else
  349. {
  350. time.z = 0.0f;
  351. }
  352. // If the line started inside the box (ie. player started in contact with the fluid)
  353. if (inside)
  354. {
  355. hitLocation = start;
  356. hitNormal.z = 0;
  357. return true;
  358. }
  359. // Otherwise, calculate when hit occured
  360. else
  361. {
  362. if (time.y > time.z)
  363. {
  364. hitTime = time.y;
  365. hitNormal.y = faceDirection[1];
  366. }
  367. else
  368. {
  369. hitTime = time.z;
  370. hitNormal.z = faceDirection[2];
  371. }
  372. if (time.x > hitTime)
  373. {
  374. hitTime = time.x;
  375. hitNormal.x = faceDirection[0];
  376. }
  377. if (hitTime >= 0.0f && hitTime <= 1.0f)
  378. {
  379. hitLocation = start + direction * hitTime;
  380. const float BOX_SIDE_THRESHOLD = 0.1f;
  381. if (hitLocation.x > box.min.x - BOX_SIDE_THRESHOLD && hitLocation.x < box.max.x + BOX_SIDE_THRESHOLD &&
  382. hitLocation.y > box.min.y - BOX_SIDE_THRESHOLD && hitLocation.y < box.max.y + BOX_SIDE_THRESHOLD &&
  383. hitLocation.z > box.min.z - BOX_SIDE_THRESHOLD && hitLocation.z < box.max.z + BOX_SIDE_THRESHOLD)
  384. {
  385. return true;
  386. }
  387. }
  388. return false;
  389. }
  390. }
  391. }
  392. }