/**
* Copyright(c) Live2D Inc. All rights reserved.
*
* Use of this source code is governed by the Live2D Open Software license
* that can be found at https://www.live2d.com/eula/live2d-open-software-license-agreement_en.html.
*/
using System;
using Live2D.Cubism.Core.Unmanaged;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Live2D.Cubism.Core
{
///
/// Cubism moc asset.
///
public sealed class CubismMoc : ScriptableObject
{
#region Factory Methods
///
/// Creates a asset from raw bytes.
///
/// Source.
/// Instance.
public static CubismMoc CreateFrom(byte[] moc3)
{
var moc = CreateInstance();
moc.Bytes = moc3;
return moc;
}
#endregion
///
/// Resets native handle.
///
///
public static void ResetUnmanagedMoc(CubismMoc moc)
{
moc.UnmanagedMoc = null;
moc.Revive();
}
///
/// backing field.
///
[SerializeField]
private byte[] _bytes;
///
/// Raw moc bytes.
///
private byte[] Bytes
{
get { return _bytes; }
set { _bytes = value; }
}
private CubismUnmanagedMoc UnmanagedMoc { get; set; }
private int ReferenceCount { get; set; }
#if UNITY_EDITOR
private static int CoreNotFoundCallCount { get; set; }
#endif
///
/// True if instance is revived.
///
public bool IsRevived
{
get
{
return UnmanagedMoc != null;
}
}
///
/// Acquires native handle.
///
/// Valid handle on success; otherwise.
public CubismUnmanagedMoc AcquireUnmanagedMoc()
{
++ReferenceCount;
#if UNITY_EDITOR
try
{
#endif
Revive();
#if UNITY_EDITOR
}
catch (DllNotFoundException)
{
if (CoreNotFoundCallCount == 0)
{
EditorUtility.DisplayDialog("Live2D CubismCore is not loaded", "Please reboot this Unity project if it is just after import of the SDK. If it's not, please check if platform settings of dll is correct. dll cannot be used on platform which is different from its own build settings.", "ok", "cancel");
}
++CoreNotFoundCallCount;
}
#endif
return UnmanagedMoc;
}
///
/// Releases native handle.
///
public void ReleaseUnmanagedMoc()
{
-- ReferenceCount;
// Release instance of unmanaged moc in case the instance isn't referenced any longer.
if (ReferenceCount == 0)
{
UnmanagedMoc.Release();
UnmanagedMoc = null;
}
// Deal with invalid reference counts.
else if (ReferenceCount < 0)
{
ReferenceCount = 0;
}
}
///
/// Revives instance without acquiring it.
///
private void Revive()
{
// Return if already revived.
if (IsRevived)
{
return;
}
// Return if no bytes are available.
if (Bytes == null)
{
return;
}
// Try revive.
UnmanagedMoc = CubismUnmanagedMoc.FromBytes(Bytes);
}
}
}