@doki-land/live2d 0.0.9 → 0.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -1,200 +1,68 @@
1
- import '../lib/cubism2.min.js';
2
- import '../lib/cubism5.min.js';
3
- import * as PIXI from 'pixi.js';
4
-
5
- import { Ticker, TickerPlugin } from '@pixi/ticker';
6
- import {
7
- Live2DModel,
8
- MotionManager,
9
- SoundManager
10
- } from 'pixi-live2d-display-lipsyncpatch';
11
- import { Application, } from 'pixi.js';
12
- import './icons/style.css';
13
- import { Live2dOptions } from '@/types/index.js';
14
-
15
- export {MotionManager, SoundManager, Live2DModel, PIXI};
16
-
17
- /**
18
- * 创建Live2D模型
19
- * @param options 模型配置选项
20
- * @returns Promise<Live2DModel> 加载完成的Live2D模型实例
21
- */
22
- export async function createLive2D(options: Live2dOptions): Promise<Live2DModel> {
23
- const {
24
- element_id = 'live2d-canvas',
25
- models,
26
- width = 300,
27
- height = 300,
28
- auto_fit = true,
29
- auto_motion = true,
30
- mouse_tracking = true
31
- } = options;
32
- // 创建画布
33
- let element = findOrCreateCanvas(element_id, options)
34
- // 初始化PIXI应用
35
- const app = new Application({
36
- view: element,
37
- width: width,
38
- height: height,
39
- // resolution: 1,
40
- backgroundAlpha: 0,
41
- autoDensity: true,
42
- antialias: true,
43
- eventMode: 'static',
44
- eventFeatures: {
45
- move: true,
46
- globalMove: true,
47
- click: true,
48
- wheel: true
49
- }
50
- });
51
-
52
- // 加载模型
53
- const model = await Live2DModel.from(models[0].model_url, {
54
- ticker: Ticker.system,
55
- });
56
- // 添加模型到舞台
57
- app.stage.addChild(model);
58
-
59
- // 自动适应大小
60
- if (auto_fit) {
61
- // 修复auto_fit功能,确保模型不被截断且保持正确比例
62
- const scale = Math.min(width / model.width, height / model.height);
63
- model.scale.set(scale);
64
-
65
- // 居中显示,确保模型完全可见
66
- model.x = (width - model.width * scale) / 2;
67
- model.y = (height - model.height * scale) / 2;
68
- }
69
-
70
- // 启用鼠标跟踪
71
- if (mouse_tracking) {
72
- enableMouseTracking(model, app.view);
73
- }
74
-
75
- // 自动开始动画
76
- if (auto_motion) {
77
- await startIdleAnimation(model);
78
- }
79
-
80
- // 创建右侧图标栏
81
- // createIconPanel(model, element);
82
-
83
- return model;
84
- }
85
-
86
- function findOrCreateCanvas(id: string, options: Live2dOptions): HTMLCanvasElement {
87
- let canvas = document.getElementById(id) as HTMLCanvasElement;
88
- if (!canvas) {
89
- canvas = document.createElement('canvas');
90
- canvas.id = id;
91
- document.body.appendChild(canvas);
92
- canvas.style.display = 'none';
93
- canvas.style.position = 'fixed';
94
- // 设置画布样式
95
- canvas.style.display = 'block';
96
- canvas.style.position = 'absolute';
97
- canvas.style.bottom = `${options.spacing_y || 0}px`;
98
- canvas.style[options.position === 'left' ? 'left' : 'right'] = `${options.spacing_x || 0}px`;
99
- canvas.style.zIndex = '9999';
100
- }
101
- return canvas;
102
- }
103
-
104
-
105
- /**
106
- * 启用鼠标跟踪功能
107
- * @param model Live2D模型实例
108
- * @param canvas 画布元素
109
- */
110
- function enableMouseTracking(model: Live2DModel, canvas: any) {
111
- // 跟踪鼠标移动
112
- document.addEventListener('mousemove', (event) => {
113
- const rect = canvas.getBoundingClientRect();
114
- const centerX = rect.left + rect.width / 2;
115
- const centerY = rect.top + rect.height / 2;
116
-
117
- // 计算鼠标位置相对于画布中心的偏移
118
- const mouseX = (event.clientX - centerX) / rect.width;
119
- // 修正Y轴方向,使用负值来反转方向
120
- const mouseY = -(event.clientY - centerY) / rect.height;
121
-
122
- // 更新模型的视线方向
123
- if (model.internalModel) {
124
- model.internalModel.focusController?.focus(mouseX, mouseY);
125
- }
126
- });
127
-
128
- // 添加点击模型触发动作的交互
129
- canvas.addEventListener('click', () => {
130
- // 尝试播放tap_body动作,如果没有则尝试其他可用动作
131
- try {
132
- const motions = model.internalModel?.motionManager.definitions;
133
- if (motions) {
134
- if (motions.tap_body) {
135
- model.motion('tap_body');
136
- } else if (motions.tap) {
137
- model.motion('tap');
138
- } else {
139
- // 使用第一个可用的动作组
140
- const firstMotionGroup = Object.keys(motions)[0];
141
- if (firstMotionGroup) {
142
- model.motion(firstMotionGroup);
143
- }
144
- }
145
- }
146
- } catch (error) {
147
- console.warn('Failed to play tap animation:', error);
148
- }
149
- });
150
- }
151
-
152
- /**
153
- * 开始空闲动画
154
- * @param model Live2D模型实例
155
- */
156
- async function startIdleAnimation(model: Live2DModel) {
157
- // 尝试播放内置的动作组
158
- try {
159
- // 获取模型支持的动作组
160
- const motions = model.internalModel?.motionManager.definitions;
161
-
162
- if (motions) {
163
- // 优先使用Idle动作组
164
- if (motions.idle) {
165
- await model.motion('idle');
166
- } else if (motions.tap_body) {
167
- // 如果没有idle动作,尝试使用 tap_body 动作
168
- await model.motion('tap_body');
169
- } else {
170
- // 使用第一个可用的动作组
171
- const firstMotionGroup = Object.keys(motions)[0];
172
- if (firstMotionGroup) {
173
- await model.motion(firstMotionGroup);
174
- }
175
- }
176
- }
177
- } catch (error) {
178
- console.warn('Failed to start idle animation:', error);
179
- }
180
- }
181
-
182
1
  /**
183
- * 加载Cubism SDK
184
- * 在使用Live2D功能前必须调用此函数
185
- * @param cubism2 可选的CubismCore对象,如果在非浏览器环境中使用,需要传入
186
- * @param cubism5
2
+ * `@doki-land/live2d` — public facade.
3
+ *
4
+ * ```ts
5
+ * import { createLive2D } from "@doki-land/live2d";
6
+ * ```
187
7
  */
188
- export async function initializeLive2D() {
189
- // 首先初始化 Cubism2 SDK
190
- // console.log('sdk2:', Cubism2);
191
- // console.log('sdk5:', Cubism5);
192
- // @ts-ignore
193
- // window.Live2D = cubism2 || Cubism2;
194
- // 然后初始化 Cubism5 SDK
195
- // @ts-ignore
196
- // window.Live2DCubismCore = cubism5 || Cubism5().Live2DCubismCore;
197
8
 
198
- // 注册 InteractionManager 以支持 Live2D 模型的自动交互
199
- // PIXI.extensions.add(InteractionManager);
200
- }
9
+ export type {
10
+ AssetResolver,
11
+ FrameProfile,
12
+ FrameSnapshot,
13
+ InternalModel,
14
+ Live2DSession,
15
+ LoadProgress,
16
+ LoadProgressStage,
17
+ ModelFormat,
18
+ ModelInstance,
19
+ ModelProgram,
20
+ ModelSettings,
21
+ ModelSource,
22
+ SessionPhase,
23
+ SessionState,
24
+ } from "@doki-land/live2d-core";
25
+ export { EventEmitter } from "@doki-land/live2d-core";
26
+ export {
27
+ DEFAULT_NPM_CDN,
28
+ resolveModelSourceUrl,
29
+ resolveNpmSpecifier,
30
+ } from "@doki-land/live2d-loader";
31
+
32
+ export {
33
+ createCanvas2DRenderer,
34
+ createMoc2Backend,
35
+ createMoc3Backend,
36
+ createQuadProgram,
37
+ createRenderer,
38
+ createWebGl2Renderer,
39
+ createWebGpuRenderer,
40
+ decodeMoc3,
41
+ evaluateFrame,
42
+ fingerprintSnapshot,
43
+ type ModelBackend,
44
+ type ParameterBinding,
45
+ parseCpuProgram,
46
+ type Renderer,
47
+ type RendererKind,
48
+ serializeCpuProgram,
49
+ } from "@doki-land/live2d-renderer";
50
+ export {
51
+ type CreateLive2DOptions,
52
+ createLive2D,
53
+ type Live2DRuntime,
54
+ MotionPriority,
55
+ type PlayMotionOptions,
56
+ } from "./create-live2d.js";
57
+ export { focusParameterUpdates } from "./focus.js";
58
+ export {
59
+ blendMotionLayers,
60
+ evaluateCurve,
61
+ evaluateMotion3,
62
+ type Motion3Clip,
63
+ type MotionApplySample,
64
+ MotionPlayer,
65
+ parseMotion3,
66
+ } from "./motion/index.js";
67
+
68
+ export const LIVE2D_VERSION = "0.0.0" as const;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Fetch model texture images via AssetResolver → TextureData for draw passes.
3
+ */
4
+
5
+ import type { AssetResolver } from "@doki-land/live2d-core";
6
+ import type { TextureData } from "@doki-land/live2d-renderer";
7
+
8
+ export interface LoadTexturesOptions {
9
+ onProgress?: (update: {
10
+ index: number;
11
+ total: number;
12
+ key: string;
13
+ bytesLoaded: number;
14
+ bytesTotal: number | null;
15
+ }) => void;
16
+ }
17
+
18
+ function guessMime(path: string): string {
19
+ const lower = path.toLowerCase();
20
+ if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return "image/jpeg";
21
+ if (lower.endsWith(".webp")) return "image/webp";
22
+ if (lower.endsWith(".gif")) return "image/gif";
23
+ return "image/png";
24
+ }
25
+
26
+ async function bytesToImageBitmap(
27
+ bytes: ArrayBuffer,
28
+ path: string,
29
+ ): Promise<ImageBitmap> {
30
+ if (typeof createImageBitmap !== "function") {
31
+ throw new Error(
32
+ "@doki-land/live2d: createImageBitmap is not available in this environment",
33
+ );
34
+ }
35
+ const blob = new Blob([new Uint8Array(bytes)], {
36
+ type: guessMime(path),
37
+ });
38
+ return createImageBitmap(blob);
39
+ }
40
+
41
+ /** Load texture paths from a resolver into GPU-uploadable TextureData. */
42
+ export async function loadTextureData(
43
+ resolver: AssetResolver,
44
+ paths: readonly string[],
45
+ options: LoadTexturesOptions = {},
46
+ ): Promise<TextureData[]> {
47
+ const out: TextureData[] = [];
48
+ const total = paths.length;
49
+ for (let i = 0; i < paths.length; i++) {
50
+ const key = paths[i]!;
51
+ options.onProgress?.({
52
+ index: i,
53
+ total,
54
+ key,
55
+ bytesLoaded: 0,
56
+ bytesTotal: null,
57
+ });
58
+ const bytes = await resolver.fetchBytes(key);
59
+ options.onProgress?.({
60
+ index: i,
61
+ total,
62
+ key,
63
+ bytesLoaded: bytes.byteLength,
64
+ bytesTotal: bytes.byteLength,
65
+ });
66
+ const image = await bytesToImageBitmap(bytes, key);
67
+ out.push({
68
+ index: i,
69
+ image,
70
+ width: image.width,
71
+ height: image.height,
72
+ });
73
+ }
74
+ return out;
75
+ }
76
+
77
+ /** Close ImageBitmaps previously passed to setTextures. */
78
+ export function releaseTextureData(textures: readonly TextureData[]): void {
79
+ for (const t of textures) {
80
+ const img = t.image;
81
+ if (typeof ImageBitmap !== "undefined" && img instanceof ImageBitmap) {
82
+ img.close();
83
+ }
84
+ }
85
+ }
@@ -0,0 +1,119 @@
1
+ import type { Motion3Clip, MotionCurve, MotionSegment } from "./types.js";
2
+
3
+ /**
4
+ * Sample all curves of a clip at `timeSeconds` (clamped to [0, duration]
5
+ * unless looping — caller should wrap time for loops).
6
+ */
7
+ export function evaluateMotion3(
8
+ clip: Motion3Clip,
9
+ timeSeconds: number,
10
+ ): Array<{ target: MotionCurve["target"]; id: string; value: number }> {
11
+ const t = clamp(timeSeconds, 0, clip.duration);
12
+ const out: Array<{
13
+ target: MotionCurve["target"];
14
+ id: string;
15
+ value: number;
16
+ }> = [];
17
+ for (const curve of clip.curves) {
18
+ out.push({
19
+ target: curve.target,
20
+ id: curve.id,
21
+ value: evaluateCurve(curve, t, clip.areBeziersRestricted),
22
+ });
23
+ }
24
+ return out;
25
+ }
26
+
27
+ export function evaluateCurve(
28
+ curve: MotionCurve,
29
+ timeSeconds: number,
30
+ areBeziersRestricted: boolean,
31
+ ): number {
32
+ const segs = curve.segments;
33
+ if (segs.length === 0) return 0;
34
+
35
+ if (timeSeconds <= segs[0]!.p0.time) return segs[0]!.p0.value;
36
+ const last = segs[segs.length - 1]!;
37
+ if (timeSeconds >= last.p3.time) return last.p3.value;
38
+
39
+ for (let i = 0; i < segs.length; i += 1) {
40
+ const seg = segs[i]!;
41
+ const isLast = i === segs.length - 1;
42
+ // At a segment boundary, hand off to the next segment so stepped ends
43
+ // expose their end value as the next key.
44
+ if (
45
+ timeSeconds < seg.p3.time ||
46
+ (isLast && timeSeconds <= seg.p3.time)
47
+ ) {
48
+ return evaluateSegment(seg, timeSeconds, areBeziersRestricted);
49
+ }
50
+ }
51
+ return last.p3.value;
52
+ }
53
+
54
+ function evaluateSegment(
55
+ seg: MotionSegment,
56
+ time: number,
57
+ areBeziersRestricted: boolean,
58
+ ): number {
59
+ const { p0, p3 } = seg;
60
+ switch (seg.kind) {
61
+ case "linear": {
62
+ const span = p3.time - p0.time;
63
+ if (span <= 0) return p3.value;
64
+ const u = (time - p0.time) / span;
65
+ return p0.value + (p3.value - p0.value) * u;
66
+ }
67
+ case "stepped":
68
+ return p0.value;
69
+ case "inverseStepped":
70
+ return p3.value;
71
+ case "bezier": {
72
+ const p1 = seg.p1!;
73
+ const p2 = seg.p2!;
74
+ if (areBeziersRestricted) {
75
+ const span = p3.time - p0.time;
76
+ if (span <= 0) return p3.value;
77
+ const u = (time - p0.time) / span;
78
+ return cubic(p0.value, p1.value, p2.value, p3.value, u);
79
+ }
80
+ // Unrestricted: solve cubic for time, then sample value.
81
+ const u = solveBezierTime(p0.time, p1.time, p2.time, p3.time, time);
82
+ return cubic(p0.value, p1.value, p2.value, p3.value, u);
83
+ }
84
+ default:
85
+ return p3.value;
86
+ }
87
+ }
88
+
89
+ function cubic(a: number, b: number, c: number, d: number, t: number): number {
90
+ const u = 1 - t;
91
+ return (
92
+ u * u * u * a + 3 * u * u * t * b + 3 * u * t * t * c + t * t * t * d
93
+ );
94
+ }
95
+
96
+ /** Binary-search parameter u in [0,1] so cubic(time) ~= targetTime. */
97
+ function solveBezierTime(
98
+ t0: number,
99
+ t1: number,
100
+ t2: number,
101
+ t3: number,
102
+ target: number,
103
+ ): number {
104
+ let lo = 0;
105
+ let hi = 1;
106
+ for (let i = 0; i < 20; i += 1) {
107
+ const mid = (lo + hi) * 0.5;
108
+ const x = cubic(t0, t1, t2, t3, mid);
109
+ if (x < target) lo = mid;
110
+ else hi = mid;
111
+ }
112
+ return (lo + hi) * 0.5;
113
+ }
114
+
115
+ function clamp(n: number, min: number, max: number): number {
116
+ if (n < min) return min;
117
+ if (n > max) return max;
118
+ return n;
119
+ }
@@ -0,0 +1,20 @@
1
+ export { evaluateCurve, evaluateMotion3 } from "./evaluate-curve.js";
2
+ export {
3
+ blendMotionLayers,
4
+ MotionPlayer,
5
+ type MotionPlayerHandlers,
6
+ } from "./motion-player.js";
7
+ export { parseMotion3 } from "./parse-motion3.js";
8
+ export type {
9
+ Motion3Clip,
10
+ MotionApplySample,
11
+ MotionCurve,
12
+ MotionCurveTarget,
13
+ MotionPoint,
14
+ MotionPriorityLevel,
15
+ MotionSegment,
16
+ MotionSegmentKind,
17
+ MotionUserData,
18
+ PlayMotionOptions,
19
+ } from "./types.js";
20
+ export { MotionPriority } from "./types.js";