CubismModel.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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.Framework;
  8. using System;
  9. using UnityEngine;
  10. #if UNITY_2019_3_OR_NEWER
  11. using UnityEngine.LowLevel;
  12. using UnityEngine.PlayerLoop;
  13. #elif UNITY_2018_1_OR_NEWER
  14. using UnityEngine.Experimental.LowLevel;
  15. using UnityEngine.Experimental.PlayerLoop;
  16. #endif
  17. namespace Live2D.Cubism.Core
  18. {
  19. /// <summary>
  20. /// Runtime Cubism model.
  21. /// </summary>
  22. [ExecuteInEditMode, CubismDontMoveOnReimport]
  23. public sealed class CubismModel : MonoBehaviour
  24. {
  25. #region Delegates
  26. /// <summary>
  27. /// Handler for <see cref="CubismDynamicDrawableData"/>.
  28. /// </summary>
  29. /// <param name="sender">Model the dymanic data applies to.</param>
  30. /// <param name="data">New data.</param>
  31. public delegate void DynamicDrawableDataHandler(CubismModel sender, CubismDynamicDrawableData[] data);
  32. #endregion
  33. #region Events
  34. /// <summary>
  35. /// Event triggered if new <see cref="CubismDynamicDrawableData"/> is available for instance.
  36. /// </summary>
  37. public event DynamicDrawableDataHandler OnDynamicDrawableData;
  38. #endregion
  39. #region Factory Methods
  40. /// <summary>
  41. /// Instantiates a <see cref="CubismMoc"/>.
  42. /// </summary>
  43. /// <param name="moc">Cubism moc to instantiate.</param>
  44. /// <returns>Instance.</returns>
  45. public static CubismModel InstantiateFrom(CubismMoc moc)
  46. {
  47. // Return if argument is invalid.
  48. if (moc == null)
  49. {
  50. return null;
  51. }
  52. // Create model.
  53. var model = new GameObject(moc.name)
  54. .AddComponent<CubismModel>();
  55. // Initialize it by resetting it.
  56. model.Reset(moc);
  57. return model;
  58. }
  59. #endregion
  60. /// <summary>
  61. /// Resets a <see cref="CubismMoc"/> reference in <see cref="CubismModel"/>.
  62. /// </summary>
  63. /// <param name="model">Target Cubism model.</param>
  64. /// <param name="moc">Cubism moc to reset.</param>
  65. public static void ResetMocReference(CubismModel model, CubismMoc moc)
  66. {
  67. model.Moc = moc;
  68. }
  69. /// <summary>
  70. /// <see cref="Moc"/> backing field.
  71. /// </summary>
  72. [SerializeField, HideInInspector]
  73. private CubismMoc _moc;
  74. /// <summary>
  75. /// Moc the instance was instantiated from.
  76. /// </summary>
  77. public CubismMoc Moc
  78. {
  79. get { return _moc; }
  80. private set { _moc = value; }
  81. }
  82. /// <summary>
  83. /// TaskableModel for unmanaged backend.
  84. /// </summary>
  85. private CubismTaskableModel TaskableModel { get; set; }
  86. /// <summary>
  87. /// <see cref="Parameters"/> backing field.
  88. /// </summary>
  89. [NonSerialized]
  90. private CubismParameter[] _parameters;
  91. /// <summary>
  92. /// Drawables of model.
  93. /// </summary>
  94. public CubismParameter[] Parameters
  95. {
  96. get
  97. {
  98. if (_parameters == null)
  99. {
  100. Revive();
  101. }
  102. return _parameters;
  103. }
  104. private set { _parameters = value; }
  105. }
  106. /// <summary>
  107. /// <see cref="Parts"/> backing field.
  108. /// </summary>
  109. [NonSerialized]
  110. private CubismPart[] _parts;
  111. /// <summary>
  112. /// Drawables of model.
  113. /// </summary>
  114. public CubismPart[] Parts
  115. {
  116. get
  117. {
  118. if (_parts == null)
  119. {
  120. Revive();
  121. }
  122. return _parts;
  123. }
  124. private set { _parts = value; }
  125. }
  126. /// <summary>
  127. /// <see cref="Drawables"/> backing field.
  128. /// </summary>
  129. [NonSerialized]
  130. private CubismDrawable[] _drawables;
  131. /// <summary>
  132. /// Drawables of model.
  133. /// </summary>
  134. public CubismDrawable[] Drawables
  135. {
  136. get
  137. {
  138. if (_drawables == null)
  139. {
  140. Revive();
  141. }
  142. return _drawables;
  143. }
  144. private set { _drawables = value; }
  145. }
  146. /// <summary>
  147. /// <see cref="CanvasInformation"/> backing field.
  148. /// </summary>
  149. [NonSerialized]
  150. private CubismCanvasInformation _canvasInformation;
  151. /// <summary>
  152. /// Canvas information of model.
  153. /// </summary>
  154. public CubismCanvasInformation CanvasInformation
  155. {
  156. get
  157. {
  158. if (_canvasInformation == null)
  159. {
  160. Revive();
  161. }
  162. return _canvasInformation;
  163. }
  164. private set { _canvasInformation = value; }
  165. }
  166. /// <summary>
  167. /// Parameter store cache.
  168. /// </summary>
  169. CubismParameterStore _parameterStore;
  170. /// <summary>
  171. /// Whether parameter repetition is performed for the entire model.
  172. /// </summary>
  173. [SerializeField]
  174. private bool _isOverriddenParameterRepeat = true;
  175. /// <summary>
  176. /// Checks whether parameter repetition is performed for the entire model.
  177. /// </summary>
  178. /// <returns>True if parameter repetition is performed for the entire model; otherwise returns false.</returns>
  179. public bool GetOverrideFlagForModelParameterRepeat()
  180. {
  181. return _isOverriddenParameterRepeat;
  182. }
  183. /// <summary>
  184. /// Sets whether parameter repetition is performed for the entire model.
  185. /// </summary>
  186. /// <param name="isRepeat">Use true to perform parameter repetition for the entire model, or false to not perform it.</param>
  187. public void SetOverrideFlagForModelParameterRepeat(bool isRepeat)
  188. {
  189. _isOverriddenParameterRepeat = isRepeat;
  190. }
  191. /// <summary>
  192. /// True if instance is revived.
  193. /// </summary>
  194. public bool IsRevived
  195. {
  196. get { return TaskableModel != null; }
  197. }
  198. /// <summary>
  199. /// True if instance can revive.
  200. /// </summary>
  201. private bool CanRevive
  202. {
  203. get { return Moc != null; }
  204. }
  205. #if UNITY_2018_1_OR_NEWER
  206. /// <summary>
  207. /// Model update functions for player loop.
  208. /// </summary>
  209. [NonSerialized]
  210. private static Action _modelUpdateFunctions;
  211. private bool WasAttachedModelUpdateFunction { get; set; }
  212. #endif
  213. /// <summary>
  214. /// True on the frame the instance was enabled.
  215. /// </summary>
  216. private bool WasJustEnabled { get; set; }
  217. /// <summary>
  218. /// Frame number last update was done.
  219. /// </summary>
  220. private int LastTick { get; set; }
  221. /// <summary>
  222. /// Revives instance.
  223. /// </summary>
  224. private void Revive()
  225. {
  226. // Return if already revive.
  227. if (IsRevived)
  228. {
  229. return;
  230. }
  231. // Return if revive isn't possible.
  232. if (!CanRevive)
  233. {
  234. return;
  235. }
  236. Reset(Moc);
  237. }
  238. /// <summary>
  239. /// Initializes instance for first use.
  240. /// </summary>
  241. /// <param name="moc">Moc to instantiate from.</param>
  242. private void Reset(CubismMoc moc)
  243. {
  244. Moc = moc;
  245. name = moc.name;
  246. TaskableModel = new CubismTaskableModel(moc);
  247. if (TaskableModel == null || TaskableModel.UnmanagedModel == null)
  248. {
  249. return;
  250. }
  251. Parameters = GetComponentsInChildren<CubismParameter>();
  252. if (Parameters.Length < 1 && (transform.Find("Parameters") == null))
  253. {
  254. // Create and initialize proxies.
  255. var parameters = CubismParameter.CreateParameters(TaskableModel.UnmanagedModel);
  256. parameters.transform.SetParent(transform);
  257. Parameters = parameters.GetComponentsInChildren<CubismParameter>();
  258. }
  259. else
  260. {
  261. Parameters.Revive(TaskableModel.UnmanagedModel);
  262. }
  263. Parts = GetComponentsInChildren<CubismPart>();
  264. if (Parts.Length < 1 && (transform.Find("Parts") == null))
  265. {
  266. // Create and initialize proxies.
  267. var parts = CubismPart.CreateParts(TaskableModel.UnmanagedModel);
  268. parts.transform.SetParent(transform);
  269. Parts = parts.GetComponentsInChildren<CubismPart>();
  270. }
  271. else
  272. {
  273. Parts.Revive(TaskableModel.UnmanagedModel);
  274. }
  275. Drawables = GetComponentsInChildren<CubismDrawable>();
  276. if (Drawables.Length < 1 && (transform.Find("Drawables") == null))
  277. {
  278. // Create and initialize proxies.
  279. var drawables = CubismDrawable.CreateDrawables(TaskableModel.UnmanagedModel);
  280. drawables.transform.SetParent(transform);
  281. Drawables = drawables.GetComponentsInChildren<CubismDrawable>();
  282. }
  283. else
  284. {
  285. Drawables.Revive(TaskableModel.UnmanagedModel);
  286. }
  287. CanvasInformation = new CubismCanvasInformation(TaskableModel.UnmanagedModel);
  288. RefreshParameterStore();
  289. SetOverrideFlagForModelParameterRepeat(_isOverriddenParameterRepeat);
  290. }
  291. /// <summary>
  292. /// Forces update.
  293. /// </summary>
  294. public void ForceUpdateNow()
  295. {
  296. WasJustEnabled = true;
  297. LastTick = -1;
  298. Revive();
  299. #if UNITY_2018_1_OR_NEWER
  300. OnModelUpdate();
  301. #else
  302. OnRenderObject();
  303. #endif
  304. }
  305. /// <summary>
  306. /// パラメータストアを最新の情報に更新する。
  307. /// </summary>
  308. public void RefreshParameterStore()
  309. {
  310. // CubismParameterStore を取得する。
  311. _parameterStore = GetComponent<CubismParameterStore>();
  312. // Return early if empty.
  313. if (_parameterStore == null)
  314. {
  315. return;
  316. }
  317. // 最新の情報に更新する。
  318. _parameterStore.Refresh();
  319. }
  320. #if UNITY_2018_1_OR_NEWER
  321. /// <summary>
  322. /// Calls model update functions for player loop.
  323. /// </summary>
  324. private static void OnModelsUpdate()
  325. {
  326. if (_modelUpdateFunctions != null)
  327. {
  328. _modelUpdateFunctions.Invoke();
  329. }
  330. }
  331. /// <summary>
  332. /// Register the model update function into the player loop.
  333. /// </summary>
  334. [RuntimeInitializeOnLoadMethod]
  335. private static void RegisterCallbackFunction()
  336. {
  337. // Prepare the function for using player loop.
  338. var myPlayerLoopSystem = new PlayerLoopSystem()
  339. {
  340. type = typeof(CubismModel), // Identifier for Profiler Hierarchy view.
  341. updateDelegate = OnModelsUpdate // Register the function.
  342. };
  343. // Get the default player loop.
  344. var playerLoopSystem =
  345. #if UNITY_2019_3_OR_NEWER
  346. PlayerLoop.GetCurrentPlayerLoop();
  347. #else
  348. PlayerLoop.GetDefaultPlayerLoop();
  349. #endif
  350. var playerLoopIndex = -1;
  351. for (var i = 0; i < playerLoopSystem.subSystemList.Length; i++)
  352. {
  353. if (playerLoopSystem.subSystemList[i].type != typeof(PreLateUpdate))
  354. {
  355. continue;
  356. }
  357. playerLoopIndex = i;
  358. break;
  359. }
  360. if (playerLoopIndex < 0)
  361. {
  362. Debug.LogError("CubismModel : Failed to add processing to PlayerLoop.");
  363. return;
  364. }
  365. // Get the "PreLateUpdate" system.
  366. var playerLoopSubSystem = playerLoopSystem.subSystemList[playerLoopIndex];
  367. var subSystemList = playerLoopSubSystem.subSystemList;
  368. // Register the model update function after "PreLateUpdate" system.
  369. Array.Resize(ref subSystemList, subSystemList.Length + 1);
  370. subSystemList[subSystemList.Length - 1] = myPlayerLoopSystem;
  371. // Restore the "PreLateUpdate" sytem.
  372. playerLoopSubSystem.subSystemList = subSystemList;
  373. playerLoopSystem.subSystemList[playerLoopIndex] = playerLoopSubSystem;
  374. PlayerLoop.SetPlayerLoop(playerLoopSystem);
  375. }
  376. #endif
  377. #region Unity Event Handling
  378. /// <summary>
  379. /// Called by Unity. Triggers <see langword="this"/> to update.
  380. /// </summary>
  381. private void Update()
  382. {
  383. #if UNITY_2018_1_OR_NEWER
  384. if (!WasAttachedModelUpdateFunction)
  385. {
  386. _modelUpdateFunctions += OnModelUpdate;
  387. WasAttachedModelUpdateFunction = true;
  388. }
  389. #endif
  390. // Return on first frame enabled.
  391. if (WasJustEnabled)
  392. {
  393. return;
  394. }
  395. // Return unless revived.
  396. if (!IsRevived)
  397. {
  398. return;
  399. }
  400. // Return if backend is ticking.
  401. if (!TaskableModel.DidExecute)
  402. {
  403. return;
  404. }
  405. // Sync parameters back.
  406. TaskableModel.TryReadParameters(Parameters);
  407. // restore last frame parameters value and parts opacity.
  408. if (_parameterStore != null)
  409. {
  410. #if UNITY_EDITOR
  411. if (Application.isPlaying)
  412. {
  413. _parameterStore.RestoreParameters();
  414. }
  415. #else
  416. _parameterStore.RestoreParameters();
  417. #endif
  418. }
  419. // Trigger event.
  420. if (OnDynamicDrawableData == null)
  421. {
  422. return;
  423. }
  424. OnDynamicDrawableData(this, TaskableModel.DynamicDrawableData);
  425. }
  426. /// <summary>
  427. /// Called by Unity. Blockingly updates <see langword="this"/> on first frame enabled; otherwise tries async update.
  428. /// </summary>
  429. private void OnRenderObject()
  430. {
  431. #if !UNITY_2018_1_OR_NEWER
  432. OnModelUpdate();
  433. #endif
  434. }
  435. /// <summary>
  436. /// Update model states.
  437. /// </summary>
  438. private void OnModelUpdate()
  439. {
  440. // Return unless revived.
  441. if (!IsRevived)
  442. {
  443. return;
  444. }
  445. // Return if already ticked this frame.
  446. if (LastTick == Time.frameCount && Application.isPlaying)
  447. {
  448. return;
  449. }
  450. LastTick = Time.frameCount;
  451. // Try to sync parameters and parts (without caring whether task is executing or not).
  452. TaskableModel.TryWriteParametersAndParts(Parameters, Parts);
  453. // Return if task is executing.
  454. if (TaskableModel.IsExecuting)
  455. {
  456. return;
  457. }
  458. // Force blocking update on first frame enabled.
  459. if (WasJustEnabled)
  460. {
  461. // Force sync update.
  462. TaskableModel.UpdateNow();
  463. // Unset condition.
  464. WasJustEnabled = false;
  465. // Fetch results by calling own 'Update()'.
  466. Update();
  467. return;
  468. }
  469. // Enqueue update task.
  470. TaskableModel.Update();
  471. }
  472. /// <summary>
  473. /// Called by Unity. Revives instance.
  474. /// </summary>
  475. private void OnEnable()
  476. {
  477. WasJustEnabled = true;
  478. Revive();
  479. }
  480. private void OnDisable()
  481. {
  482. #if UNITY_2018_1_OR_NEWER
  483. if (WasAttachedModelUpdateFunction)
  484. {
  485. _modelUpdateFunctions -= OnModelUpdate;
  486. WasAttachedModelUpdateFunction = false;
  487. }
  488. #endif
  489. }
  490. /// <summary>
  491. /// Called by Unity. Releases unmanaged memory.
  492. /// </summary>
  493. private void OnDestroy()
  494. {
  495. if (!IsRevived)
  496. {
  497. return;
  498. }
  499. TaskableModel.ReleaseUnmanaged();
  500. TaskableModel = null;
  501. }
  502. /// <summary>
  503. /// Called by Unity. Triggers <see cref="OnEnable"/>.
  504. /// </summary>
  505. private void OnValidate()
  506. {
  507. OnEnable();
  508. }
  509. #endregion
  510. }
  511. }