Scaffold Electron+React+TS app and render avatar VRM with animations

Sets up a transparent, always-on-top, frameless Electron window hosting
a Three.js scene that loads assets/avatar.vrm via @pixiv/three-vrm and
plays the bundled .vrma clips through @pixiv/three-vrm-animation. Fixes
the default CSP (which blocked texture-loading blob: fetches) and
frames the camera on the model automatically.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
william
2026-10-18 11:38:44 +02:00
co-authored by Claude Sonnet 5
commit 1959ddb41a
41 changed files with 9318 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
+6
View File
@@ -0,0 +1,6 @@
node_modules
dist
out
.DS_Store
.eslintcache
*.log*
+6
View File
@@ -0,0 +1,6 @@
out
dist
pnpm-lock.yaml
LICENSE.md
tsconfig.json
tsconfig.*.json
+4
View File
@@ -0,0 +1,4 @@
singleQuote: true
semi: false
printWidth: 100
trailingComma: none
+3
View File
@@ -0,0 +1,3 @@
{
"recommendations": ["dbaeumer.vscode-eslint"]
}
+39
View File
@@ -0,0 +1,39 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Main Process",
"type": "node",
"request": "launch",
"cwd": "${workspaceRoot}",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron-vite",
"windows": {
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron-vite.cmd"
},
"runtimeArgs": ["--sourcemap"],
"env": {
"REMOTE_DEBUGGING_PORT": "9222"
}
},
{
"name": "Debug Renderer Process",
"port": 9222,
"request": "attach",
"type": "chrome",
"webRoot": "${workspaceFolder}/src/renderer",
"timeout": 60000,
"presentation": {
"hidden": true
}
}
],
"compounds": [
{
"name": "Debug All",
"configurations": ["Debug Main Process", "Debug Renderer Process"],
"presentation": {
"order": 1
}
}
]
}
+11
View File
@@ -0,0 +1,11 @@
{
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
+34
View File
@@ -0,0 +1,34 @@
# forge-scaffold
An Electron application with React and TypeScript
## Recommended IDE Setup
- [VSCode](https://code.visualstudio.com/) + [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) + [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)
## Project Setup
### Install
```bash
$ npm install
```
### Development
```bash
$ npm run dev
```
### Build
```bash
# For windows
$ npm run build:win
# For macOS
$ npm run build:mac
# For Linux
$ npm run build:linux
```
+42
View File
@@ -0,0 +1,42 @@
◆ Contents ◆
A zip file containing 7 types of VRM Animation files (.vrma).
Included files:
・vrma
└VRMA_○○.vrma (Animation file)
・Readme_VRMA_MotionPack_JP.txt
・Readme_VRMA_MotionPack_EN.txt
◆ List of motions ◆
VRMA_01 Show full body
VRMA_02 Greeting
VRMA_03 Peace sign
VRMA_04 Shoot
VRMA_05 Spin
VRMA_06 Model pose
VRMA_07 Squat
◆ Terms of Use ◆
*By using these animation files, you automatically agree to these terms.
1. Disclaimer
・Regardless of whether the data is modified, the copyright belongs to pixiv Inc.
・The distributor is not responsible for any direct or indirect damage, disadvantage, or impairment that may arise from using the data.
・These terms of use may be changed without notice.
・The data may be updated or distribution may be suspended without notice.
・The laws of Japan apply to the use of this data.
2. Prohibited Actions
The following actions are prohibited with respect to the use of this data:
・Distributing these motions or their alterations without permission in a way that can be rigged or extracted.
・Using this data for specific religious beliefs or political purposes.
・Using this data with the intention of denigrating the dignity of a third party in an extraordinary manner.
・Illegal activities and actions that encourage such behavior.
・Acts that infringe on the rights of third parties.
・Using this data for sexual and significantly violent content.
3. License Scope
Users of this data can do the following:
・Freely customize the data.
・Use it for any purpose as long as it does not violate the prohibited actions.
・Commercial use by individuals or corporations (Please include the credit phrase "キャラクターアニメーション: ピクシブ株式会社 VRoidプロジェクト" in Japanese, or "Animation credits to pixiv Inc.'s VRoid Project")
If you want to confirm if your usage is appropriate, please contact us at the following: https://www.pixiv.net/support?type=45&mode=inquiry&service=vroid-feedback
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.allow-dyld-environment-variables</key>
<true/>
</dict>
</plist>
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

@@ -0,0 +1,72 @@
# Avatar de bureau IA - Cahier des charges
Oct 17, 2026 · @Vandal William
## Objectif du projet
Créer un avatar de bureau virtuel en 3D qui s'affiche automatiquement au démarrage de l'ordinateur (Windows et Mac), accueille l'utilisateur, et peut converser à voix/texte grâce à une IA connectée. L'IA doit être spécialisée en santé et sécurité au travail, capable de répondre aux questions sur ce sujet et d'exécuter des actions via des fonctions dédiées (function calling).
## Stack technique retenue
| Besoin | Technologie | Rôle |
| --- | --- | --- |
| Modèle 3D et animations | Tripo AI | Génère l'avatar 3D au format VRM à partir d'une description texte |
| Rendu 3D temps réel | Three.js | Charge le modèle VRM et joue les animations (.vrma) dans l'app |
| Chargement VRM et animations | @pixiv/three-vrm + @pixiv/three-vrm-animation | Charge le VRM, joue les .vrma via AnimationMixer, lip-sync via blendshapes natifs |
| Génération d'animations | Fichiers .vrma fournis | Fichiers .vrma déjà disponibles — aucune génération nécessaire, intégration directe |
| Application de bureau | Electron | Fenêtre transparente, toujours au premier plan, démarrage automatique |
| Interface | React | Construit l'UI et la logique de l'avatar à l'intérieur d'Electron, en TypeScript strict |
| Accès aux IA | OpenRouter | API unique donnant accès à plusieurs modèles (DeepSeek, Claude, GPT, etc.) |
| Modèle de langage | DeepSeek | Bon rapport performance/coût, choisi pour les réponses santé-sécurité |
| Appels de fonctions | Function calling (standard OpenRouter) | Permet à l'IA d'exécuter des actions définies dans le code (recherche de procédure, rappel, etc.) |
## Pipeline de création de l'avatar (Tripo AI + VRM)
1. Rédiger une description texte détaillée de l'avatar souhaité (apparence, style, tenue).
2. Générer le modèle 3D avec Tripo AI à partir de cette description.
3. Les fichiers .vrma sont déjà disponibles. Les placer dans le dossier assets/ et les charger directement via @pixiv/three-vrm-animation sans aucune génération supplémentaire.
4. Exporter le modèle au format VRM depuis Tripo AI. Les animations sont des fichiers .vrma distincts, générés par NVIDIA ARDY.
5. Charger le VRM dans Three.js via @pixiv/three-vrm. Charger les animations .vrma via @pixiv/three-vrm-animation. Piloter l'animation active avec AnimationMixer. Le lip-sync est géré nativement par le système de blendshapes VRM.
## Application de bureau (Electron)
- Fenêtre sans bordure, fond transparent, toujours au premier plan (always-on-top), pour afficher l'avatar par-dessus le bureau.
- Option de fenêtre cliquable ou click-through selon l'usage voulu (interaction ou simple présence visuelle).
- Démarrage automatique au lancement de Windows ou macOS via le module intégré d'Electron dédié au lancement au démarrage du système.
- React + TypeScript comme interface à l'intérieur de la fenêtre Electron, avec Three.js monté dans le composant qui affiche l'avatar.
- Compatible Windows et Mac nativement, sans code spécifique à chaque plateforme pour la partie rendu.
## Intégration IA (OpenRouter + DeepSeek)
- Requêtes HTTP vers l'endpoint `https://openrouter.ai/api/v1/chat/completions`, avec la clé API dans l'en-tête `Authorization`.
- Le modèle est choisi via le paramètre `model` (ex: `deepseek/deepseek-chat`) ; changer de modèle ne demande de modifier que cette valeur, le reste du code reste identique.
- Facturation centralisée chez OpenRouter : un seul compte et une seule facture, quel que soit le modèle utilisé.
- Function calling standardisé : définir des fonctions (ex: `rechercher_procedure_securite`) dans le paramètre `tools`, que l'IA peut décider d'appeler selon la conversation.
- Le résultat de la fonction exécutée côté application est renvoyé à l'IA pour qu'elle poursuive la conversation avec cette information.
- DeepSeek recommandé comme modèle principal pour son bon rapport performance/coût, avec possibilité de basculer vers un autre modèle (Claude, GPT) si besoin de qualité supérieure sur certains cas.
## Interaction vocale (voix française)
- Reconnaissance vocale (speech-to-text) : transforme la voix de l'utilisateur en texte, à envoyer ensuite à l'IA. Candidat recommandé : Whisper (OpenAI), fiable en français.
- Synthèse vocale (text-to-speech) : transforme la réponse texte de l'IA en voix, pour que l'avatar réponde à l'oral. Candidat recommandé : ElevenLabs, bon rendu en français, avec option de lip-sync à synchroniser sur les animations de l'avatar.
- Coût estimé : de l'ordre de quelques dollars à une vingtaine de dollars par mois pour un usage personnel quotidien (synthèse + reconnaissance vocale + appels DeepSeek via OpenRouter combinés).
## Base de connaissances santé et sécurité au travail
- Pas d'accès à Internet : les documents de référence sont stockés localement dans un dossier dédié.
- Format retenu : Markdown directement, sans passer par du PDF. Le Markdown conserve la structure des titres, ce qui permet un découpage du texte propre et une recherche plus fiable par l'IA.
- Prévoir une fonction dédiée (function calling) permettant à l'IA de rechercher dans ces fichiers Markdown locaux (recherche par mot-clé ou par similarité) plutôt que de répondre uniquement de mémoire.
- Étape technique à prévoir : indexer le contenu des fichiers Markdown à l'avance (découpage en passages selon les titres, recherche par similarité) pour que l'IA retrouve rapidement le passage pertinent lors d'une question.
## Étapes d'implémentation suggérées
1. Mettre en place le projet Electron avec React, fenêtre transparente et toujours au premier plan.
2. Intégrer Three.js et @pixiv/three-vrm dans le composant React (TypeScript) et charger le modèle VRM pour valider le rendu.
3. Le modèle VRM et les fichiers .vrma sont déjà prêts. Les placer dans assets/ et les intégrer via @pixiv/three-vrm et @pixiv/three-vrm-animation.
4. Configurer le démarrage automatique de l'application au lancement du système (Windows et macOS).
5. Mettre en place l'appel à OpenRouter avec le modèle DeepSeek, message système incluant l'expertise santé-sécurité au travail.
6. Définir et implémenter les premières fonctions exploitables par l'IA (function calling), ex: recherche dans la bibliothèque Markdown, création de rappel.
7. Intégrer la reconnaissance vocale (Whisper) pour capter la voix de l'utilisateur et la convertir en texte.
8. Intégrer la synthèse vocale (ElevenLabs) pour que la réponse de l'IA soit lue à voix haute en français.
9. Relier la voix à l'avatar : déclenchement des animations adaptées et lip-sync synchronisé sur l'audio généré.
10. Tester l'ensemble sur Windows et Mac, ajuster les performances (chargement du modèle, latence des appels IA et voix).
+43
View File
@@ -0,0 +1,43 @@
appId: com.electron.app
productName: forge-scaffold
directories:
buildResources: build
files:
- '!**/.vscode/*'
- '!src/*'
- '!electron.vite.config.{js,ts,mjs,cjs}'
- '!{.eslintcache,eslint.config.mjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}'
- '!{.env,.env.*,.npmrc,pnpm-lock.yaml}'
- '!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}'
asarUnpack:
- resources/**
win:
executableName: forge-scaffold
nsis:
artifactName: ${name}-${version}-setup.${ext}
shortcutName: ${productName}
uninstallDisplayName: ${productName}
createDesktopShortcut: always
mac:
entitlementsInherit: build/entitlements.mac.plist
extendInfo:
- NSCameraUsageDescription: Application requests access to the device's camera.
- NSMicrophoneUsageDescription: Application requests access to the device's microphone.
- NSDocumentsFolderUsageDescription: Application requests access to the user's Documents folder.
- NSDownloadsFolderUsageDescription: Application requests access to the user's Downloads folder.
notarize: false
dmg:
artifactName: ${name}-${version}.${ext}
linux:
target:
- AppImage
- snap
- deb
maintainer: electronjs.org
category: Utility
appImage:
artifactName: ${name}-${version}.${ext}
npmRebuild: false
publish:
provider: generic
url: https://example.com/auto-updates
+17
View File
@@ -0,0 +1,17 @@
import { resolve } from 'path'
import { defineConfig } from 'electron-vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
main: {},
preload: {},
renderer: {
publicDir: resolve('assets'),
resolve: {
alias: {
'@renderer': resolve('src/renderer/src')
}
},
plugins: [react()]
}
})
+32
View File
@@ -0,0 +1,32 @@
import { defineConfig } from 'eslint/config'
import tseslint from '@electron-toolkit/eslint-config-ts'
import eslintConfigPrettier from '@electron-toolkit/eslint-config-prettier'
import eslintPluginReact from 'eslint-plugin-react'
import eslintPluginReactHooks from 'eslint-plugin-react-hooks'
import eslintPluginReactRefresh from 'eslint-plugin-react-refresh'
export default defineConfig(
{ ignores: ['**/node_modules', '**/dist', '**/out'] },
tseslint.configs.recommended,
eslintPluginReact.configs.flat.recommended,
eslintPluginReact.configs.flat['jsx-runtime'],
{
settings: {
react: {
version: 'detect'
}
}
},
{
files: ['**/*.{ts,tsx}'],
plugins: {
'react-hooks': eslintPluginReactHooks,
'react-refresh': eslintPluginReactRefresh
},
rules: {
...eslintPluginReactHooks.configs.recommended.rules,
...eslintPluginReactRefresh.configs.vite.rules
}
},
eslintConfigPrettier
)
+8494
View File
File diff suppressed because it is too large Load Diff
+51
View File
@@ -0,0 +1,51 @@
{
"name": "forge-avatar",
"version": "1.0.0",
"description": "Avatar de bureau IA specialise en sante et securite au travail",
"main": "./out/main/index.js",
"author": "Vandal William",
"scripts": {
"format": "prettier --write .",
"lint": "eslint --cache .",
"typecheck:node": "tsc --noEmit -p tsconfig.node.json --composite false",
"typecheck:web": "tsc --noEmit -p tsconfig.web.json --composite false",
"typecheck": "npm run typecheck:node && npm run typecheck:web",
"start": "electron-vite preview",
"dev": "electron-vite dev",
"build": "npm run typecheck && electron-vite build",
"postinstall": "install-electron && electron-builder install-app-deps",
"build:unpack": "npm run build && electron-builder --dir",
"build:win": "npm run build && electron-builder --win",
"build:mac": "electron-vite build && electron-builder --mac",
"build:linux": "electron-vite build && electron-builder --linux"
},
"dependencies": {
"@electron-toolkit/preload": "^3.0.2",
"@electron-toolkit/utils": "^4.0.0",
"@pixiv/three-vrm": "^3.5.5",
"@pixiv/three-vrm-animation": "^3.5.5",
"three": "^0.186.1"
},
"devDependencies": {
"@electron-toolkit/eslint-config-prettier": "^3.0.1",
"@electron-toolkit/eslint-config-ts": "^4.0.0",
"@electron-toolkit/tsconfig": "^2.0.0",
"@types/node": "^24.19.2",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@types/three": "^0.186.0",
"@vitejs/plugin-react": "^6.1.2",
"electron": "^44.7.2",
"electron-builder": "^26.15.3",
"electron-vite": "^6.0.0",
"eslint": "^9.39.5",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.7",
"prettier": "^3.9.10",
"react": "^19.3.0",
"react-dom": "^19.3.0",
"typescript": "^5.9.3",
"vite": "^8.3.4"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

+73
View File
@@ -0,0 +1,73 @@
import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
let mainWindow: BrowserWindow | null = null
function createWindow(): void {
mainWindow = new BrowserWindow({
width: 420,
height: 720,
show: false,
frame: false,
transparent: true,
backgroundColor: '#00000000',
hasShadow: false,
alwaysOnTop: true,
resizable: false,
skipTaskbar: true,
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: false
}
})
mainWindow.setAlwaysOnTop(true, 'screen-saver')
mainWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true })
mainWindow.on('ready-to-show', () => {
mainWindow?.show()
})
mainWindow.webContents.setWindowOpenHandler((details) => {
shell.openExternal(details.url)
return { action: 'deny' }
})
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
} else {
mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
}
}
app.whenReady().then(() => {
electronApp.setAppUserModelId('com.forgeavatar.app')
if (!is.dev) {
app.setLoginItemSettings({ openAtLogin: true })
}
app.on('browser-window-created', (_, window) => {
optimizer.watchWindowShortcuts(window)
})
ipcMain.on(
'set-ignore-mouse-events',
(_event, ignore: boolean, options?: { forward: boolean }) => {
mainWindow?.setIgnoreMouseEvents(ignore, options)
}
)
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
+12
View File
@@ -0,0 +1,12 @@
import { ElectronAPI } from '@electron-toolkit/preload'
export interface ForgeAvatarApi {
setIgnoreMouseEvents: (ignore: boolean, options?: { forward: boolean }) => void
}
declare global {
interface Window {
electron: ElectronAPI
api: ForgeAvatarApi
}
}
+22
View File
@@ -0,0 +1,22 @@
import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
const api = {
setIgnoreMouseEvents: (ignore: boolean, options?: { forward: boolean }): void => {
ipcRenderer.send('set-ignore-mouse-events', ignore, options)
}
}
if (process.contextIsolated) {
try {
contextBridge.exposeInMainWorld('electron', electronAPI)
contextBridge.exposeInMainWorld('api', api)
} catch (error) {
console.error(error)
}
} else {
// @ts-ignore (define in dts)
window.electron = electronAPI
// @ts-ignore (define in dts)
window.api = api
}
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Forge Avatar</title>
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self' blob: data:; worker-src 'self' blob:"
/>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+23
View File
@@ -0,0 +1,23 @@
import { useCallback, useState } from 'react'
import AvatarViewer, { type AvatarHandle } from './components/AvatarViewer'
function App(): React.JSX.Element {
const [avatar, setAvatar] = useState<AvatarHandle | null>(null)
const handleReady = useCallback((handle: AvatarHandle) => {
setAvatar(handle)
}, [])
return (
<div
style={{ width: '100%', height: '100%' }}
onMouseEnter={() => window.api.setIgnoreMouseEvents(false)}
onMouseLeave={() => window.api.setIgnoreMouseEvents(true, { forward: true })}
onDoubleClick={() => avatar?.playAnimation(1)}
>
<AvatarViewer onReady={handleReady} />
</div>
)
}
export default App
+67
View File
@@ -0,0 +1,67 @@
:root {
--ev-c-white: #ffffff;
--ev-c-white-soft: #f8f8f8;
--ev-c-white-mute: #f2f2f2;
--ev-c-black: #1b1b1f;
--ev-c-black-soft: #222222;
--ev-c-black-mute: #282828;
--ev-c-gray-1: #515c67;
--ev-c-gray-2: #414853;
--ev-c-gray-3: #32363f;
--ev-c-text-1: rgba(255, 255, 245, 0.86);
--ev-c-text-2: rgba(235, 235, 245, 0.6);
--ev-c-text-3: rgba(235, 235, 245, 0.38);
--ev-button-alt-border: transparent;
--ev-button-alt-text: var(--ev-c-text-1);
--ev-button-alt-bg: var(--ev-c-gray-3);
--ev-button-alt-hover-border: transparent;
--ev-button-alt-hover-text: var(--ev-c-text-1);
--ev-button-alt-hover-bg: var(--ev-c-gray-2);
}
:root {
--color-background: var(--ev-c-black);
--color-background-soft: var(--ev-c-black-soft);
--color-background-mute: var(--ev-c-black-mute);
--color-text: var(--ev-c-text-1);
}
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
font-weight: normal;
}
ul {
list-style: none;
}
body {
min-height: 100vh;
color: var(--color-text);
background: var(--color-background);
line-height: 1.6;
font-family:
Inter,
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
Roboto,
Oxygen,
Ubuntu,
Cantarell,
'Fira Sans',
'Droid Sans',
'Helvetica Neue',
sans-serif;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
+13
View File
@@ -0,0 +1,13 @@
@import './base.css';
html,
body {
background: transparent !important;
overflow: hidden;
user-select: none;
}
#root {
width: 100vw;
height: 100vh;
}
@@ -0,0 +1,173 @@
import { useEffect, useRef } from 'react'
import * as THREE from 'three'
import { GLTFLoader, type GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { VRMLoaderPlugin, VRMUtils, type VRM } from '@pixiv/three-vrm'
import {
VRMAnimationLoaderPlugin,
createVRMAnimationClip,
type VRMAnimation
} from '@pixiv/three-vrm-animation'
const ANIMATION_FILES = [
'VRMA_01.vrma',
'VRMA_02.vrma',
'VRMA_03.vrma',
'VRMA_04.vrma',
'VRMA_05.vrma',
'VRMA_06.vrma',
'VRMA_07.vrma'
]
const GREETING_INDEX = 1
export interface AvatarHandle {
playAnimation: (index: number) => void
}
interface AvatarViewerProps {
onReady?: (handle: AvatarHandle) => void
}
function AvatarViewer({ onReady }: AvatarViewerProps): React.JSX.Element {
const containerRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const container = containerRef.current
if (!container) return
let disposed = false
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(30, 1, 0.1, 20)
camera.position.set(0, 1.35, 2.2)
const renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true })
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setClearColor(0x000000, 0)
container.appendChild(renderer.domElement)
const resize = (): void => {
const { clientWidth, clientHeight } = container
renderer.setSize(clientWidth, clientHeight)
camera.aspect = clientWidth / clientHeight
camera.updateProjectionMatrix()
}
resize()
window.addEventListener('resize', resize)
const hemiLight = new THREE.HemisphereLight(0xffffff, 0x8888aa, 1.2)
scene.add(hemiLight)
const dirLight = new THREE.DirectionalLight(0xffffff, 0.8)
dirLight.position.set(1, 1.5, 1)
scene.add(dirLight)
const loader = new GLTFLoader()
loader.register((parser) => new VRMLoaderPlugin(parser))
loader.register((parser) => new VRMAnimationLoaderPlugin(parser))
let currentVrm: VRM | null = null
let mixer: THREE.AnimationMixer | null = null
const clips: THREE.AnimationClip[] = []
let currentAction: THREE.AnimationAction | null = null
const playClip = (index: number): void => {
if (!currentVrm || !mixer) return
const clip = clips[index]
if (!clip) return
const next = mixer.clipAction(clip)
next.reset().fadeIn(0.4).play()
if (currentAction && currentAction !== next) {
currentAction.fadeOut(0.4)
}
currentAction = next
}
loader.load(
'avatar.vrm',
async (gltf: GLTF) => {
if (disposed) return
const vrm = gltf.userData.vrm as VRM
VRMUtils.removeUnnecessaryVertices(gltf.scene)
VRMUtils.combineSkeletons(gltf.scene)
vrm.scene.traverse((obj) => {
obj.frustumCulled = false
})
currentVrm = vrm
scene.add(vrm.scene)
mixer = new THREE.AnimationMixer(vrm.scene)
const box = new THREE.Box3().setFromObject(vrm.scene)
const center = box.getCenter(new THREE.Vector3())
const height = box.max.y - box.min.y
const fovRad = (camera.fov * Math.PI) / 180
const distance = (height / 2 / Math.tan(fovRad / 2)) * 1.25
camera.position.set(center.x, center.y, center.z - distance)
camera.lookAt(center.x, center.y, center.z)
const animLoader = new GLTFLoader()
animLoader.register((parser) => new VRMAnimationLoaderPlugin(parser))
const loadedClips = await Promise.all(
ANIMATION_FILES.map(
(url) =>
new Promise<THREE.AnimationClip | null>((resolve) => {
animLoader.load(
url,
(animGltf: GLTF) => {
const vrmAnimations = animGltf.userData.vrmAnimations as
VRMAnimation[] | undefined
const vrmAnimation = vrmAnimations?.[0]
if (!vrmAnimation) {
resolve(null)
return
}
resolve(createVRMAnimationClip(vrmAnimation, vrm))
},
undefined,
() => resolve(null)
)
})
)
)
if (disposed) return
loadedClips.forEach((clip) => {
if (clip) clips.push(clip)
})
playClip(GREETING_INDEX)
onReady?.({ playAnimation: playClip })
},
undefined,
(error) => {
console.error('[avatar] Erreur de chargement du modele VRM', error)
}
)
const clock = new THREE.Clock()
let frameId = 0
const tick = (): void => {
frameId = requestAnimationFrame(tick)
const delta = clock.getDelta()
mixer?.update(delta)
currentVrm?.update(delta)
renderer.render(scene, camera)
}
tick()
return () => {
disposed = true
cancelAnimationFrame(frameId)
window.removeEventListener('resize', resize)
if (currentVrm) {
scene.remove(currentVrm.scene)
VRMUtils.deepDispose(currentVrm.scene)
}
renderer.dispose()
container.removeChild(renderer.domElement)
}
}, [onReady])
return <div ref={containerRef} style={{ width: '100%', height: '100%' }} />
}
export default AvatarViewer
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+11
View File
@@ -0,0 +1,11 @@
import './assets/main.css'
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>
)
+4
View File
@@ -0,0 +1,4 @@
{
"files": [],
"references": [{ "path": "./tsconfig.node.json" }, { "path": "./tsconfig.web.json" }]
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "@electron-toolkit/tsconfig/tsconfig.node.json",
"include": ["electron.vite.config.*", "src/main/**/*", "src/preload/**/*"],
"compilerOptions": {
"composite": true,
"types": ["electron-vite/node"]
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"extends": "@electron-toolkit/tsconfig/tsconfig.web.json",
"include": [
"src/renderer/src/env.d.ts",
"src/renderer/src/**/*",
"src/renderer/src/**/*.tsx",
"src/preload/*.d.ts"
],
"compilerOptions": {
"composite": true,
"jsx": "react-jsx",
"baseUrl": ".",
"paths": {
"@renderer/*": [
"src/renderer/src/*"
]
}
}
}