К основному содержанию
скилл Claude Code CX Codex Cursor GitHub Copilot

threejs-gltf-loading — скилл для Claude Code: glTF и анимации

Загружает glTF и GLB в three.js и проигрывает запечённые клипы через AnimationMixer, включая сжатые DRACO, Meshopt и KTX2. Пригодится, когда модель вроде загрузилась, а на экране пусто.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill threejs-gltf-loading -a claude-code
Открыть на GitHub

Что делает threejs-gltf-loading

Скилл даёт агенту рабочие шаблоны для .gltf и .glb в three.js. GLTFLoader возвращает gltf.scene, массив AnimationClip и запечённые камеры, а AnimationMixer проигрывает клипы: один микшер на анимированный корень, mixer.update(delta) в цикле рендера. В примерах есть колбэки прогресса и ошибок, поиск детали через traverse и переход между клипами через crossFadeTo.

Сжатые ассеты разобраны отдельно: DRACOLoader с DRACO_GLTF_CONFIG, KTX2Loader, декодер Meshopt. Шаблоны рассчитаны на r186, а версию, закреплённую в проекте, скилл советует не трогать без запроса на миграцию. Вот где легко споткнуться: на релизах до r185 загрузчики не находят свои файлы декодеров сами, поэтому папку копируют в проект и передают в setDecoderPath.

Раздел с граблями читается как список для отладки. Модель загрузилась, но её не видно, потому что PBR-материалам нужен свет или scene.environment. Клип стоит на месте, если забыли mixer.update или передали миллисекунды вместо секунд. И THREE.Clock устарел с r183, в примерах используется THREE.Timer. Когда gltf-transform в проекте уже есть, скилл просит прогнать gltf-transform validate path/to/model.glb по изменённым файлам до загрузки.

Какие задачи решает

  • загрузить .glb в сцену и разобрать дерево узлов
  • проиграть скиннинг-клип Run из gltf.animations
  • сделать переход с Idle на Run без рывка
  • подключить DRACO и KTX2, чтобы сжатые меши перестали отдавать 404
  • найти деталь по имени через traverse и раскрутить её в цикле рендера

Примеры запросов агенту

  • Загрузи `assets/robot.glb` через `GLTFLoader` и выведи имена клипов в консоль.
  • Сделай переход с `Idle` на `Run` через `crossFadeTo` за 0.3 секунды.
  • Модель с DRACO не грузится, в сети 404 на `draco_*` — почини загрузчик.

Как установить threejs-gltf-loading

1Через Skills CLI (Vercel)

npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill threejs-gltf-loading -a claude-code

2Вручную: положить файлы

~/.claude/skills/threejs-gltf-loading/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/threejs-gltf-loading/

Из того же набора40

Весь набор →
game-feel gamedev-skills Скилл учит агента добавлять отклик к игровым действиям: тряску камеры, стоп-кадр, твины с easing, сквош и отброс. Для случаев, когда механика работает, но ощущается ватной. Claude Code CX Codex Cursor +1 9 400установок game-ui-ux gamedev-skills Архитектурный скилл для создания адаптивных игровых интерфейсов, стека экранов и навигации с геймпада без покадрового опроса состояния. Claude Code CX Codex Cursor +1 9 200установок level-design gamedev-skills Помогает спроектировать игровой уровень от блокута до плейтеста: маршруты, темп, препятствия и столкновения. Нужен при работе с whitebox, критическим путём и геймплейными комнатами. Claude Code CX Codex Cursor +1 7 500установок camera-systems gamedev-skills Рецепты для игровых камер в 2D и 3D: плавное следование, мёртвые зоны, опережение движения и обработка столкновений для Godot и Unity. Claude Code CX Codex Cursor +1 7 100установок audio-design gamedev-skills Скилл учит раскладывать игровой звук по шинам, глушить музыку под голос и собирать адаптивный саундтрек слоями. Примеры кода — на GDScript под Godot 4.7, с пометками для Unity. Claude Code CX Codex Cursor +1 7 100установок performance-optimization gamedev-skills Скилл учит искать узкое место в игре по профайлеру движка, а не по догадке, и даёт набор правок: пулы объектов, батчинг, отказ от лишних аллокаций. Claude Code CX Codex Cursor +1 7 100установок game-ai gamedev-skills Помогает проектировать логику врагов и NPC: конечные автоматы, деревья поведения, алгоритмы руления и поиск пути A*. Пригодится при сборке поведения ботов для любого движка. Claude Code CX Codex Cursor +1 7 100установок input-systems gamedev-skills Архитектура игровых управлений: отображение клавиш на действия, перекоординирование с проверкой конфликтов, поддержка клавиатуры, геймпада и сенсора, мёртвые зоны, буферизация и coyote time. Claude Code CX Codex Cursor +1 6 800установок

Похожие

threejs-game-ui-designer majidmanzarpour Скилл для проектирования игровых интерфейсов на Three.js: HUD, меню, экраны паузы и победы, адаптивная вёрстка для мобильных и десктопа. Помогает избежать наложений, обеспечить читаемость и согласованность со стилем игры. Claude Code CX Codex Cursor +1 3 300установок threejs-gameplay-systems majidmanzarpour Разворачивает игровой цикл на Three.js, Vite и TypeScript с контролем физики, ввода и камеры. Пригодится при сборке прототипов и настройке гейм-фила. Claude Code CX Codex Cursor +1 3 300установок orbit-card heygen-com Скилл для встраивания готового 10-секундного 3D-блока HyperFrames: карточка фичи облетает сферу из точек по траектории камеры из Blender. Claude Code CX Codex Cursor +1 9 800установок sdf earthtojake Скилл создаёт и проверяет SDFormat-файлы для моделей и миров, а затем помогает подготовить их к передаче в симулятор. Claude Code CX Codex Cursor +1 10 500установок urdf earthtojake Скилл помогает создавать, проверять и отлаживать описания роботов в формате URDF. Пригодится для работы со звеньями, сочленениями и геометрией. Claude Code CX Codex Cursor +1 10 400установок hatch-pet официальный openai Создаёт и упаковывает анимированных питомцев и спрайт-листы для Codex. Пригодится, когда нужен персонаж по описанию, изображению или фирменным ориентирам. Claude Code CX Codex Cursor +1 3 300установок gcode earthtojake Нарезает модели STL, 3MF и OBJ в G-code через OrcaSlicer. Подходит, когда нужно подготовить файл для печати без подключения к принтеру. Claude Code CX Codex Cursor +1 9 500установок dxf earthtojake Скилл собирает и проверяет 2D DXF-чертежи из Python-скриптов на build123d: контуры, прокладки, панели, развёртки под лазер. Claude Code CX Codex Cursor +1 9 100установок

Вопросы о threejs-gltf-loading

Как установить threejs-gltf-loading в Claude Code?

Выполните npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill threejs-gltf-loading -a claude-code. Файл скилла появится по пути ~/.claude/skills/threejs-gltf-loading/SKILL.md.

Что делает threejs-gltf-loading?

Разбирает импорт glTF и GLB в three.js: GLTFLoader, AnimationMixer, сжатые меши и текстуры. Агент получает шаблоны кода и список типичных ошибок загрузки.

Нужно ли что-то настраивать для DRACO и KTX2?

На r185 и новее загрузчики находят встроенные декодеры сами, путь указывать не нужно. На более старых релизах файлы копируют в проект и передают папку в setDecoderPath.

Исходный текст

SKILL.md · Apache-2.0
---
name: threejs-gltf-loading
description: >
  Load glTF/GLB models in three.js with GLTFLoader and play their skinned
  animations with AnimationMixer, including DRACO/Meshopt-compressed meshes and
  KTX2 textures. Use when importing 3D models into three.js — when the user
  mentions glTF, GLB, GLTFLoader, AnimationMixer, animation clips, DRACOLoader, or
  "load a 3D model". For scene/camera/renderer setup use threejs-scene-setup; for
  materials and lights use threejs-materials-lighting.
---

# three.js glTF Loading

Load `.gltf`/`.glb` models and play their animations in three.js, including
compressed geometry (DRACO/Meshopt) and textures (KTX2). Patterns target
**r186**; preserve an existing project's pinned release unless migration is requested.

## When to use

- Use to import a 3D model, add it to the scene, inspect its node hierarchy, and
  play baked/skinned animation clips with an `AnimationMixer`.
- Use when files are `.gltf`/`.glb`, or code imports `GLTFLoader` /
  `DRACOLoader` / `KTX2Loader` from `three/addons/loaders/...`.

**When *not* to use:** creating the renderer/camera/loop → `threejs-scene-setup`.
Tuning surface look, lights, or shadows on the loaded model →
`threejs-materials-lighting`. Authoring/exporting the model itself (Blender) is out
of scope; prefer glTF over OBJ/FBX for runtime.

## Core workflow

1. **Why glTF.** It's a transmission format: binary vertex data, PBR materials, and
   animations are ready to render with minimal parsing. Prefer it over OBJ (no scene
   graph, no animation) and FBX (heavy) for the web.
2. **Load with `GLTFLoader`.** `loader.load(url, onLoad, onProgress, onError)`. The
   result `gltf` has `gltf.scene` (the `Object3D` root), `gltf.animations`
   (`AnimationClip[]`), `gltf.cameras`, and `gltf.asset`.
3. **Add `gltf.scene` to your scene** and frame it. Inspect the hierarchy with
   `traverse` / `getObjectByName` to find the parts you'll control.
4. **Play animations with an `AnimationMixer`.** One mixer per animated root;
   `mixer.clipAction(clip).play()`; advance with `mixer.update(delta)` every frame.
5. **Decode compressed assets.** Attach a `DRACOLoader`, a `KTX2Loader`, and/or
   the Meshopt decoder so DRACO meshes, KTX2 textures, and meshopt-compressed
   buffers load. Since r185 the DRACO and KTX2 loaders find their bundled
   decoder files on their own.
6. **Validate changed glTF files when the project already has the tool.** Run
   `gltf-transform validate path/to/model.glb` for each changed `.gltf` or `.glb`;
   fix reported errors before loading.
7. **Verify what loaded** — log the scene graph and `gltf.animations`, and confirm
   the model is visible (right scale, lit) and the clip actually plays.

## Patterns

### 1. Load a model and frame it

```js
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

const loader = new GLTFLoader();
loader.load(
  'assets/robot.glb',
  (gltf) => {
    const root = gltf.scene;
    scene.add(root);
    // Inspect: gltf.animations is an array of AnimationClip.
    console.log('clips:', gltf.animations.map((c) => c.name));
  },
  (event) => {
    // total is 0 when the server sends no Content-Length (e.g. compressed responses)
    if (event.total) console.log(`${(event.loaded / event.total) * 100}% loaded`);
  },
  (error) => console.error('glTF load failed:', error)
);
```

### 2. Play a skinned animation with AnimationMixer

```js
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

let mixer;                                  // declare outside so the loop can see it
const timer = new THREE.Timer();            // THREE.Clock is deprecated since r183

new GLTFLoader().load('assets/character.glb', (gltf) => {
  scene.add(gltf.scene);
  mixer = new THREE.AnimationMixer(gltf.scene);          // one mixer per animated root
  const clip = THREE.AnimationClip.findByName(gltf.animations, 'Run')
            ?? gltf.animations[0];
  mixer.clipAction(clip).play();
});

renderer.setAnimationLoop((time) => {
  timer.update(time);
  const dt = timer.getDelta();
  if (mixer) mixer.update(dt);              // advance the animation by real seconds
  renderer.render(scene, camera);
});
```

### 3. Cross-fade between two clips

```js
const actions = {};
mixer = new THREE.AnimationMixer(gltf.scene);
for (const clip of gltf.animations) {
  actions[clip.name] = mixer.clipAction(clip);
}
let current = actions['Idle'];
current.play();

function transitionTo(name, duration = 0.3) {
  const next = actions[name];
  if (!next || next === current) return;
  next.reset().play();                      // rewind and clear any old fade
  current.crossFadeTo(next, duration, false); // fade the old one out, new one in
  current = next;
}
```

### 4. DRACO-compressed geometry

```js
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { DRACOLoader, DRACO_GLTF_CONFIG } from 'three/addons/loaders/DRACOLoader.js';

// r185+: DRACOLoader finds the decoder that ships next to it in
// three/examples/jsm/libs/draco/, so no path is required. DRACO_GLTF_CONFIG
// (also r185+) selects the smaller glTF-only WASM build in libs/draco/gltf/.
const draco = new DRACOLoader().setDecoderPath(DRACO_GLTF_CONFIG);

const loader = new GLTFLoader();
loader.setDRACOLoader(draco);              // share one DRACOLoader across loads
loader.load('assets/city-draco.glb', (gltf) => scene.add(gltf.scene));
```

On releases before r185, or when your host does not serve those files, pass a
folder instead: `draco.setDecoderPath('/decoders/draco/')` with the files copied
from the same `three` version.

### 5. Find and animate a named part

```js
const timer = new THREE.Timer();

new GLTFLoader().load('assets/car.glb', (gltf) => {
  scene.add(gltf.scene);
  const wheels = [];
  gltf.scene.traverse((node) => {
    if (node.name.startsWith('Wheel')) wheels.push(node);
  });
  renderer.setAnimationLoop((time) => {
    timer.update(time);
    const dt = timer.getDelta();
    for (const w of wheels) w.rotation.x += dt * 4;
    renderer.render(scene, camera);
  });
});
```

## Pitfalls

- **Model loads but is invisible** → it has lit (PBR) materials and the scene has no
  light or environment. Add a light or `scene.environment` (see
  `threejs-materials-lighting`), and check scale — glTF is in metres, so a 0.01-scaled
  asset is tiny.
- **`load` is async** → `gltf` only exists inside the callback; declare `mixer`/refs
  outside and assign them in the callback, or use `await loader.loadAsync(url)`.
- **Animation never moves** → you didn't call `mixer.update(delta)` each frame, or you
  passed milliseconds instead of seconds (use `timer.getDelta()` after
  `timer.update(time)`), or you forgot
  `action.play()`.
- **DRACO/KTX2 model fails, or the network tab shows a 404 for `draco_*`/`basis_*`
  files** → the decoder/transcoder files are not being served, or come from a
  different three.js version. Since r185 the loaders default to the copies inside
  `three/examples/jsm/libs/`; if your bundler or host doesn't serve those, copy the
  folders from the installed `three` and point `setDecoderPath`/`setTranscoderPath`
  at them.
- **`setKTX2Loader must be called before loading KTX2 textures`** or
  **`setMeshoptDecoder must be called before loading compressed files`** → the
  asset uses `KHR_texture_basisu` or meshopt compression (`EXT_`/`KHR_meshopt_compression`);
  attach the missing decoder (see the reference).
- **Multiple mixers fighting** → use **one** `AnimationMixer` per animated root and
  create all actions from it; don't make a new mixer per clip.
- **Baked-in transforms surprise you** → exporters sometimes bake scale/rotation onto
  child nodes. Dump the hierarchy (names + position/rotation/scale) before relying on
  a node's local transform; re-export from the source if the rig is unusable.
- **Origins are off** → re-parent a part under a fresh `Object3D` to give it a clean
  pivot rather than fighting baked offsets.

## References

- For the full decode/transcode setup (DRACO + Meshopt + KTX2 together), `loadAsync`
  + a `LoadingManager` progress bar, reusing models with `SkeletonUtils.clone`, and
  exporter guidance (apply transforms, one clean root), read
  `references/loaders-and-animation.md`.

## Related skills

- `threejs-scene-setup` — the renderer, camera, and loop this model renders into.
- `threejs-materials-lighting` — lighting/environment so PBR models look right.
- `fps-shooter` — a 3D genre that composes three.js skills.

© gamedev-skills · Apache-2.0 · gamedev-skills/awesome-gamedev-agent-skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой