MeshBender.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. using UnityEngine;
  2. using UnityEditor;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. namespace SplineMesh {
  7. /// <summary>
  8. /// A component that creates a deformed mesh from a given one along the given spline segment.
  9. /// The source mesh will always be bended along the X axis.
  10. /// It can work on a cubic bezier curve or on any interval of a given spline.
  11. /// On the given interval, the mesh can be place with original scale, stretched, or repeated.
  12. /// The resulting mesh is stored in a MeshFilter component and automaticaly updated on the next update if the spline segment change.
  13. /// </summary>
  14. [DisallowMultipleComponent]
  15. [RequireComponent(typeof(MeshFilter))]
  16. [ExecuteInEditMode]
  17. public class MeshBender : MonoBehaviour {
  18. private bool isDirty = false;
  19. private Mesh result;
  20. private bool useSpline;
  21. private Spline spline;
  22. private float intervalStart, intervalEnd;
  23. private CubicBezierCurve curve;
  24. private Dictionary<float, CurveSample> sampleCache = new Dictionary<float, CurveSample>();
  25. private SourceMesh source;
  26. /// <summary>
  27. /// The source mesh to bend.
  28. /// </summary>
  29. public SourceMesh Source {
  30. get { return source; }
  31. set {
  32. if (value == source) return;
  33. SetDirty();
  34. source = value;
  35. }
  36. }
  37. private FillingMode mode = FillingMode.StretchToInterval;
  38. /// <summary>
  39. /// The scaling mode along the spline
  40. /// </summary>
  41. public FillingMode Mode {
  42. get { return mode; }
  43. set {
  44. if (value == mode) return;
  45. SetDirty();
  46. mode = value;
  47. }
  48. }
  49. /// <summary>
  50. /// Sets a curve along which the mesh will be bent.
  51. /// The mesh will be updated if the curve changes.
  52. /// </summary>
  53. /// <param name="curve">The <see cref="CubicBezierCurve"/> to bend the source mesh along.</param>
  54. public void SetInterval(CubicBezierCurve curve) {
  55. if (this.curve == curve) return;
  56. if (curve == null) throw new ArgumentNullException("curve");
  57. if (this.curve != null) {
  58. this.curve.Changed.RemoveListener(SetDirty);
  59. }
  60. this.curve = curve;
  61. spline = null;
  62. curve.Changed.AddListener(SetDirty);
  63. useSpline = false;
  64. SetDirty();
  65. }
  66. /// <summary>
  67. /// Sets a spline's interval along which the mesh will be bent.
  68. /// If interval end is absent or set to 0, the interval goes from start to spline length.
  69. /// The mesh will be update if any of the curve changes on the spline, including curves
  70. /// outside the given interval.
  71. /// </summary>
  72. /// <param name="spline">The <see cref="SplineMesh"/> to bend the source mesh along.</param>
  73. /// <param name="intervalStart">Distance from the spline start to place the mesh minimum X.<param>
  74. /// <param name="intervalEnd">Distance from the spline start to stop deforming the source mesh.</param>
  75. public void SetInterval(Spline spline, float intervalStart, float intervalEnd = 0) {
  76. if (this.spline == spline && this.intervalStart == intervalStart && this.intervalEnd == intervalEnd) return;
  77. if (spline == null) throw new ArgumentNullException("spline");
  78. if (intervalStart < 0 || intervalStart >= spline.Length) {
  79. throw new ArgumentOutOfRangeException("interval start must be 0 or greater and lesser than spline length (was " + intervalStart + ")");
  80. }
  81. if (intervalEnd != 0 && intervalEnd <= intervalStart || intervalEnd > spline.Length) {
  82. throw new ArgumentOutOfRangeException("interval end must be 0 or greater than interval start, and lesser than spline length (was " + intervalEnd + ")");
  83. }
  84. if (this.spline != null) {
  85. // unlistening previous spline
  86. this.spline.CurveChanged.RemoveListener(SetDirty);
  87. }
  88. this.spline = spline;
  89. // listening new spline
  90. spline.CurveChanged.AddListener(SetDirty);
  91. curve = null;
  92. this.intervalStart = intervalStart;
  93. this.intervalEnd = intervalEnd;
  94. useSpline = true;
  95. SetDirty();
  96. }
  97. private void OnEnable() {
  98. if(GetComponent<MeshFilter>().sharedMesh != null) {
  99. result = GetComponent<MeshFilter>().sharedMesh;
  100. } else {
  101. GetComponent<MeshFilter>().sharedMesh = result = new Mesh();
  102. result.name = "Generated by " + GetType().Name;
  103. }
  104. }
  105. private void LateUpdate() {
  106. ComputeIfNeeded();
  107. }
  108. public void ComputeIfNeeded() {
  109. if (isDirty) {
  110. Compute();
  111. }
  112. }
  113. private void SetDirty() {
  114. isDirty = true;
  115. }
  116. /// <summary>
  117. /// Bend the mesh. This method may take time and should not be called more than necessary.
  118. /// Consider using <see cref="ComputeIfNeeded"/> for faster result.
  119. /// </summary>
  120. private void Compute() {
  121. isDirty = false;
  122. switch (Mode) {
  123. case FillingMode.Once:
  124. FillOnce();
  125. break;
  126. case FillingMode.Repeat:
  127. FillRepeat();
  128. break;
  129. case FillingMode.StretchToInterval:
  130. FillStretch();
  131. break;
  132. }
  133. }
  134. private void OnDestroy() {
  135. if(curve != null) {
  136. curve.Changed.RemoveListener(Compute);
  137. }
  138. }
  139. /// <summary>
  140. /// The mode used by <see cref="MeshBender"/> to bend meshes on the interval.
  141. /// </summary>
  142. public enum FillingMode {
  143. /// <summary>
  144. /// In this mode, source mesh will be placed on the interval by preserving mesh scale.
  145. /// Vertices that are beyond interval end will be placed on the interval end.
  146. /// </summary>
  147. Once,
  148. /// <summary>
  149. /// In this mode, the mesh will be repeated to fill the interval, preserving
  150. /// mesh scale.
  151. /// This filling process will stop when the remaining space is not enough to
  152. /// place a whole mesh, leading to an empty interval.
  153. /// </summary>
  154. Repeat,
  155. /// <summary>
  156. /// In this mode, the mesh is deformed along the X axis to fill exactly the interval.
  157. /// </summary>
  158. StretchToInterval
  159. }
  160. private void FillOnce() {
  161. sampleCache.Clear();
  162. var bentVertices = new List<MeshVertex>(source.Vertices.Count);
  163. // for each mesh vertex, we found its projection on the curve
  164. foreach (var vert in source.Vertices) {
  165. float distance = vert.position.x - source.MinX;
  166. CurveSample sample;
  167. if (!sampleCache.TryGetValue(distance, out sample)) {
  168. if (!useSpline) {
  169. if (distance > curve.Length) distance = curve.Length;
  170. sample = curve.GetSampleAtDistance(distance);
  171. } else {
  172. float distOnSpline = intervalStart + distance;
  173. if (distOnSpline > spline.Length) {
  174. if (spline.IsLoop) {
  175. while (distOnSpline > spline.Length) {
  176. distOnSpline -= spline.Length;
  177. }
  178. } else {
  179. distOnSpline = spline.Length;
  180. }
  181. }
  182. sample = spline.GetSampleAtDistance(distOnSpline);
  183. }
  184. sampleCache[distance] = sample;
  185. }
  186. bentVertices.Add(sample.GetBent(vert));
  187. }
  188. MeshUtility.Update(result,
  189. source.Mesh,
  190. source.Triangles,
  191. bentVertices.Select(b => b.position),
  192. bentVertices.Select(b => b.normal));
  193. }
  194. private void FillRepeat() {
  195. float intervalLength = useSpline?
  196. (intervalEnd == 0 ? spline.Length : intervalEnd) - intervalStart :
  197. curve.Length;
  198. int repetitionCount = Mathf.FloorToInt(intervalLength / source.Length);
  199. // building triangles and UVs for the repeated mesh
  200. var triangles = new List<int>();
  201. var uv = new List<Vector2>();
  202. var uv2 = new List<Vector2>();
  203. var uv3 = new List<Vector2>();
  204. var uv4 = new List<Vector2>();
  205. var uv5 = new List<Vector2>();
  206. var uv6 = new List<Vector2>();
  207. var uv7 = new List<Vector2>();
  208. var uv8 = new List<Vector2>();
  209. for (int i = 0; i < repetitionCount; i++) {
  210. foreach (var index in source.Triangles) {
  211. triangles.Add(index + source.Vertices.Count * i);
  212. }
  213. uv.AddRange(source.Mesh.uv);
  214. uv2.AddRange(source.Mesh.uv2);
  215. uv3.AddRange(source.Mesh.uv3);
  216. uv4.AddRange(source.Mesh.uv4);
  217. #if UNITY_2018_2_OR_NEWER
  218. uv5.AddRange(source.Mesh.uv5);
  219. uv6.AddRange(source.Mesh.uv6);
  220. uv7.AddRange(source.Mesh.uv7);
  221. uv8.AddRange(source.Mesh.uv8);
  222. #endif
  223. }
  224. // computing vertices and normals
  225. var bentVertices = new List<MeshVertex>(source.Vertices.Count);
  226. float offset = 0;
  227. for (int i = 0; i < repetitionCount; i++) {
  228. sampleCache.Clear();
  229. // for each mesh vertex, we found its projection on the curve
  230. foreach (var vert in source.Vertices) {
  231. float distance = vert.position.x - source.MinX + offset;
  232. CurveSample sample;
  233. if (!sampleCache.TryGetValue(distance, out sample)) {
  234. if (!useSpline) {
  235. if (distance > curve.Length) continue;
  236. sample = curve.GetSampleAtDistance(distance);
  237. } else {
  238. float distOnSpline = intervalStart + distance;
  239. //if (true) { //spline.isLoop) {
  240. while (distOnSpline > spline.Length) {
  241. distOnSpline -= spline.Length;
  242. }
  243. //} else if (distOnSpline > spline.Length) {
  244. // continue;
  245. //}
  246. sample = spline.GetSampleAtDistance(distOnSpline);
  247. }
  248. sampleCache[distance] = sample;
  249. }
  250. bentVertices.Add(sample.GetBent(vert));
  251. }
  252. offset += source.Length;
  253. }
  254. MeshUtility.Update(result,
  255. source.Mesh,
  256. triangles,
  257. bentVertices.Select(b => b.position),
  258. bentVertices.Select(b => b.normal),
  259. uv,
  260. uv2,
  261. uv3,
  262. uv4,
  263. uv5,
  264. uv6,
  265. uv7,
  266. uv8);
  267. }
  268. private void FillStretch() {
  269. var bentVertices = new List<MeshVertex>(source.Vertices.Count);
  270. sampleCache.Clear();
  271. // for each mesh vertex, we found its projection on the curve
  272. foreach (var vert in source.Vertices) {
  273. float distanceRate = source.Length == 0 ? 0 : Math.Abs(vert.position.x - source.MinX) / source.Length;
  274. CurveSample sample;
  275. if (!sampleCache.TryGetValue(distanceRate, out sample)) {
  276. if (!useSpline) {
  277. sample = curve.GetSampleAtDistance(curve.Length * distanceRate);
  278. } else {
  279. float intervalLength = intervalEnd == 0 ? spline.Length - intervalStart : intervalEnd - intervalStart;
  280. float distOnSpline = intervalStart + intervalLength * distanceRate;
  281. if(distOnSpline > spline.Length) {
  282. distOnSpline = spline.Length;
  283. Debug.Log("dist " + distOnSpline + " spline length " + spline.Length + " start " + intervalStart);
  284. }
  285. sample = spline.GetSampleAtDistance(distOnSpline);
  286. }
  287. sampleCache[distanceRate] = sample;
  288. }
  289. bentVertices.Add(sample.GetBent(vert));
  290. }
  291. MeshUtility.Update(result,
  292. source.Mesh,
  293. source.Triangles,
  294. bentVertices.Select(b => b.position),
  295. bentVertices.Select(b => b.normal));
  296. if (TryGetComponent(out MeshCollider collider)) {
  297. collider.sharedMesh = result;
  298. }
  299. }
  300. }
  301. }