Web 연동
React 없이 DOM 기반 앱에 캐릭터를 연결하는 방법이다. 앱은 캐릭터가 표시될 요소, 이동 위치, 상호작용 대상을 등록한다.
구성
flowchart LR
App[Web application] --> Load[Public Content validation]
App --> Session[Runtime / autonomy session]
App --> Registry[Public Host registry]
App --> Geometry[Browser Host geometry adapter]
Registry --> Selector[Host target selector]
Geometry --> Coordinator[Browser Runtime coordinator]
Selector --> Coordinator
Session --> Coordinator
Coordinator --> Renderer[Application renderer]
실행 가능한 예제
저장소 내 Vite/TypeScript 앱에서 @charaweave/core, @charaweave/browser, @charaweave/content를 workspace 의존성으로 추가하고 필요한 패키지를 빌드한다. SDK는 npm에 배포되지 않았다. 일반 Core 세션은 Content V10을 사용한다.
apps/runtime-playground/public/demo-character-cw019c-simple-cat/의 V7 예제를 Vite 앱의 public/ 디렉터리에 같은 이름으로 복사한다. 패키지 안의 상대 경로를 유지한다.
index.html을 작성한다.
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Character host example</title>
<link rel="icon" href="data:,">
<style>
#photo { position: fixed; left: 65%; top: 50%; }
#character { position: fixed; width: 80px; height: 80px;
object-fit: contain; pointer-events: none; }
</style>
<button id="photo" type="button">Open photo</button>
<button id="stop" type="button">Stop and detach</button>
<img id="character" alt="Example character">
<output id="status" aria-live="polite"></output>
<script type="module" src="./main.ts"></script>
</html>
main.ts를 작성한다.
import { loadCharacterContentV10 } from "@charaweave/content";
import { createCoreSession } from "@charaweave/core";
import { createBrowserSession } from "@charaweave/browser";
const packageBase = new URL("./demo-character-cw019c-simple-cat/", document.baseURI);
function resource(path: string): URL {
if (path.split("/").some(s => !s || s === "." || s === "..") ||
/[\\:%?#]/.test(path)) throw Error("Unsafe package path");
return new URL(path, packageBase);
}
const reader = {
async readText(path: string) {
const response = await fetch(resource(path));
if (!response.ok) throw Error("Package text request failed: " + response.status);
return response.text();
},
async exists(path: string) {
const response = await fetch(resource(path), { method: "HEAD" });
if (response.status === 404 || response.status === 410) return false;
if (!response.ok) throw Error("Package resource check failed: " + response.status);
return true;
},
};
const input = { reader, characterId: "sorune.simple-cat:cat" };
const loaded = await loadCharacterContentV10(input);
if (!loaded.ok) throw Error(JSON.stringify(loaded.issues));
const image = document.querySelector<HTMLImageElement>("#character")!;
const photo = document.querySelector<HTMLButtonElement>("#photo")!;
const status = document.querySelector<HTMLOutputElement>("#status")!;
const render = loaded.character.render;
image.src = resource(render.primaryAsset.path).href;
await image.decode();
const scale = render.defaultScale ?? 1;
image.style.width = (80 * scale) + "px";
image.style.height = (80 * scale) + "px";
let placement = { x: 100, y: 180 };
function applyPlacement(next: { x: number; y: number }) {
placement = next;
image.style.left = next.x + "px";
image.style.top = next.y + "px";
}
applyPlacement(placement);
// The Host treats placement as the image box's top-left CSS-pixel position.
const core = await createCoreSession({
character: input,
targetSessionPolicy: {
repeatTargetFactor: 0.5, recentTargetFactor: 0.5,
seenTargetFactor: 0.8, recentCapacity: 8, seenCapacity: 32,
},
});
const browser = createBrowserSession({
core,
character: {
getElement: () => image,
getCurrentPlacement: () => placement,
applyPlacement,
},
approachClearancePx: 12,
motionDurationMs: 400,
onDiagnostic: diagnostic => console.warn(diagnostic.code, diagnostic.message),
onCharacterExecution: event => { status.value = JSON.stringify(event); },
});
const binding = browser.attachHost({
element: photo,
id: "feed.photo.42",
role: "photo-card",
capabilities: ["activate"],
onActivate: () => { photo.click(); },
});
photo.addEventListener("click", () => { photo.dataset.opened = "true"; });
core.start();
if (browser.start().status !== "accepted") {
binding.detach(); browser.dispose(); core.dispose();
throw Error("Browser did not start");
}
status.value = "RUNNING";
let closed = false;
function cleanup() {
if (closed) return;
closed = true;
browser.suspend();
binding.detach();
browser.dispose();
core.dispose();
status.value = "DISPOSED";
}
document.querySelector("#stop")!.addEventListener("click", cleanup);
window.addEventListener("pagehide", cleanup, { once: true });
Vite 개발 서버로 페이지를 열면 캐릭터 이미지와 RUNNING 상태가 표시된다. 유효 기회 간격과 최소 대기 시간이 지난 뒤 대상 방문 또는 활성화가 선택될 수 있다. 방문이 콜백을 실행하는 것은 아니다. Stop and detach를 누르면 실행이 중단되고 세션이 정리된다.
이 예제는 고정 크기의 이미지로 이동과 대상 상호작용을 구현한다. 완전한 프레임 렌더러나 앵커 보정, 터치/드래그, V11 행동 전체를 제공하지 않는다. 실제 앱에서 애니메이션을 구현할 때는 클립을 재생하고 한 번 재생하는 클립의 종료 결과를 전달한다. 예제 reader는 파일이 없을 때 404 또는 410을 반환하는 서버를 전제로 한다. SPA fallback이 모든 요청에 200을 반환할 때에는 파일 목록 기반으로 존재 여부를 확인해야 한다.
Platform V6에서 대상 연결
이미 @charaweave/platform/browser를 사용한다면 BrowserEnvironment에 DOM 요소를 등록한다.
const registration = browser.attachHost({
element: cardElement,
id: "feed.photo.42",
role: "photo-card",
capabilities: ["activate"],
onActivate: async ({ surfaceId }) => openPhoto(surfaceId),
});
// Call when the element unmounts or refers to a different product object.
registration.detach();
이 구성의 Content 버전은 V6이다. V11 데이터를 읽으려면 loadCharacterContentV11을 사용하되 전체 V11 자율 실행을 생성하는 단일 Public API는 없다.
렌더링과 이동
getElement, getCurrentPlacement, applyPlacement로 캐릭터 DOM과 이동 좌표를 연결한다. Host의 DOMRect는 viewport CSS 픽셀이다. DPR을 곱하지 않는다. 현재 화면의 좌표축에 정렬된 사각형을 사용하며 회전·원근 변환의 정밀 충돌 판정은 지원 범위가 아니다.
비즈니스 콜백
activate capability 및 앱에서 등록한 onActivate 콜백이 있어야 활성화할 수 있다. visit는 대상까지 접근하는 동작이다. inspect, emote, rest는 V11의 행동이며 패키지에서 제품 데이터를 읽거나 코드를 실행하도록 허용하지 않는다.
종료 순서
자동 실행을 중단하고 대상 연결을 해제한다. 브라우저 및 Host 서비스를 해당 소유자가 정리한 뒤 Core 세션을 닫는다. 공유 서비스는 하위 컴포넌트에서 중복으로 dispose하지 않는다.