### Configure and Start Up Cubism Framework
Source: https://docs.live2d.com/cubism-sdk-manual/framework-init-close-web
Call CubismFramework.startUp before initialize. Configure logging options such as the log function and logging level. This setup is required for CubismFramework.initialize to function correctly.
```typescript
let cubismOption: Option;
// prepare for Cubism Framework API.
cubismOption.logFunction = LAppPal.printMessage;
cubismOption.loggingLevel = LogLevel.LogLevel_Info;
CubismFramework.startUp(cubismOption);
```
--------------------------------
### startMotion(group, no, priority)
Source: https://docs.live2d.com/cubism-sdk-manual/motion
Starts the playback of a motion specified by the group name, index number, and priority. Returns a handle or identifier for the motion, or -1 if the motion could not be started.
```APIDOC
## startMotion(group: string, no: number, priority: number)
### Description
Starts the playback of a motion specified by the group name, index number, and priority. This method handles reservation logic based on the provided priority.
### Parameters
- **group** (string) - The name of the motion group.
- **no** (number) - The index number of the motion within the group.
- **priority** (number) - The priority level for the motion playback.
### Returns
- **CubismMotionQueueEntryHandle** (or int) - The identifier for the started motion, used for tracking completion. Returns -1 if the motion cannot be started.
```
--------------------------------
### Start Motion in TypeScript
Source: https://docs.live2d.com/cubism-sdk-manual/motion
Initiates motion playback by checking priority and reserving the motion manager before starting the motion.
```TypeScript
// TypeScript
/**
* 引数で指定したモーションの再生を開始する
* @param group モーショングループ名
* @param no グループ内の番号
* @param priority 優先度
* @return 開始したモーションの識別番号を返す。
* 個別のモーションが終了したか否かを判定するisFinished()の引数で使用する.
* 開始できない時は[-1]
*/
public startMotion(group: string, no: number, priority: number) : CubismMotionQueueEntryHandle
{
if(priority == LAppDefine.PriorityForce)
{
this._motionManager.setReservePriority(priority);
}
else if(!this._motionManager.reserveMotion(priority))
{
if(this._debugMode)
{
LAppPal.printLog("[APP]can't start motion.");
}
return InvalidMotionQueueEntryHandleValue;
}
/*モーションデータ準備部分省略*/
return this._motionManager.startMotionPriority(motion, autoDelete, priority);
}
```
--------------------------------
### Start Motion with Priority in C++
Source: https://docs.live2d.com/cubism-sdk-manual/motion
Starts a motion while checking against reserved priorities to ensure higher-priority motions take precedence.
```C++
CubismMotionQueueEntryHandle LAppModel::StartMotion(const csmChar* group, csmInt32 no, csmInt32 priority)
{
if (priority == PriorityForce)
{
_motionManager->SetReservePriority(priority);
}
else if (!_motionManager->ReserveMotion(priority))
{
if (_debugMode)
{
LAppPal::PrintLog("[APP]can't start motion.");
}
return InvalidMotionQueueEntryHandleValue;
}
/*モーションデータ準備部分省略*/
return _motionManager->StartMotionPriority(motion, autoDelete, priority);
}
```
```C++
CubismMotionQueueEntryHandle LAppModel::StartMotion(const csmChar* group, csmInt32 no, csmInt32 priority)
{
if (priority == PriorityForce)
{
_motionManager->SetReservePriority(priority);
}
else if (!_motionManager->ReserveMotion(priority))
{
if (_debugMode)
{
LAppPal::PrintLog("[APP]can't start motion.");
}
return InvalidMotionQueueEntryHandleValue;
}
/*モーションデータ準備部分省略*/
return _motionManager->StartMotionPriority(motion, autoDelete, priority);
}
```
--------------------------------
### Start Motion in Java
Source: https://docs.live2d.com/cubism-sdk-manual/motion
Initiates motion playback in Java, including priority reservation and callback handling.
```Java
// Java
public int startMotion(final String group,
int number,
int priority,
IFinishedMotionCallback onFinishedMotionHandler
) {
if (priority == LAppDefine.Priority.FORCE.getPriority()) {
motionManager.setReservationPriority(priority);
} else if (!motionManager.reserveMotion(priority)) {
if (debugMode) {
LAppPal.printLog("Cannot start motion.");
}
return -1;
}
/*モーションデータ準備部分省略*/
if (motionManager.startMotionPriority(motion, priority) != -1) {
return motionManager.startMotionPriority(motion, priority);
}
return -1;
}
```
--------------------------------
### Start Motion in Java
Source: https://docs.live2d.com/cubism-sdk-manual/motion
Initiates a motion playback by adding it to the queue and setting fade-out flags for existing motions.
```Java
public int startMotion(ACubismMotion motion, float userTimeSeconds) {
if (motion == null) {
return -1;
}
// 既にモーションがあれば終了フラグを立てる
for (CubismMotionQueueEntry entry : motions){
if (entry == null) {
continue;
}
entry.setFadeOut(entry.getMotion().getFadeOutTime());
}
CubismMotionQueueEntry motionQueueEntry = new CubismMotionQueueEntry();
motionQueueEntry.setMotion(motion);
motions.add(motionQueueEntry);
return System.identityHashCode(motionQueueEntry);
}
```
```Java
public int startMotion(ACubismMotion motion, float userTimeSeconds) {
if (motion == null) {
return -1;
}
// 既にモーションがあれば終了フラグを立てる
for (CubismMotionQueueEntry entry : motions){
if (entry == null) {
continue;
}
entry.setFadeOut(entry.getMotion().getFadeOutTime());
}
CubismMotionQueueEntry motionQueueEntry = new CubismMotionQueueEntry();
motionQueueEntry.setMotion(motion);
motions.add(motionQueueEntry);
return System.identityHashCode(motionQueueEntry);
}
```
--------------------------------
### Initialize CubismLookController on Start
Source: https://docs.live2d.com/cubism-sdk-manual/lookat-unity
Ensures the controller's cache is initialized when the component starts. It sets a default center if none is assigned and then calls Refresh() to prepare the parameter references.
```csharp
///
/// Called by Unity. Makes sure cache is initialized.
///
private void Start()
{
// Default center if necessary.
if (Center == null)
{
Center = GetComponent() as Object;
}
// Initialize cache.
Refresh();
}
```
--------------------------------
### Get Parts Info (Native C++)
Source: https://docs.live2d.com/cubism-sdk-manual/cdi3json
Iterates through all parts to retrieve their IDs and names. Ensure cdiJson is initialized.
```cpp
// 総パーツ数
csmInt32 partsCount = cdiJson->GetPartsCount();
for(int i = 0; i < partsCount; i++)
{
// パーツID
csmChar* partId = cdiJson->GetPartsId(i);
// パーツ名
csmChar* partName = cdiJson->GetPartsName(i);
}
```
--------------------------------
### Initialize CubismHarmonicMotionController on Start
Source: https://docs.live2d.com/cubism-sdk-manual/harmonicmotion-cocos
Called by Cocos Creator when the component starts. Ensures the cache is initialized by calling the refresh method to get initial parameter references.
```typescript
/** Called by Cocos Creator. Makes sure cache is initialized. */
protected start() {
// Initialize cache.
this.refresh();
}
```
--------------------------------
### Cubism SDKの初期化
Source: https://docs.live2d.com/cubism-sdk-manual/framework-init-close-java
startUp実行後にCubismFramework.initializeを呼び出します。アプリケーション内で一度だけ実行してください。
```Java
// Java
public void onSurfaceCreated() {
// テクスチャサンプリング設定
GLES20.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
GLES20.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// 透過設定
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Initialize Cubism SDK framework
CubismFramework.initialize();
// シェーダーの初期化
view.initializeShader();
}
```
--------------------------------
### ACubismMotion Class Callbacks
Source: https://docs.live2d.com/cubism-sdk-manual/callback-motion-end-native
The ACubismMotion class provides methods to set and get handlers for motion playback start and end callbacks. These callbacks are invoked when a motion begins or finishes playing.
```APIDOC
## ACubismMotion Class Callbacks
### Description
This section details the callback mechanisms within the `ACubismMotion` class for handling motion playback events.
### Methods
#### `typedef void (*BeganMotionCallback)(ACubismMotion* self);`
Defines the function signature for the motion playback start callback.
#### `typedef void (*FinishedMotionCallback)(ACubismMotion* self);`
Defines the function signature for the motion playback end callback.
#### `void SetBeganMotionHandler(BeganMotionCallback onBeganMotionHandler);`
Registers a callback function to be invoked when motion playback begins.
#### `void SetFinishedMotionHandler(FinishedMotionCallback onFinishedMotionHandler);`
Registers a callback function to be invoked when motion playback ends.
#### `BeganMotionCallback GetBeganMotionHandler() const;`
Retrieves the currently registered motion playback start callback handler.
#### `FinishedMotionCallback GetFinishedMotionHandler();`
Retrieves the currently registered motion playback end callback handler.
### Private Members
#### `BeganMotionCallback _onBeganMotion;`
Internal variable to store the motion playback start callback.
#### `FinishedMotionCallback _onFinishedMotion;`
Internal variable to store the motion playback end callback.
### Tips
Callbacks may not be invoked under the following conditions:
- When the currently playing motion is set to loop.
- When NULL is registered as the callback.
```
--------------------------------
### Get Parameter Information (Java)
Source: https://docs.live2d.com/cubism-sdk-manual/cdi3json
Retrieve the total number of parameters and then loop to get each parameter's ID, parent group ID, and name using the respective get methods.
```java
// 総パラメータ数
int parametersCount = cdiJson.getParametersCount();
for (int i = 0; i < parametersCount; i++) {
// パラメータID
String parameterId = cdiJson.getParametersId(i);
// 所属パラメータグループID
String parentParameterGroupId = cdiJson.getParametersGroupId(i);
// パラメータ名
String parameterName = cdiJson.getParametersName(i);
}
```
--------------------------------
### CubismMotion.create with Callbacks
Source: https://docs.live2d.com/cubism-sdk-manual/callback-motion-end-web
Demonstrates the static `create` method of `CubismMotion` which allows for the registration of callback functions to handle the beginning and end of motion playback.
```APIDOC
## CubismMotion.create with Callbacks
### Description
This method creates a `CubismMotion` instance and allows for the optional registration of callback functions to be invoked when a motion begins or finishes.
### Method Signature
`public static create( buffer: ArrayBuffer, size: number, onFinishedMotionHandler?: FinishedMotionCallback, onBeganMotionHandler?: BeganMotionCallback ): CubismMotion`
### Parameters
- **buffer** (ArrayBuffer) - The buffer containing the motion data.
- **size** (number) - The size of the motion data buffer.
- **onFinishedMotionHandler** (FinishedMotionCallback, optional) - A callback function to be executed when the motion finishes.
- **onBeganMotionHandler** (BeganMotionCallback, optional) - A callback function to be executed when the motion begins.
### Return Value
- **CubismMotion** - An instance of `CubismMotion` with the specified motion data and registered callbacks.
### Code Example
```typescript
public static create(
buffer: ArrayBuffer,
size: number,
onFinishedMotionHandler?: FinishedMotionCallback,
onBeganMotionHandler?: BeganMotionCallback
): CubismMotion {
const ret = new CubismMotion();
ret.parse(buffer, size);
ret._sourceFrameRate = ret._motionData.fps;
ret._loopDurationSeconds = ret._motionData.duration;
// コールバック関数の登録
ret._onFinishedMotion = onFinishedMotionHandler;
ret._onBeganMotion = onBeganMotionHandler;
return ret;
}
```
```
--------------------------------
### Initialize Cache in Start
Source: https://docs.live2d.com/cubism-sdk-manual/harmonicmotion
Ensures the controller cache is initialized when the component starts.
```csharp
///
/// Called by Unity. Makes sure cache is initialized.
///
private void Start()
{
// Initialize cache.
Refresh();
}
```
--------------------------------
### Framework Startup
Source: https://docs.live2d.com/cubism-sdk-manual/framework-init-close-web
Initializes the Cubism Framework by setting up logging options. This function must be called before CubismFramework.initialize().
```APIDOC
## Framework Startup
### Description
Initializes the Cubism Framework by setting up logging options. This function must be called before `CubismFramework.initialize()`.
### Method
`CubismFramework.startUp(cubismOption)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **cubismOption** (Option) - Required - An object containing logging options.
- **logFunction** (Function) - Optional - A function to handle log messages. Defaults to `LAppPal.printMessage`.
- **loggingLevel** (LogLevel) - Optional - The desired logging level. Defaults to `LogLevel.LogLevel_Info`.
### Request Example
```typescript
let cubismOption: Option;
// prepare for Cubism Framework API.
cubismOption.logFunction = LAppPal.printMessage;
cubismOption.loggingLevel = LogLevel.LogLevel_Info;
CubismFramework.startUp(cubismOption);
```
### Response
#### Success Response (200)
No explicit response body is defined, but successful startup may lead to version information being logged.
#### Response Example
```
[CSM][I]Live2D Cubism Core version: 03.00.0003 (50331651)
```
```
--------------------------------
### Apply Layout from model3.json (Java)
Source: https://docs.live2d.com/cubism-sdk-manual/layout
Use CubismModelMatrix.setupFromLayout with a layout map obtained from CubismModelSettingJson. This is for Java implementations.
```java
CubismModelSettingJson model3Json;
Map layout = new HashMap();
model3Json.getLayoutMap(layout);
// モデルのレイアウトを設定
cubismModelMatrix.setupFromLayout(layout);
```
--------------------------------
### Obtaining Transformed Coordinates
Source: https://docs.live2d.com/cubism-sdk-manual/layout
Functions to get coordinates transformed by the matrix. `TransformX` and `TransformY` are used to get the screen position from model vertex coordinates. `InvertTransformX` and `InvertTransformY` are used to get model coordinates from screen coordinates (e.g., for hit detection).
```APIDOC
## CubismMatrix44::TransformX & CubismMatrix44::TransformY (Native C++)
### Description
Gets the screen position from the model's vertex coordinates in the local coordinate system.
### Method
`CubismMatrix44::TransformX(localX)`
`CubismMatrix44::TransformY(localY)`
### Parameters
- **localX** (csmFloat32) - The X-coordinate in the local coordinate system.
- **localY** (csmFloat32) - The Y-coordinate in the local coordinate system.
### Response
#### Success Response
- **positionX** (csmFloat32) - The X-coordinate on the screen.
- **positionY** (csmFloat32) - The Y-coordinate on the screen.
### Request Example
```cpp
csmFloat32 positionX = cubismMatrix44->TransformX(localX);
csmFloat32 positionY = cubismMatrix44->TransformY(localY);
```
```
```APIDOC
## CubismMatrix44.transformX & CubismMatrix44.transformY (Web/Typescript & Java)
### Description
Gets the screen position from the model's vertex coordinates in the local coordinate system.
### Method
`CubismMatrix44.transformX(localX)`
`CubismMatrix44.transformY(localY)`
### Parameters
- **localX** (number/float) - The X-coordinate in the local coordinate system.
- **localY** (number/float) - The Y-coordinate in the local coordinate system.
### Response
#### Success Response
- **positionX** (number/float) - The X-coordinate on the screen.
- **positionY** (number/float) - The Y-coordinate on the screen.
### Request Example
```typescript
let positionX: number = cubismMatrix44.transformX(localX);
let positionY: number = cubismMatrix44.transformY(localY);
```
```java
float positionX = cubismMatrix44.transformX(localX);
float positionY = cubismMatrix44.transformY(localY);
```
```
```APIDOC
## CubismMatrix44::InvertTransformX & CubismMatrix44::InvertTransformY (Native C++)
### Description
Gets the model's local coordinates from the input coordinates in the screen coordinate system.
### Method
`CubismMatrix44::InvertTransformX(inputPositionX)`
`CubismMatrix44::InvertTransformY(inputPositionY)`
### Parameters
- **inputPositionX** (csmFloat32) - The X-coordinate in the screen coordinate system.
- **inputPositionY** (csmFloat32) - The Y-coordinate in the screen coordinate system.
### Response
#### Success Response
- **localX** (csmFloat32) - The X-coordinate in the local coordinate system.
- **localY** (csmFloat32) - The Y-coordinate in the local coordinate system.
### Request Example
```cpp
csmFloat32 localX = cubismMatrix44->InvertTransformX(inputPositionX);
csmFloat32 localY = cubismMatrix44->InvertTransformY(inputPositionY);
```
```
```APIDOC
## CubismMatrix44.invertTransformX & CubismMatrix44.invertTransformY (Web/Typescript & Java)
### Description
Gets the model's local coordinates from the input coordinates in the screen coordinate system.
### Method
`CubismMatrix44.invertTransformX(inputPositionX)`
`CubismMatrix44.invertTransformY(inputPositionY)`
### Parameters
- **inputPositionX** (number/float) - The X-coordinate in the screen coordinate system.
- **inputPositionY** (number/float) - The Y-coordinate in the screen coordinate system.
### Response
#### Success Response
- **localX** (number/float) - The X-coordinate in the local coordinate system.
- **localY** (number/float) - The Y-coordinate in the local coordinate system.
### Request Example
```typescript
let localX: number = cubismMatrix44.invertTransformX(inputPositionX);
let localY: number = cubismMatrix44.invertTransformY(inputPositionY);
```
```java
float localX = cubismMatrix44.invertTransformX(inputPositionX);
float localY = cubismMatrix44.invertTransformY(inputPositionY);
```
```
--------------------------------
### Cubism SDKの起動設定
Source: https://docs.live2d.com/cubism-sdk-manual/framework-init-close-java
CubismFramework.startUpを呼び出してログオプションを設定します。この処理はCubismFramework.initializeの前に実行する必要があります。
```Java
// Java
private LAppDelegate() {
currentModel = ModelDir.values()[0];
// Set up Cubism SDK framework.
cubismOption.logFunction = new LAppPal.PrintLogFunction();
cubismOption.loggingLevel = LAppDefine.cubismLoggingLevel;
CubismFramework.cleanUp();
CubismFramework.startUp(cubismOption);
}
private final CubismFramework.Option cubismOption = new CubismFramework.Option();
```
--------------------------------
### Apply Layout from model3.json (C++)
Source: https://docs.live2d.com/cubism-sdk-manual/layout
Use CubismModelMatrix::SetupFromLayout with a layout map obtained from CubismModelSettingJson. This is for Native (C++) implementations.
```cpp
CubismModelSettingJson* model3Json;
csmMap layout;
model3Json->GetLayoutMap(layout);
// モデルのレイアウトを設定。
cubismModelMatrix->SetupFromLayout(layout);
```
--------------------------------
### Registering Animation Start Callbacks in Unity
Source: https://docs.live2d.com/cubism-sdk-manual/motion-unity
Registers a custom function to the AnimationBeginHandler to detect when a specific motion starts playing.
```csharp
private CubismMotionController _motionController;
private CubismFadeMotionList _cubismFadeMotionList;
// Start is called before the first frame update
private void Start()
{
_motionController = GetComponent();
_cubismFadeMotionList = GetComponent().CubismFadeMotionList;
_motionController.AnimationBeginHandler += OnAnimationBegin;
}
private void OnAnimationBegin(int instanceId)
{
if (!_cubismFadeMotionList)
{
return;
}
for (int i = 0; i < _cubismFadeMotionList.MotionInstanceIds.Length; i++)
{
if (_cubismFadeMotionList.MotionInstanceIds[i] != instanceId)
{
continue;
}
Debug.Log("StartedMotion: " + _cubismFadeMotionList.CubismFadeMotionObjects[i].MotionName);
break;
}
}
```
--------------------------------
### Create CubismPhysics Instance (Java)
Source: https://docs.live2d.com/cubism-sdk-manual/physics
Initializes a CubismPhysics instance in Java by providing a buffer created from the .physics3.json file.
```java
String path = "example.physics3.json";
buffer = createBuffer(path);
CubismPhysics physics = CubismPhysics.create(buffer);
```
--------------------------------
### Start Motion in CubismMotionQueueManager
Source: https://docs.live2d.com/cubism-sdk-manual/motion
Initiates a motion and handles existing motions by triggering their fade-out process. Returns a handle for the started motion.
```TypeScript
// TypeScript
/**
* 指定したモーションの開始
*
* 指定したモーションを開始する。同じタイプのモーションが既にある場合は、既存のモーションに終了フラグを立て、フェードアウトを開始させる。
*
* @param motion 開始するモーション
* @param autoDelete 再生が終了したモーションのインスタンスを削除するなら true
* @param userTimeSeconds デルタ時間の積算値[秒]
* @return 開始したモーションの識別番号を返す。個別のモーションが終了したか否かを判定するIsFinished()の引数で使用する。開始できない時は「-1」
*/
public startMotion(motion: ACubismMotion, autoDelete: boolean, userTimeSeconds: number) : CubismMotionQueueEntryHandle
{
if(motion == null)
{
return InvalidMotionQueueEntryHandleValue;
}
let motionQueueEntry: CubismMotionQueueEntry = null;
// 既にモーションがあれば終了フラグを立てる
for(let i: number = 0; i < this._motions.length; ++i)
{
motionQueueEntry = this._motions[i];
if(motionQueueEntry == null)
{
continue;
}
motionQueueEntry.startFadeout(motionQueueEntry._motion.getFadeOutTime(), userTimeSeconds); // フェードアウトを開始し終了する
}
motionQueueEntry = new CubismMotionQueueEntry(); // 終了時に破棄する
motionQueueEntry._autoDelete = autoDelete;
motionQueueEntry._motion = motion;
this._motions.pushBack(motionQueueEntry);
return motionQueueEntry._motionQueueEntryHandle;
}
```
```TypeScript
// TypeScript
/**
* 指定したモーションの開始
*
* 指定したモーションを開始する。同じタイプのモーションが既にある場合は、既存のモーションに終了フラグを立て、フェードアウトを開始させる。
*
* @param motion 開始するモーション
* @param autoDelete 再生が終了したモーションのインスタンスを削除するなら true
* @param userTimeSeconds デルタ時間の積算値[秒]
* @return 開始したモーションの識別番号を返す。個別のモーションが終了したか否かを判定するIsFinished()の引数で使用する。開始できない時は「-1」
*/
public startMotion(motion: ACubismMotion, autoDelete: boolean, userTimeSeconds: number) : CubismMotionQueueEntryHandle
{
if(motion == null)
{
return InvalidMotionQueueEntryHandleValue;
}
let motionQueueEntry: CubismMotionQueueEntry = null;
// 既にモーションがあれば終了フラグを立てる
for(let i: number = 0; i < this._motions.length; ++i)
{
motionQueueEntry = this._motions[i];
if(motionQueueEntry == null)
{
continue;
}
motionQueueEntry.startFadeout(motionQueueEntry._motion.getFadeOutTime(), userTimeSeconds); // フェードアウトを開始し終了する
}
motionQueueEntry = new CubismMotionQueueEntry(); // 終了時に破棄する
motionQueueEntry._autoDelete = autoDelete;
motionQueueEntry._motion = motion;
this._motions.pushBack(motionQueueEntry);
return motionQueueEntry._motionQueueEntryHandle;
}
```
--------------------------------
### Implement Motion Start and End Callbacks
Source: https://docs.live2d.com/cubism-sdk-manual/callback-motion-end-native
Implement these functions to define actions when a motion begins or finishes. The sample logs messages using LAppPal::PrintLog.
```cpp
void BeganMotion(ACubismMotion* self)
{
LAppPal::PrintLog("Motion Began: %x", self);
}
void FinishedMotion(ACubismMotion* self)
{
LAppPal::PrintLog("Motion Finished: %x", self);
}
```
--------------------------------
### Initialize CubismEyeBlinkController on Start
Source: https://docs.live2d.com/cubism-sdk-manual/eyeblink-unity
This method is called by Unity at the start of the application. It ensures that the controller's cache is initialized by calling the Refresh() method.
```csharp
///
/// Called by Unity. Makes sure cache is initialized.
///
private void Start()
{
// Initialize cache.
Refresh();
}
```
--------------------------------
### TypeScript: ユーザトリガーコールバックの実装と登録
Source: https://docs.live2d.com/cubism-sdk-manual/motion
SampleClass内でコールバックを定義し、motionManagerに登録する例です。
```TypeScript
// TypeScript
class SampleClass
{
public userTriggerEventFired(userTriggerValue): void
{
// 処理
}
public static sampleCallback(caller: CubismMotionQueueManager,
userTriggerValue: string, customData: any): void
{
let sample: SampleClass = customData;
if(sample != null)
{
sample.userTriggerEventFired(userTriggerValue);
}
}
};
let sampleA: SampleClass = new SampleClass();
motionManager.setUserTriggerCallback(SampleClass.sampleCallback, sampleA);
```
--------------------------------
### Get Transformed Coordinates (Java)
Source: https://docs.live2d.com/cubism-sdk-manual/layout
Use CubismMatrix44.transformX and CubismMatrix44.transformY to get the screen position from the model's vertex coordinates in the local coordinate system.
```java
float positionX = cubismMatrix44.transformX(localX);
float positionY = cubismMatrix44.transformY(localY);
```
--------------------------------
### Get Transformed Coordinates (Web/TypeScript)
Source: https://docs.live2d.com/cubism-sdk-manual/layout
Use CubismMatrix44.transformX and CubismMatrix44.transformY to get the screen position from the model's vertex coordinates in the local coordinate system.
```typescript
let positionX: number = cubismMatrix44.transformX(localX);
let positionY: number = cubismMatrix44.transformY(localY);
```
--------------------------------
### C++でモーションインスタンスを作成する
Source: https://docs.live2d.com/cubism-sdk-manual/motion
CreateBufferで読み込んだバッファとサイズを使用してCubismMotionインスタンスを生成します。
```cpp
// C++
csmString path = "example.motion3.json";
csmByte* buffer;
csmSizeInt size;
buffer = CreateBuffer(path.GetRawString(), &size);
CubismMotion* motion = CubismMotion::Create(buffer, size);
```
--------------------------------
### Pass Callback Object to Start Motion
Source: https://docs.live2d.com/cubism-sdk-manual/point-to-note-java
Pass an instance of the custom callback class (e.g., finishedMotion) as an argument when starting a motion to receive completion notifications.
```java
public void onTap(float x, float y) {
...
for (LAppModel model : models){
...
model.startRandomMotion(MotionGroup.TAP_BODY.getId(), Priority.NORMAL.getPriority(), finishedMotion);
...
}
}
```
--------------------------------
### Get Transformed Coordinates (C++)
Source: https://docs.live2d.com/cubism-sdk-manual/layout
Use CubismMatrix44::TransformX and CubismMatrix44::TransformY to get the screen position from the model's vertex coordinates in the local coordinate system.
```cpp
csmFloat32 positionX = cubismMatrix44->TransformX(localX);
csmFloat32 positionY = cubismMatrix44->TransformY(localY);
```
--------------------------------
### Apply Motion and Update Model
Source: https://docs.live2d.com/cubism-sdk-manual/cubismnativeframework
Illustrates the recommended order of operations where motion playback occurs before custom parameter manipulation and the final model update.
```cpp
// 再生中のモーションをモデルに反映
_motionManager->UpdateMotion(_model, deltaTimeSeconds);
// 視線追従などの値操作や物理演算処理
// モデルの頂点情報を更新
_model->Update();
```
--------------------------------
### Initialize Expression Motion in Java
Source: https://docs.live2d.com/cubism-sdk-manual/expression
This snippet shows the beginning of loading expression motion data in Java, iterating through expressions and preparing to create buffers.
```java
final int count = modelSetting.getExpressionCount();
for (int i = 0; i < count; i++) {
String name = modelSetting.getExpressionName(i);
String path = modelSetting.getExpressionFileName(i);
path = modelHomeDirectory + path;
byte[] buffer = createBuffer(path);
```
--------------------------------
### Get User Data from Parsed .userdata3.json
Source: https://docs.live2d.com/cubism-sdk-manual/json-cocos
Retrieve user data from a parsed .userdata3.json object using CubismUserData3Json.toBodyArray(). Specify CubismUserDataTargetType.ArtMesh to get data for art meshes.
```typescript
const drawableBodies = userData3Json.toBodyArray(
CubismUserDataTargetType.ArtMesh
);
```
--------------------------------
### Implement Motion Start and End Callbacks
Source: https://docs.live2d.com/cubism-sdk-manual/callback-motion-end-web
Implement custom logic for motion start and end events. These functions can be modified to change the behavior when a motion begins or finishes.
```typescript
_beganMotion = (self: ACubismMotion) => {
LAppPal.printMessage("Motion Began:");
console.log(self);
}
_finishedMotion = (self: ACubismMotion) => {
LAppPal.printMessage("Motion Finished:");
console.log(self);
}
```
--------------------------------
### Initialize CubismMotion from Buffer
Source: https://docs.live2d.com/cubism-sdk-manual/sdk-type-for-motiopn
Parses a motion buffer and initializes frame rate and duration settings.
```cpp
CubismMotion* CubismMotion::Create(const csmByte* buffer, csmSizeInt size)
{
CubismMotion* ret = CSM_NEW CubismMotion();
ret->Parse(buffer, size);
ret->_sourceFrameRate = ret->_motionData->Fps;
ret->_loopDurationSeconds = ret->_motionData->Duration;
// NOTE: Editorではループありのモーション書き出しは非対応
// ret->_loop = (ret->_motionData->Loop > 0);
return ret;
}
```
--------------------------------
### Initialize Cubism Framework
Source: https://docs.live2d.com/cubism-sdk-manual/framework-init-close
Call this function once before using the framework. It must be called after CubismFramework::StartUp.
```cpp
// C++
CubismFramework::Initialize();
```
--------------------------------
### CubismRaycaster.Start()
Source: https://docs.live2d.com/cubism-sdk-manual/raycasting-unity
Called by Unity during initialization. Ensures the cache of raycastables is initialized by calling Refresh().
```APIDOC
## CubismRaycaster.Start()
### Description
Called by Unity. Makes sure cache is initialized.
### Method
private void Start()
### Code Example
```csharp
private void Start()
{
// Initialize cache.
Refresh();
}
```
```
--------------------------------
### Play Expression Motion (Java)
Source: https://docs.live2d.com/cubism-sdk-manual/expression
Start an expression motion using the expressionManager with a specified priority. Ensure the motion is loaded and not null.
```java
ACubismMotion motion = expressions.get(expressionID); // loaded CubismExpression
if (motion != null){
expressionManager.startMotionPriority(motion, LAppDefine.Priority.FORCE.getPriority());
}
```
--------------------------------
### Initialize and Refresh CubismRaycaster
Source: https://docs.live2d.com/cubism-sdk-manual/raycasting-unity
Call Refresh() after adding or removing CubismRaycastable components to update the raycaster's cache. The Start() method ensures the cache is initialized upon game start.
```csharp
///
/// Refreshes the controller. Call this method after adding and/or removing .
///
private void Refresh()
{
var candidates = this
.FindCubismModel()
.Drawables;
// Find raycastable drawables.
var raycastables = new List();
var raycastablePrecisions = new List();
for (var i = 0; i < candidates.Length; i++)
{
// Skip non-raycastables.
if (candidates[i].GetComponent() == null)
{
continue;
}
raycastables.Add(candidates[i].GetComponent());
raycastablePrecisions.Add(candidates[i].GetComponent().Precision);
}
// Cache raycastables.
Raycastables = raycastables.ToArray();
RaycastablePrecisions = raycastablePrecisions.ToArray();
}
...
///
/// Called by Unity. Makes sure cache is initialized.
///
private void Start()
{
// Initialize cache.
Refresh();
}
```
--------------------------------
### Apply Layout from model3.json (TypeScript)
Source: https://docs.live2d.com/cubism-sdk-manual/layout
Use CubismModelMatrix.setupFromLayout with a layout map obtained from CubismModelSettingJson. This is for Web (TypeScript) implementations.
```typescript
let model3Json: CubismModelSettingJson;
let layout: Map
model3Json.getLayoutMap(layout);
// モデルのレイアウトを設定。
cubismModelMatrix.setupFromLayout(layout);
```
--------------------------------
### Start Lip Sync Motion with Priority (TypeScript)
Source: https://docs.live2d.com/cubism-sdk-manual/lipsync
This TypeScript code starts a lip sync motion with a specified priority. Use this when you need to control the lip sync animation directly.
```TypeScript
// TypeScript
_mouseMotionManager.startMotionPriority(lipSyncMotion, autoDelete, priority);
```
```TypeScript
// TypeScript
_mouseMotionManager.startMotionPriority(lipSyncMotion, autoDelete, priority);
```
--------------------------------
### C++でのモーション再生
Source: https://docs.live2d.com/cubism-sdk-manual/motion
StartMotionPriority関数を使用してモーションを再生します。優先度と自動削除フラグを指定します。
```cpp
// C++
csmBool autoDelete = true;
csmInt32 priority = PriorityNormal;// 2
motionManager->StartMotionPriority( motion, autoDelete, priority);
```
```cpp
// C++
csmBool autoDelete = true;
csmInt32 priority = PriorityNormal;// 2
motionManager->StartMotionPriority( motion, autoDelete, priority);
```
--------------------------------
### Calculate Random Blink Start Time (C++)
Source: https://docs.live2d.com/cubism-sdk-manual/eyeblink-ue
Calculates the start time for a blink action, incorporating randomness based on the Mean and MaximumDeviation parameters. This is used for automatic blinking behavior.
```cpp
StartTime = Mean + FMath::FRandRange(-MaximumDeviation, MaximumDeviation);
```
--------------------------------
### Play Expression Motion (C++)
Source: https://docs.live2d.com/cubism-sdk-manual/expression
Start an expression motion using the expressionManager. Ensure the motion is loaded and not null before attempting to play.
```cpp
ACubismMotion* motion = _expressions[expressionID];//loaded CubismExpression
if (motion != NULL)
{
expressionManager->StartMotion(motion, false);
}
```
--------------------------------
### Get Parameter Index and Set Value by Index (TypeScript)
Source: https://docs.live2d.com/cubism-sdk-manual/parameters
In TypeScript, use CubismModel.getParameterIndex to get the parameter's index. Subsequently, use setParameterValueByIndex with the obtained index to modify parameter values.
```typescript
// TypeScript
// 初期化時
let paramAngleX: number;
paramAngleX = _model.getParameterIndex(CubismFramework.getIdManager().getId("ParamAngleX"));
// パラメータの設定時
_model.setParameterValueByIndex(paramAngleX, 30.0, 1.0);
```
--------------------------------
### Get Inverted Transformed Coordinates (Java)
Source: https://docs.live2d.com/cubism-sdk-manual/layout
Use CubismMatrix44.invertTransformX and CubismMatrix44.invertTransformY to get the model's local coordinates from input coordinates in the screen's coordinate system, typically used for hit detection.
```java
float localX = cubismMatrix44.invertTransformX(inputPositionX);
float localY = cubismMatrix44.invertTransformY(inputPositionY);
```
--------------------------------
### Javaでのモーション再生
Source: https://docs.live2d.com/cubism-sdk-manual/motion
startMotionPriority関数を使用してモーションを再生します。優先度と自動削除フラグを指定します。
```java
// Java
boolean autoDelete = true;
int priority = LAppDefine.Priority.NORMAL; // 2
motionManager.startMotionPriority(motion, autoDelete, priority);
```
```java
// Java
boolean autoDelete = true;
int priority = LAppDefine.Priority.NORMAL; // 2
motionManager.startMotionPriority(motion, autoDelete, priority);
```
--------------------------------
### SRP対応環境におけるモデル更新処理の実装
Source: https://docs.live2d.com/cubism-sdk-manual/cubism-sdk-for-unity-parameter
Unity 2018.1以降のSRP環境で頂点更新処理を適切に実行するためのPlayerLoop登録パターンです。
```csharp
private bool WasAttachedModelUpdateFunction { get; set; }
...
///
/// Called by Unity. Triggers to update.
///
private void Update()
{
#if UNITY_2018_1_OR_NEWER
if (!WasAttachedModelUpdateFunction)
{
_modelUpdateFunctions += OnModelUpdate;
WasAttachedModelUpdateFunction = true;
}
#endif
...
///
/// Called by Unity. Destroys instance.
///
private void OnDisable()
{
#if UNITY_2018_1_OR_NEWER
if (WasAttachedModelUpdateFunction)
{
_modelUpdateFunctions -= OnModelUpdate;
WasAttachedModelUpdateFunction = false;
}
#endif
}
///
/// Called by Unity. Blockingly updates on first frame enabled; otherwise tries async update.
///
private void OnRenderObject()
{
#if !UNITY_2018_1_OR_NEWER
OnModelUpdate();
#endif
}
...
///
/// Update model states.
///
private void OnModelUpdate()
{
// 頂点の更新処理
}
```
--------------------------------
### Get Inverted Transformed Coordinates (Web/TypeScript)
Source: https://docs.live2d.com/cubism-sdk-manual/layout
Use CubismMatrix44.invertTransformX and CubismMatrix44.invertTransformY to get the model's local coordinates from input coordinates in the screen's coordinate system, typically used for hit detection.
```typescript
let localX: number = cubismMatrix44.invertTransformX(inputPositionX);
let localY: number = cubismMatrix44.invertTransformY(inputPositionY);
```
--------------------------------
### Start Lip Sync Motion with Priority (Java)
Source: https://docs.live2d.com/cubism-sdk-manual/lipsync
This Java code starts a lip sync motion with a specified priority. It's the Java equivalent of the TypeScript `startMotionPriority` function for controlling lip sync animations.
```Java
// Java
mouseMotionManager.startMotionPriority(lipSyncMotion, autoDelete, priority);
```
```Java
// Java
mouseMotionManager.startMotionPriority(lipSyncMotion, autoDelete, priority);
```
--------------------------------
### Get Inverted Transformed Coordinates (C++)
Source: https://docs.live2d.com/cubism-sdk-manual/layout
Use CubismMatrix44::InvertTransformX and CubismMatrix44::InvertTransformY to get the model's local coordinates from input coordinates in the screen's coordinate system, typically used for hit detection.
```cpp
csmFloat32 localX = cubismMatrix44->InvertTransformX(inputPositionX);
csmFloat32 localY = cubismMatrix44->InvertTransformY(inputPositionY);
```
--------------------------------
### Create CubismPhysics Instance (C++)
Source: https://docs.live2d.com/cubism-sdk-manual/physics
Instantiates a CubismPhysics class in C++ by loading physics settings from a .physics3.json file. Ensure the buffer is deleted after use.
```cpp
csmString path = "example.physics3.json";
buffer = CreateBuffer(path.GetRawString(), &size);
CubismPhysics* _physics = CubismPhysics::Create(buffer, size);
DeleteBuffer(buffer, path.GetRawString());
```
--------------------------------
### Creating a CubismMotionManager Instance
Source: https://docs.live2d.com/cubism-sdk-manual/motion
Initialize a motion manager to apply motion instances to a model. Note that syntax varies by language.
```cpp
// C++
CubismMotionManager* motionManager = CSM_NEW CubismMotionManager();
```
```typescript
// TypeScript
let motionManager: CubismMotionManager = new CubismMotionManager();
```
```java
// Java
CubismMotionManager motionManager = new CubismMotionManager();
```
--------------------------------
### Get Offscreen Screen Color
Source: https://docs.live2d.com/cubism-sdk-manual/multiply-color-screen-color-web
Retrieves the screen color of a specific offscreen as a CubismTextureColor object.
```APIDOC
## getOffscreenScreenColor
### Description
Retrieves the screen color of a specific offscreen as a CubismTextureColor object.
### Method
```typescript
public getOffscreenScreenColor(index: number): CubismTextureColor
```
### Parameters
#### Path Parameters
- **index** (number) - Required - The index of the offscreen.
```
--------------------------------
### Get Offscreen Multiply Color
Source: https://docs.live2d.com/cubism-sdk-manual/multiply-color-screen-color-web
Retrieves the multiply color of a specific offscreen as a CubismTextureColor object.
```APIDOC
## getOffscreenMultiplyColor
### Description
Retrieves the multiply color of a specific offscreen as a CubismTextureColor object.
### Method
```typescript
public getOffscreenMultiplyColor(index: number): CubismTextureColor
```
### Parameters
#### Path Parameters
- **index** (number) - Required - The index of the offscreen.
```
--------------------------------
### Create Cubism Model Instance
Source: https://docs.live2d.com/cubism-sdk-manual/model-java
Loads a .moc3 file into a buffer to initialize a CubismMoc instance, then creates a CubismModel from it.
```Java
// Java
String path = "example.moc3";
path = dir + path;
byte[] buffer = createBuffer(path);
CubismMoc moc = CubismMoc.create(buffer);
CubismModel model = moc.createModel();
```
```Java
// Java
String path = "example.moc3";
path = dir + path;
byte[] buffer = createBuffer(path);
CubismMoc moc = CubismMoc.create(buffer);
CubismModel model = moc.createModel();
```