MeshUtility.cs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. // Magica Cloth.
  2. // Copyright (c) MagicaSoft, 2020-2022.
  3. // https://magicasoft.jp
  4. using System.Collections.Generic;
  5. using Unity.Mathematics;
  6. using UnityEngine;
  7. namespace MagicaCloth
  8. {
  9. public static class MeshUtility
  10. {
  11. /// <summary>
  12. /// SkinnedMeshRendererをMeshRendererに変換する
  13. /// </summary>
  14. /// <param name="sren"></param>
  15. /// <param name="replaceSkinnedMeshRenderer">trueの場合は置き換え、falseの場合は子のオブジェクトを生成して追加する</param>
  16. /// <returns></returns>
  17. public static GameObject ReplaceSkinnedMeshRendererToMeshRenderer(SkinnedMeshRenderer sren, bool replaceSkinnedMeshRenderer)
  18. {
  19. var obj = sren.gameObject;
  20. sren.enabled = false;
  21. GameObject copyobj = obj;
  22. if (replaceSkinnedMeshRenderer == false)
  23. {
  24. // 子のオブジェクトとして追加
  25. copyobj = new GameObject(obj.name + "[work mesh]");
  26. // transform
  27. var t = copyobj.transform;
  28. t.SetParent(obj.transform);
  29. t.localPosition = Vector3.zero;
  30. t.localRotation = Quaternion.identity;
  31. t.localScale = Vector3.one;
  32. }
  33. // mesh filter
  34. var meshFilter = copyobj.AddComponent<MeshFilter>();
  35. meshFilter.sharedMesh = sren.sharedMesh;
  36. // mesh renderer
  37. var mren = copyobj.AddComponent<MeshRenderer>();
  38. mren.sharedMaterials = sren.sharedMaterials;
  39. mren.lightProbeUsage = sren.lightProbeUsage;
  40. mren.probeAnchor = sren.probeAnchor;
  41. mren.reflectionProbeUsage = sren.reflectionProbeUsage;
  42. mren.shadowCastingMode = sren.shadowCastingMode;
  43. mren.receiveShadows = sren.receiveShadows;
  44. mren.motionVectorGenerationMode = sren.motionVectorGenerationMode;
  45. mren.allowOcclusionWhenDynamic = sren.allowOcclusionWhenDynamic;
  46. if (replaceSkinnedMeshRenderer)
  47. {
  48. // SkinnedMeshRendererを削除
  49. GameObject.Destroy(sren);
  50. }
  51. return copyobj;
  52. }
  53. /// <summary>
  54. /// メッシュデータから頂点/法線/接線をワールド座標変換して返す
  55. /// </summary>
  56. /// <param name="meshData"></param>
  57. /// <param name="boneList"></param>
  58. /// <param name="wposList"></param>
  59. /// <param name="wnorList"></param>
  60. /// <param name="wtanList"></param>
  61. /// <returns></returns>
  62. public static bool CalcMeshWorldPositionNormalTangent(
  63. MeshData meshData, List<Transform> boneList,
  64. out List<Vector3> wposList, out List<Vector3> wnorList, out List<Vector3> wtanList
  65. )
  66. {
  67. wposList = new List<Vector3>();
  68. wnorList = new List<Vector3>();
  69. wtanList = new List<Vector3>();
  70. if (meshData == null || boneList == null)
  71. return false;
  72. if (meshData.isSkinning == false)
  73. {
  74. // 通常メッシュ
  75. Transform t = boneList[0];
  76. for (int i = 0; i < meshData.VertexCount; i++)
  77. {
  78. // 頂点スキニング
  79. var vw = meshData.vertexWeightList[i];
  80. Vector3 wpos = t.TransformPoint(vw.localPos);
  81. Vector3 wnor = t.TransformDirection(vw.localNor);
  82. Vector3 wtan = t.TransformDirection(vw.localTan);
  83. wposList.Add(wpos);
  84. wnorList.Add(wnor);
  85. wtanList.Add(wtan);
  86. }
  87. }
  88. else
  89. {
  90. // スキンメッシュ
  91. float[] weights = new float[4];
  92. int[] boneIndexs = new int[4];
  93. for (int i = 0; i < meshData.VertexCount; i++)
  94. {
  95. Vector3 wpos = Vector3.zero;
  96. Vector3 wnor = Vector3.zero;
  97. Vector3 wtan = Vector3.zero;
  98. // 頂点スキニング
  99. uint pack = meshData.vertexInfoList[i];
  100. int wcnt = DataUtility.Unpack4_28Hi(pack);
  101. int sindex = DataUtility.Unpack4_28Low(pack);
  102. for (int j = 0; j < wcnt; j++)
  103. {
  104. var vw = meshData.vertexWeightList[sindex + j];
  105. Transform t = boneList[vw.parentIndex];
  106. wpos += t.TransformPoint(vw.localPos) * vw.weight;
  107. wnor += t.TransformDirection(vw.localNor) * vw.weight;
  108. wtan += t.TransformDirection(vw.localTan) * vw.weight;
  109. }
  110. wposList.Add(wpos);
  111. wnorList.Add(wnor);
  112. wtanList.Add(wtan);
  113. }
  114. }
  115. return true;
  116. }
  117. /// <summary>
  118. /// メッシュの頂点/法線/接線をワールド座標変換して返す
  119. /// </summary>
  120. /// <param name="ren"></param>
  121. /// <param name="mesh"></param>
  122. /// <param name="wposList"></param>
  123. /// <param name="wnorList"></param>
  124. /// <param name="wtanList"></param>
  125. /// <returns></returns>
  126. public static bool CalcMeshWorldPositionNormalTangent(
  127. Renderer ren, Mesh mesh, out List<Vector3> wposList, out List<Vector3> wnorList, out List<Vector3> wtanList
  128. )
  129. {
  130. wposList = new List<Vector3>();
  131. wnorList = new List<Vector3>();
  132. wtanList = new List<Vector3>();
  133. if (ren == null || mesh == null)
  134. return false;
  135. int vcnt = mesh.vertexCount;
  136. Vector3[] vlist = mesh.vertices;
  137. Vector3[] nlist = mesh.normals;
  138. bool hasNormal = nlist != null && nlist.Length > 0;
  139. Vector4[] tlist = mesh.tangents;
  140. bool hasTangent = tlist != null && tlist.Length > 0;
  141. if (ren is MeshRenderer)
  142. {
  143. // 通常メッシュ
  144. Transform t = ren.transform;
  145. for (int i = 0; i < vcnt; i++)
  146. {
  147. Vector3 wpos = t.TransformPoint(vlist[i]);
  148. wposList.Add(wpos);
  149. if (hasNormal)
  150. {
  151. Vector3 wnor = t.TransformDirection(nlist[i]);
  152. wnor.Normalize();
  153. wnorList.Add(wnor);
  154. }
  155. if (hasTangent)
  156. {
  157. Vector3 wtan = t.TransformDirection(tlist[i]);
  158. wtan.Normalize();
  159. wtanList.Add(wtan);
  160. }
  161. }
  162. }
  163. else if (ren is SkinnedMeshRenderer)
  164. {
  165. // スキンメッシュ
  166. SkinnedMeshRenderer sren = ren as SkinnedMeshRenderer;
  167. Transform[] boneList = sren.bones;
  168. Matrix4x4[] bindposeList = mesh.bindposes;
  169. BoneWeight[] boneWeightList = mesh.boneWeights;
  170. float[] weights = new float[4];
  171. int[] boneIndexs = new int[4];
  172. for (int i = 0; i < vcnt; i++)
  173. {
  174. Vector3 wpos = Vector3.zero;
  175. Vector3 wnor = Vector3.zero;
  176. Vector3 wtan = Vector3.zero;
  177. // 頂点スキニング
  178. weights[0] = boneWeightList[i].weight0;
  179. weights[1] = boneWeightList[i].weight1;
  180. weights[2] = boneWeightList[i].weight2;
  181. weights[3] = boneWeightList[i].weight3;
  182. boneIndexs[0] = boneWeightList[i].boneIndex0;
  183. boneIndexs[1] = boneWeightList[i].boneIndex1;
  184. boneIndexs[2] = boneWeightList[i].boneIndex2;
  185. boneIndexs[3] = boneWeightList[i].boneIndex3;
  186. for (int j = 0; j < 4; j++)
  187. {
  188. float w = weights[j];
  189. if (w > 0.0f)
  190. {
  191. int bindex = boneIndexs[j];
  192. Transform t = boneList[bindex];
  193. // position
  194. Vector3 v = bindposeList[bindex].MultiplyPoint3x4(vlist[i]);
  195. v = t.TransformPoint(v);
  196. v *= w;
  197. wpos += v;
  198. // normal
  199. if (hasNormal)
  200. {
  201. v = bindposeList[bindex].MultiplyVector(nlist[i]);
  202. v = t.TransformVector(v);
  203. wnor += v.normalized * w;
  204. }
  205. // tangent
  206. if (hasTangent)
  207. {
  208. v = bindposeList[bindex].MultiplyVector(tlist[i]);
  209. v = t.TransformVector(v);
  210. wtan += v.normalized * w;
  211. }
  212. }
  213. }
  214. wposList.Add(wpos);
  215. if (hasNormal)
  216. wnorList.Add(wnor);
  217. if (hasTangent)
  218. wtanList.Add(wtan);
  219. }
  220. }
  221. return true;
  222. }
  223. #if false
  224. /// <summary>
  225. /// メッシュの頂点/回転をワールド座標変換して返す
  226. /// 回転は法線をforwardベクトル,接線をupベクトルとして計算
  227. /// </summary>
  228. /// <param name="ren"></param>
  229. /// <param name="mesh"></param>
  230. /// <param name="wposList"></param>
  231. /// <param name="wrotList"></param>
  232. /// <returns></returns>
  233. public static bool CalcMeshWorldPositionRotation(
  234. Renderer ren, Mesh mesh, out List<Vector3> wposList, out List<Quaternion> wrotList
  235. )
  236. {
  237. wrotList = new List<Quaternion>();
  238. List<Vector3> wnorList;
  239. List<Vector4> wtanList;
  240. if (CalcMeshWorldPositionNormalTangent(ren, mesh, out wposList, out wnorList, out wtanList) == false)
  241. return false;
  242. for (int i = 0; i < wposList.Count; i++)
  243. {
  244. Quaternion rot = Quaternion.LookRotation(wnorList[i], wtanList[i]);
  245. wrotList.Add(rot);
  246. }
  247. return true;
  248. }
  249. #endif
  250. /// <summary>
  251. /// メッシュのローカル法線/接線を座標とUV値から一般的なアルゴリズムで算出して返す
  252. /// </summary>
  253. /// <param name="ren"></param>
  254. /// <param name="mesh"></param>
  255. /// <param name="wposList"></param>
  256. /// <param name="wnorList"></param>
  257. /// <param name="wtanList"></param>
  258. /// <returns></returns>
  259. public static bool CalcMeshLocalNormalTangent(
  260. List<int> selectList,
  261. Vector3[] vlist, Vector2[] uvlist, int[] triangles,
  262. out List<Vector3> lnorList, out List<Vector3> ltanList
  263. )
  264. {
  265. lnorList = new List<Vector3>();
  266. ltanList = new List<Vector3>();
  267. int vcnt = vlist.Length;
  268. int tcnt = triangles.Length / 3;
  269. for (int i = 0; i < vcnt; i++)
  270. {
  271. lnorList.Add(Vector3.zero);
  272. ltanList.Add(Vector3.zero);
  273. }
  274. // 法線算出
  275. for (int i = 0; i < tcnt; i++)
  276. {
  277. int index = i * 3;
  278. int i1 = triangles[index];
  279. int i2 = triangles[index + 1];
  280. int i3 = triangles[index + 2];
  281. var v1 = vlist[i1];
  282. var v2 = vlist[i2];
  283. var v3 = vlist[i3];
  284. var w1 = uvlist[i1];
  285. var w2 = uvlist[i2];
  286. var w3 = uvlist[i3];
  287. // トライアングル頂点がすべて使用されている場合のみ計算する
  288. if (selectList != null)
  289. {
  290. var use1 = selectList[i1];
  291. var use2 = selectList[i2];
  292. var use3 = selectList[i3];
  293. if (use1 == 0 || use2 == 0 || use3 == 0)
  294. continue;
  295. }
  296. // 法線
  297. Vector3 vn1 = v2 - v1;
  298. Vector3 vn2 = v3 - v1;
  299. vn1 *= 1000;
  300. vn2 *= 1000;
  301. Vector3 nor = Vector3.Cross(vn1, vn2).normalized;
  302. lnorList[i1] = lnorList[i1] + nor;
  303. lnorList[i2] = lnorList[i2] + nor;
  304. lnorList[i3] = lnorList[i3] + nor;
  305. // 接線
  306. Vector3 distBA = v2 - v1;
  307. Vector3 distCA = v3 - v1;
  308. Vector2 tdistBA = w2 - w1;
  309. Vector2 tdistCA = w3 - w1;
  310. float area = tdistBA.x * tdistCA.y - tdistBA.y * tdistCA.x;
  311. Vector3 tan = Vector3.zero;
  312. if (area == 0.0f)
  313. {
  314. // error!
  315. Debug.LogError("area = 0!");
  316. }
  317. else
  318. {
  319. float delta = 1.0f / area;
  320. tan = new Vector3(
  321. (distBA.x * tdistCA.y) + (distCA.x * -tdistBA.y),
  322. (distBA.y * tdistCA.y) + (distCA.y * -tdistBA.y),
  323. (distBA.z * tdistCA.y) + (distCA.z * -tdistBA.y)
  324. ) * delta;
  325. // 左手座標系に合わせる
  326. tan = -tan;
  327. }
  328. ltanList[i1] = ltanList[i1] + tan;
  329. ltanList[i2] = ltanList[i2] + tan;
  330. ltanList[i3] = ltanList[i3] + tan;
  331. }
  332. // 正規化
  333. for (int i = 0; i < vcnt; i++)
  334. {
  335. if (lnorList[i] != Vector3.zero && ltanList[i] != Vector3.zero)
  336. {
  337. ltanList[i] = ltanList[i].normalized;
  338. lnorList[i] = lnorList[i].normalized;
  339. }
  340. else
  341. {
  342. // この頂点の法線接線は無効なのでデフォルト値
  343. ltanList[i] = new Vector3(0, 1, 0);
  344. lnorList[i] = new Vector4(1, 0, 0, 1);
  345. }
  346. }
  347. return true;
  348. }
  349. #if false
  350. /// <summary>
  351. /// 本来のメッシュ法線/接線とアルゴリズムで算出した法線/接線を補間する回転を頂点ごとに求めて返す
  352. /// 回転はアルゴリズム法線/接線のローカル空間での、本来姿勢への回転値。
  353. /// </summary>
  354. /// <param name="mesh"></param>
  355. /// <param name="vrotList"></param>
  356. /// <returns></returns>
  357. public static bool CalcMeshAdjustVertexRotation(
  358. Vector3[] vlist, Vector3[] nlist, Vector4[] tlist, Vector2[] uvlist, int[] triangles,
  359. out Quaternion[] vrotList)
  360. {
  361. vrotList = null;
  362. int vcnt = vlist.Length;
  363. // アルゴリズム計算のローカル法線/接線を取得する
  364. List<Vector3> lnorList;
  365. List<Vector3> ltanList;
  366. if (CalcMeshLocalNormalTangent(vlist, uvlist, triangles, out lnorList, out ltanList) == false)
  367. return false;
  368. // 各頂点においてアルゴリズム計算の法線をオリジナル法線に合わせる回転を求める
  369. vrotList = new Quaternion[vcnt];
  370. for (int i = 0; i < vcnt; i++)
  371. {
  372. // オリジナル
  373. var q1 = Quaternion.LookRotation(nlist[i], tlist[i]);
  374. // アルゴリズム
  375. var q2 = Quaternion.LookRotation(lnorList[i], ltanList[i]);
  376. // オリジナル法線/接線をアルゴリズムでの法線/接線空間に投影する
  377. Quaternion iq2 = Quaternion.Inverse(q2);
  378. var n = iq2 * (q1 * Vector3.forward);
  379. var t = iq2 * (q1 * Vector3.up);
  380. // アルゴリズム空間でのオリジナル姿勢へ戻す回転
  381. Quaternion q = Quaternion.LookRotation(n, t);
  382. vrotList[i] = q;
  383. }
  384. return true;
  385. }
  386. #endif
  387. /// <summary>
  388. /// ライン/トライアングル情報を分解して各頂点の接続頂点をリストにして返す
  389. /// </summary>
  390. /// <param name="vcnt"></param>
  391. /// <param name="triangleList"></param>
  392. /// <returns></returns>
  393. public static List<HashSet<int>> GetTriangleToVertexLinkList(int vcnt, List<int> lineList, List<int> triangleList)
  394. {
  395. List<HashSet<int>> vlink = new List<HashSet<int>>();
  396. for (int i = 0; i < vcnt; i++)
  397. {
  398. vlink.Add(new HashSet<int>());
  399. }
  400. if (lineList != null && lineList.Count > 0)
  401. {
  402. int lcnt = lineList.Count / 2;
  403. for (int i = 0; i < lcnt; i++)
  404. {
  405. int index = i * 2;
  406. int v1 = lineList[index];
  407. int v2 = lineList[index + 1];
  408. vlink[v1].Add(v2);
  409. vlink[v2].Add(v1);
  410. }
  411. }
  412. if (triangleList != null && triangleList.Count > 0)
  413. {
  414. int tcnt = triangleList.Count / 3;
  415. for (int i = 0; i < tcnt; i++)
  416. {
  417. int index = i * 3;
  418. int v1 = triangleList[index];
  419. int v2 = triangleList[index + 1];
  420. int v3 = triangleList[index + 2];
  421. vlink[v1].Add(v2);
  422. vlink[v1].Add(v3);
  423. vlink[v2].Add(v1);
  424. vlink[v2].Add(v3);
  425. vlink[v3].Add(v1);
  426. vlink[v3].Add(v2);
  427. }
  428. }
  429. return vlink;
  430. }
  431. /// <summary>
  432. /// ラインペア情報を分解して各頂点の接続頂点をリストにして返す
  433. /// </summary>
  434. /// <param name="vcnt"></param>
  435. /// <param name="lineSet"></param>
  436. /// <returns></returns>
  437. public static List<HashSet<int>> GetVertexLinkList(int vcnt, HashSet<uint> lineSet)
  438. {
  439. List<HashSet<int>> vlink = new List<HashSet<int>>();
  440. for (int i = 0; i < vcnt; i++)
  441. {
  442. vlink.Add(new HashSet<int>());
  443. }
  444. foreach (var pair in lineSet)
  445. {
  446. int v0, v1;
  447. DataUtility.UnpackPair(pair, out v0, out v1);
  448. vlink[v0].Add(v1);
  449. vlink[v1].Add(v0);
  450. }
  451. return vlink;
  452. }
  453. /// <summary>
  454. /// 頂点が接続するトライアングルを辞書にして返す
  455. /// </summary>
  456. /// <param name="triangleList"></param>
  457. /// <returns></returns>
  458. public static Dictionary<int, HashSet<int>> GetVertexToTriangles(List<int> triangleList)
  459. {
  460. var vtdict = new Dictionary<int, HashSet<int>>();
  461. for (int i = 0; i < triangleList.Count; i++)
  462. {
  463. int vindex = triangleList[i];
  464. int tindex = i / 3;
  465. if (vtdict.ContainsKey(vindex) == false)
  466. vtdict.Add(vindex, new HashSet<int>());
  467. vtdict[vindex].Add(tindex);
  468. }
  469. return vtdict;
  470. }
  471. /// <summary>
  472. /// ポリゴン番号とその2つの頂点を与え、残り1つの頂点番号を返す
  473. /// </summary>
  474. /// <param name="tindex"></param>
  475. /// <param name="v0"></param>
  476. /// <param name="v1"></param>
  477. /// <param name="triangleList"></param>
  478. /// <returns></returns>
  479. public static int RestTriangleVertex(int tindex, int v0, int v1, List<int> triangleList)
  480. {
  481. int index = tindex * 3;
  482. for (int i = 0; i < 3; i++)
  483. {
  484. int n = triangleList[index + i];
  485. if (n != v0 && n != v1)
  486. return n;
  487. }
  488. return 0;
  489. }
  490. /// <summary>
  491. /// トライアングル番頭とその1つの頂点を与え、残りの2つの頂点番号を返す
  492. /// </summary>
  493. /// <param name="tindex"></param>
  494. /// <param name="v0"></param>
  495. /// <param name="triangleList"></param>
  496. /// <param name="v1"></param>
  497. /// <param name="v2"></param>
  498. public static void RestTriangleVertex(int tindex, int v0, List<int> triangleList, out int v1, out int v2)
  499. {
  500. int index = tindex * 3;
  501. int n0 = triangleList[index];
  502. int n1 = triangleList[index + 1];
  503. int n2 = triangleList[index + 2];
  504. if (n0 == v0)
  505. {
  506. v1 = n1;
  507. v2 = n2;
  508. }
  509. else if (n1 == v0)
  510. {
  511. v1 = n0;
  512. v2 = n2;
  513. }
  514. else if (n2 == v0)
  515. {
  516. v1 = n0;
  517. v2 = n1;
  518. }
  519. else
  520. {
  521. Debug.LogError("RestTriangleVertex() failed!");
  522. v1 = -1;
  523. v2 = -1;
  524. }
  525. }
  526. /// <summary>
  527. /// 2つのトライアングルが隣接しているか判定する
  528. /// </summary>
  529. /// <param name="tindex0"></param>
  530. /// <param name="tindex1"></param>
  531. /// <param name="triangleList"></param>
  532. /// <returns></returns>
  533. public static bool CheckAdjacentTriangle(int tindex0, int tindex1, List<int> triangleList)
  534. {
  535. int index0 = tindex0 * 3;
  536. int index1 = tindex1 * 3;
  537. int cnt = 0;
  538. for (int i = 0; i < 3; i++, index0++)
  539. {
  540. int v = triangleList[index0];
  541. for (int j = 0; j < 3; j++)
  542. {
  543. if (v == triangleList[index1 + j])
  544. cnt++;
  545. }
  546. }
  547. return cnt >= 2;
  548. }
  549. /// <summary>
  550. /// エッジをキーとして隣接するトライアングルインデックスを辞書に変換して返す
  551. /// </summary>
  552. /// <param name="vcnt"></param>
  553. /// <param name="triangleList"></param>
  554. /// <returns></returns>
  555. public static Dictionary<uint, List<int>> GetTriangleEdgePair(List<int> triangleList)
  556. {
  557. Dictionary<uint, List<int>> triangleEdgeDict = new Dictionary<uint, List<int>>();
  558. if (triangleList != null && triangleList.Count >= 3)
  559. {
  560. // すべてのトライアングル
  561. int tcnt = triangleList.Count / 3;
  562. for (int i = 0; i < tcnt; i++)
  563. {
  564. int tindex = i * 3;
  565. int v0 = triangleList[tindex];
  566. int v1 = triangleList[tindex + 1];
  567. int v2 = triangleList[tindex + 2];
  568. // エッジにトライアングルを追加する
  569. AddTriangleEdge(v0, v1, i, triangleEdgeDict);
  570. AddTriangleEdge(v0, v2, i, triangleEdgeDict);
  571. AddTriangleEdge(v1, v2, i, triangleEdgeDict);
  572. }
  573. }
  574. return triangleEdgeDict;
  575. }
  576. // エッジに隣接するトライアングルを追加する
  577. static void AddTriangleEdge(int v0, int v1, int tindex, Dictionary<uint, List<int>> triangleEdgeDict)
  578. {
  579. // 頂点v0/v1をパックする
  580. uint pack = DataUtility.PackPair(v0, v1);
  581. List<int> tlist;
  582. if (triangleEdgeDict.ContainsKey(pack))
  583. {
  584. // 既存
  585. tlist = triangleEdgeDict[pack];
  586. }
  587. else
  588. {
  589. // 新規
  590. tlist = new List<int>();
  591. triangleEdgeDict.Add(pack, tlist);
  592. }
  593. // 追加
  594. tlist.Add(tindex);
  595. }
  596. /// <summary>
  597. /// トライアングルリストをulongにパッキングして返す
  598. /// </summary>
  599. /// <param name="triangleList"></param>
  600. /// <returns></returns>
  601. public static List<ulong> GetTrianglePackList(List<int> triangleList)
  602. {
  603. var packList = new List<ulong>();
  604. if (triangleList != null && triangleList.Count > 0)
  605. {
  606. int cnt = triangleList.Count / 3;
  607. for (int i = 0; i < cnt; i++)
  608. {
  609. int index = i * 3;
  610. int v0 = triangleList[index];
  611. int v1 = triangleList[index + 1];
  612. int v2 = triangleList[index + 2];
  613. ulong pack = DataUtility.PackTriple(v0, v1, v2);
  614. packList.Add(pack);
  615. }
  616. }
  617. return packList;
  618. }
  619. /// <summary>
  620. /// 指定ボーンのすべての子へのラインに対して最近接点距離を返す
  621. /// </summary>
  622. /// <param name="pos"></param>
  623. /// <param name="bone"></param>
  624. /// <param name="lineWidth"></param>
  625. /// <returns></returns>
  626. public static float ClosestPtBoneLine(Vector3 pos, Transform bone, float lineWidth, out Vector3 d)
  627. {
  628. float mindist = 10000;
  629. d = bone.position;
  630. // 子がいない場合はそのまま
  631. if (bone.childCount == 0)
  632. {
  633. mindist = Mathf.Max(Vector3.Distance(pos, bone.position) - lineWidth, 0.0f);
  634. return mindist;
  635. }
  636. // すべての子へのラインに対して判定
  637. for (int i = 0; i < bone.childCount; i++)
  638. {
  639. var child = bone.GetChild(i);
  640. var spos = bone.position;
  641. var epos = child.position;
  642. var w = MathUtility.ClosestPtPointSegment(pos, spos, epos);
  643. float dist = Mathf.Max(Vector3.Distance(pos, w) - lineWidth, 0.0f);
  644. //mindist = Mathf.Min(dist, mindist);
  645. if (dist < mindist)
  646. {
  647. mindist = dist;
  648. d = w;
  649. }
  650. }
  651. return mindist;
  652. }
  653. /// <summary>
  654. /// スキンメッシュから実際に利用しているボーントランスフォームのみリスト化して返す
  655. /// </summary>
  656. /// <param name="bones"></param>
  657. /// <param name="mesh"></param>
  658. /// <returns></returns>
  659. public static List<Transform> GetUseBoneTransformList(Transform[] bones, Mesh mesh)
  660. {
  661. List<Transform> boneTransformList = new List<Transform>();
  662. if (mesh)
  663. {
  664. // use bone index
  665. List<int> boneIndexList = new List<int>();
  666. HashSet<int> useBoneSet = new HashSet<int>();
  667. BoneWeight[] bws = mesh.boneWeights;
  668. foreach (var bw in bws)
  669. {
  670. if (bw.weight0 > 0.0f)
  671. useBoneSet.Add(bw.boneIndex0);
  672. if (bw.weight1 > 0.0f)
  673. useBoneSet.Add(bw.boneIndex1);
  674. if (bw.weight2 > 0.0f)
  675. useBoneSet.Add(bw.boneIndex2);
  676. if (bw.weight3 > 0.0f)
  677. useBoneSet.Add(bw.boneIndex3);
  678. }
  679. // use transform
  680. foreach (var index in useBoneSet)
  681. {
  682. boneTransformList.Add(bones[index]);
  683. }
  684. }
  685. return boneTransformList;
  686. }
  687. //=========================================================================================
  688. // テトラメッシュ
  689. //=========================================================================================
  690. private class TetraVertex
  691. {
  692. public int index;
  693. public Vector3 pos;
  694. public TetraVertex() { }
  695. public TetraVertex(Vector3 pos, int index)
  696. {
  697. this.pos = pos;
  698. this.index = index;
  699. }
  700. }
  701. private class Tetra
  702. {
  703. public List<TetraVertex> vertexList = new List<TetraVertex>();
  704. // 外接円
  705. public Vector3 circumCenter;
  706. public float circumRadius;
  707. // 重心と重心からの最大距離
  708. public Vector3 tetraCenter;
  709. public float tetraSize;
  710. public Tetra()
  711. {
  712. }
  713. public Tetra(TetraVertex a, TetraVertex b, TetraVertex c, TetraVertex d)
  714. {
  715. vertexList.Add(a);
  716. vertexList.Add(b);
  717. vertexList.Add(c);
  718. vertexList.Add(d);
  719. //CalcCircumcircle();
  720. CalcSize();
  721. }
  722. public ulong GetTetraHash()
  723. {
  724. return DataUtility.PackQuater(vertexList[0].index, vertexList[1].index, vertexList[2].index, vertexList[3].index);
  725. }
  726. /// <summary>
  727. /// テトラの外接円と半径を求める
  728. /// https://qiita.com/kkttm530/items/d32bad84a6a7f0d8d7e7
  729. /// からだけどdeterminantの計算は間違ってるっぽいのでmathの関数を使用する
  730. /// </summary>
  731. public void CalcCircumcircle()
  732. {
  733. var p1 = vertexList[0].pos;
  734. var p2 = vertexList[1].pos;
  735. var p3 = vertexList[2].pos;
  736. var p4 = vertexList[3].pos;
  737. float4x4 a = new float4x4(
  738. new float4(p1.x, p1.y, p1.z, 1),
  739. new float4(p2.x, p2.y, p2.z, 1),
  740. new float4(p3.x, p3.y, p3.z, 1),
  741. new float4(p4.x, p4.y, p4.z, 1)
  742. );
  743. float s0 = Mathf.Pow(p1.x, 2.0f) + Mathf.Pow(p1.y, 2.0f) + Mathf.Pow(p1.z, 2.0f);
  744. float s1 = Mathf.Pow(p2.x, 2.0f) + Mathf.Pow(p2.y, 2.0f) + Mathf.Pow(p2.z, 2.0f);
  745. float s2 = Mathf.Pow(p3.x, 2.0f) + Mathf.Pow(p3.y, 2.0f) + Mathf.Pow(p3.z, 2.0f);
  746. float s3 = Mathf.Pow(p4.x, 2.0f) + Mathf.Pow(p4.y, 2.0f) + Mathf.Pow(p4.z, 2.0f);
  747. float4x4 dx = new float4x4(
  748. new float4(s0, p1.y, p1.z, 1),
  749. new float4(s1, p2.y, p2.z, 1),
  750. new float4(s2, p3.y, p3.z, 1),
  751. new float4(s3, p4.y, p4.z, 1)
  752. );
  753. float4x4 dy = new float4x4(
  754. new float4(s0, p1.x, p1.z, 1),
  755. new float4(s1, p2.x, p2.z, 1),
  756. new float4(s2, p3.x, p3.z, 1),
  757. new float4(s3, p4.x, p4.z, 1)
  758. );
  759. float4x4 dz = new float4x4(
  760. new float4(s0, p1.x, p1.y, 1),
  761. new float4(s1, p2.x, p2.y, 1),
  762. new float4(s2, p3.x, p3.y, 1),
  763. new float4(s3, p4.x, p4.y, 1)
  764. );
  765. float4x4 c = new float4x4(
  766. new float4(s0, p1.x, p1.y, p1.z),
  767. new float4(s1, p2.x, p2.y, p2.z),
  768. new float4(s2, p3.x, p3.y, p3.z),
  769. new float4(s3, p4.x, p4.y, p4.z)
  770. );
  771. float a0 = math.determinant(a);
  772. float dx0 = math.determinant(dx);
  773. float dy0 = -math.determinant(dy);
  774. float dz0 = math.determinant(dz);
  775. float c0 = math.determinant(c);
  776. circumCenter = new Vector3(dx0 / (2 * a0), dy0 / (2 * a0), dz0 / (2 * a0));
  777. circumRadius = Mathf.Sqrt(dx0 * dx0 + dy0 * dy0 + dz0 * dz0 - 4.0f * a0 * c0) / (2.0f * Mathf.Abs(a0));
  778. }
  779. public bool IntersectCircumcircle(Vector3 pos)
  780. {
  781. return Vector3.Distance(pos, circumCenter) <= circumRadius;
  782. }
  783. public bool CheckSame(Tetra tri)
  784. {
  785. return circumCenter == tri.circumCenter && circumRadius == tri.circumRadius;
  786. }
  787. public bool ContainsPoint(TetraVertex p1)
  788. {
  789. return vertexList.Contains(p1);
  790. }
  791. public bool ContainsPoint(TetraVertex p1, TetraVertex p2, TetraVertex p3, TetraVertex p4)
  792. {
  793. return vertexList.Contains(p1) || vertexList.Contains(p2) || vertexList.Contains(p3) || vertexList.Contains(p4);
  794. }
  795. /// <summary>
  796. /// 重心と重心からの最大距離を計算する
  797. /// </summary>
  798. public void CalcSize()
  799. {
  800. var wpos0 = vertexList[0].pos;
  801. var wpos1 = vertexList[1].pos;
  802. var wpos2 = vertexList[2].pos;
  803. var wpos3 = vertexList[3].pos;
  804. tetraCenter = (wpos0 + wpos1 + wpos2 + wpos3) / 4.0f;
  805. float len0 = Vector3.Distance(wpos0, tetraCenter);
  806. float len1 = Vector3.Distance(wpos1, tetraCenter);
  807. float len2 = Vector3.Distance(wpos2, tetraCenter);
  808. float len3 = Vector3.Distance(wpos3, tetraCenter);
  809. tetraSize = Mathf.Max(Mathf.Max(len0, len1), Mathf.Max(len2, len3));
  810. }
  811. /// <summary>
  812. /// テトラの検証
  813. /// </summary>
  814. /// <returns></returns>
  815. public bool Verification()
  816. {
  817. // あまりに平坦なものは弾く
  818. var wpos0 = vertexList[0].pos;
  819. var wpos1 = vertexList[1].pos;
  820. var wpos2 = vertexList[2].pos;
  821. var wpos3 = vertexList[3].pos;
  822. var n = Vector3.Cross(wpos0 - wpos1, wpos0 - wpos2);
  823. if (n.magnitude < 0.00001f)
  824. return false;
  825. n.Normalize();
  826. var v = wpos3 - wpos0;
  827. var h = Vector3.Dot(n, v);
  828. if (Mathf.Abs(h) < (tetraSize * 0.2f))
  829. return false;
  830. return true;
  831. }
  832. }
  833. /// <summary>
  834. /// テトラメッシュを構築して返す
  835. /// </summary>
  836. /// <param name="posList"></param>
  837. /// <param name="tetraCount">作成されたテトラ数</param>
  838. /// <param name="tetraIndexList">テトラ数x4のインデックスリスト</param>
  839. /// <param name="tetraSizeList">テトラの重心からの最大距離リスト</param>
  840. public static void CalcTetraMesh(List<Vector3> posList, out int tetraCount, out List<int> tetraIndexList, out List<float> tetraSizeList)
  841. {
  842. tetraCount = 0;
  843. tetraIndexList = new List<int>();
  844. tetraSizeList = new List<float>();
  845. // 作業用バッファ
  846. List<TetraVertex> vertexList = new List<TetraVertex>();
  847. for (int i = 0; i < posList.Count; i++)
  848. {
  849. vertexList.Add(new TetraVertex(posList[i], i));
  850. }
  851. // 入力頂点のバウンディングボックス
  852. Bounds b = new Bounds(posList[0], Vector3.one * 0.01f);
  853. foreach (var pos in posList)
  854. {
  855. b.Encapsulate(pos);
  856. }
  857. // ポイントをすべて内包するテトラポイントを追加する
  858. float areaRadius = Mathf.Max(Mathf.Max(b.extents.x, b.extents.y), b.extents.z);
  859. float dist = areaRadius * 100.0f;
  860. var tempSV0 = new TetraVertex();
  861. var tempSV1 = new TetraVertex();
  862. var tempSV2 = new TetraVertex();
  863. var tempSV3 = new TetraVertex();
  864. tempSV0.pos = b.center + new Vector3(0.0f, -dist, 0.0f);
  865. tempSV1.pos = b.center + new Vector3(-dist, dist, dist);
  866. tempSV2.pos = b.center + new Vector3(dist, dist, dist);
  867. tempSV3.pos = b.center + new Vector3(0.0f, dist, -dist);
  868. int svcnt = vertexList.Count;
  869. tempSV0.index = svcnt++;
  870. tempSV1.index = svcnt++;
  871. tempSV2.index = svcnt++;
  872. tempSV3.index = svcnt++;
  873. vertexList.Add(tempSV0);
  874. vertexList.Add(tempSV1);
  875. vertexList.Add(tempSV2);
  876. vertexList.Add(tempSV3);
  877. // 最初のテトラを分割テトラとして登録
  878. List<Tetra> divideTetras = new List<Tetra>();
  879. var tetra0 = new Tetra(tempSV0, tempSV1, tempSV2, tempSV3);
  880. tetra0.CalcCircumcircle();
  881. divideTetras.Add(tetra0);
  882. // 重複チェック用
  883. Dictionary<ulong, Tetra> useTetraHash = new Dictionary<ulong, Tetra>();
  884. useTetraHash.Add(tetra0.GetTetraHash(), tetra0);
  885. // テトラ構築
  886. for (int k = 0; k < (vertexList.Count - 4); k++)
  887. {
  888. var point = vertexList[k];
  889. List<Tetra> tempDivTetras = new List<Tetra>();
  890. for (int i = 0; i < divideTetras.Count;)
  891. {
  892. var tetra = divideTetras[i];
  893. if (tetra.ContainsPoint(point) == false)
  894. {
  895. if (tetra.IntersectCircumcircle(point.pos))
  896. {
  897. // 再分割
  898. var tetra1 = new Tetra(tetra.vertexList[0], tetra.vertexList[1], tetra.vertexList[2], point);
  899. var tetra2 = new Tetra(tetra.vertexList[0], tetra.vertexList[2], tetra.vertexList[3], point);
  900. var tetra3 = new Tetra(tetra.vertexList[0], tetra.vertexList[3], tetra.vertexList[1], point);
  901. var tetra4 = new Tetra(tetra.vertexList[1], tetra.vertexList[2], tetra.vertexList[3], point);
  902. tempDivTetras.Add(tetra1);
  903. tempDivTetras.Add(tetra2);
  904. tempDivTetras.Add(tetra3);
  905. tempDivTetras.Add(tetra4);
  906. useTetraHash.Remove(tetra.GetTetraHash());
  907. divideTetras.RemoveAt(i);
  908. continue;
  909. }
  910. }
  911. i++;
  912. }
  913. // 次の候補として追加
  914. foreach (var tetra in tempDivTetras)
  915. {
  916. ulong thash = tetra.GetTetraHash();
  917. if (useTetraHash.ContainsKey(thash) == false)
  918. {
  919. tetra.CalcCircumcircle();
  920. useTetraHash.Add(thash, tetra);
  921. divideTetras.Add(tetra);
  922. }
  923. else
  924. {
  925. // 衝突
  926. // 衝突もとも削除する
  927. var deltetra = useTetraHash[thash];
  928. useTetraHash.Remove(thash);
  929. divideTetras.Remove(deltetra);
  930. }
  931. }
  932. }
  933. // 最初に追加したテトラを削除
  934. for (int i = 0; i < divideTetras.Count;)
  935. {
  936. var tetra = divideTetras[i];
  937. if (tetra.ContainsPoint(tempSV0, tempSV1, tempSV2, tempSV3))
  938. {
  939. // このテトラは削除する
  940. useTetraHash.Remove(tetra.GetTetraHash());
  941. divideTetras.RemoveAt(i);
  942. continue;
  943. }
  944. i++;
  945. }
  946. vertexList.Remove(tempSV0);
  947. vertexList.Remove(tempSV1);
  948. vertexList.Remove(tempSV2);
  949. vertexList.Remove(tempSV3);
  950. // テトラの検証
  951. for (int i = 0; i < divideTetras.Count;)
  952. {
  953. var tetra = divideTetras[i];
  954. if (tetra.Verification() == false)
  955. {
  956. divideTetras.RemoveAt(i);
  957. continue;
  958. }
  959. i++;
  960. }
  961. // 最終結果を格納
  962. tetraCount = divideTetras.Count;
  963. foreach (var tetra in divideTetras)
  964. {
  965. for (int i = 0; i < 4; i++)
  966. tetraIndexList.Add(tetra.vertexList[i].index);
  967. tetraSizeList.Add(tetra.tetraSize);
  968. }
  969. }
  970. /// <summary>
  971. /// 現在のボーンを置換辞書から置き換えて返す
  972. /// 辞書に登録されていない場合は、現在のボーンをそのまま返す
  973. /// </summary>
  974. /// <param name="now"></param>
  975. /// <param name="boneReplaceDict"></param>
  976. /// <returns></returns>
  977. public static Transform GetReplaceBone<T>(Transform now, Dictionary<T, Transform> boneReplaceDict) where T : class
  978. {
  979. if (typeof(T) == typeof(string))
  980. return boneReplaceDict.ContainsKey(now.name as T) ? boneReplaceDict[now.name as T] : now;
  981. else
  982. return boneReplaceDict.ContainsKey(now as T) ? boneReplaceDict[now as T] : now;
  983. }
  984. }
  985. }