threejs-tresjs について
threejs-tresjsは、Three.jsとVue 3連携のTresJSで3D HUDを構築する開発スキルです。描画性能、GPUリソース管理、入力検証、コンポーネントテストを扱います。
主な機能
- 013D HUDシーンとパネルの構築
- 02TresJSとVue 3のリアクティビティ連携
- 03インスタンシングとLODによる描画最適化
- 04ジオメトリ、マテリアル、テクスチャの破棄
- 05カラー検証とGPUリソース保護
活用シーン
- 01アニメーション付きステータス表示のHUD開発
- 02リアルタイム指標やパーティクルの表示
- 03反復オブジェクトを含む3Dシーンの最適化
- 04コンポーネント描画とリソース解放のテスト
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ martinholovsky/ claude-skills-generator --skill threejs-tresjsインストール後、Claude Code で/threejs-tresjsを入力して読み込まれたか確認します。
同梱ファイルreferences/advanced-patterns.mdreferences/security-examples.md
詳細
Three.js / TresJS 開発スキル
ファイル構成:このスキルは分割構成を使用します。高度なパターンやセキュリティの例については、
references/を参照してください。
1. 概要
このスキルでは、Three.js と TresJS(Vue 3 統合)を使用した 3D HUD インターフェースの構築に関する知識を提供します。JARVIS AI アシスタント向けに、高性能で視覚的に優れたホログラフィックディスプレイを作成することに重点を置いています。
リスクレベル:中 — GPU リソースの消費、カラー解析における ReDoS の可能性、WebGL のセキュリティ上の考慮事項
主な用途:
- 3D ホログラフィック HUD パネルのレンダリング
- ステータスインジケーターとゲージのアニメーション
- システムの可視化に使用するパーティクルエフェクト
- 3D 要素を含むリアルタイムのメトリクス表示
2. 主な責務
2.1 基本原則
- まず TDD:実装の前にテストを作成し、3D コンポーネントが正しくレンダリングされることを確認します
- パフォーマンスを考慮:インスタンシング、LOD、効率的なレンダーループにより、60fps を目指して最適化します
- リソース管理:メモリーリークを防ぐため、ジオメトリー、マテリアル、テクスチャは必ず破棄します
- Vue のリアクティビティとの統合:TresJS を使用して、Vue 3 Composition API とシームレスに統合します
- 安全なカラー解析:ReDoS 攻撃を防ぐため、カラー入力を検証します
- GPU の保護:GPU リソースの枯渇を防ぐ対策を実装します
- アクセシビリティ:WebGL 非対応デバイス向けの代替手段を提供します
3. 技術スタックとバージョン
3.1 推奨バージョン
| パッケージ | バージョン | セキュリティ上の注意 |
|---|---|---|
| three | ^0.160.0+ | 最新の安定版。CVE-2020-28496 の ReDoS を修正 |
| @tresjs/core | ^4.0.0 | Vue 3 統合 |
| @tresjs/cientos | ^3.0.0 | コンポーネントライブラリ |
| postprocessing | ^6.0.0 | エフェクトライブラリ |
3.2 セキュリティ上重要な更新
{
"dependencies": {
"three": "^0.160.0",
"@tresjs/core": "^4.0.0",
"@tresjs/cientos": "^3.0.0"
}
}
注記:0.137.0 より前のバージョンには XSS の脆弱性があり、0.125.0 より前のバージョンには ReDoS の脆弱性があります。
4. 実装パターン
4.1 基本的な HUD シーンのセットアップ
<script setup lang="ts">
import { TresCanvas } from '@tresjs/core'
import { OrbitControls } from '@tresjs/cientos'
const gl = {
clearColor: '#000011',
alpha: true,
antialias: true,
powerPreference: 'high-performance'
}
</script>
<template>
<TresCanvas v-bind="gl">
<TresPerspectiveCamera :position="[0, 0, 5]" />
<OrbitControls :enable-damping="true" />
<HUDPanels />
<MetricsDisplay />
<ParticleEffects />
</TresCanvas>
</template>
4.2 安全なカラー処理
// utils/safeColor.ts
import { Color } from 'three'
// ✅ Safe color parsing with validation
export function safeParseColor(input: string): Color {
// Validate format to prevent ReDoS
const hexPattern = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/
const rgbPattern = /^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/
if (!hexPattern.test(input) && !rgbPattern.test(input)) {
console.warn('Invalid color format, using default')
return new Color(0x00ff00) // Default JARVIS green
}
return new Color(input)
}
// ❌ DANGEROUS - User input directly to Color
// const color = new Color(userInput) // Potential ReDoS
// ✅ SECURE - Validated input
const color = safeParseColor(userInput)
4.3 メモリー安全なコンポーネント
<script setup lang="ts">
import { onUnmounted, shallowRef } from 'vue'
import { Mesh, BoxGeometry, MeshStandardMaterial } from 'three'
// ✅ Use shallowRef for Three.js objects
const meshRef = shallowRef<Mesh | null>(null)
// ✅ Cleanup on unmount
onUnmounted(() => {
if (meshRef.value) {
meshRef.value.geometry.dispose()
if (Array.isArray(meshRef.value.material)) {
meshRef.value.material.forEach(m => m.dispose())
} else {
meshRef.value.material.dispose()
}
}
})
</script>
<template>
<TresMesh ref="meshRef">
<TresBoxGeometry :args="[1, 1, 1]" />
<TresMeshStandardMaterial color="#00ff41" />
</TresMesh>
</template>
4.4 パフォーマンスに最適化されたインスタンシング
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { InstancedMesh, Object3D, Matrix4 } from 'three'
const instanceCount = 1000
const instancedMeshRef = ref<InstancedMesh | null>(null)
onMounted(() => {
if (!instancedMeshRef.value) return
const dummy = new Object3D()
const matrix = new Matrix4()
// ✅ Batch updates for performance
for (let i = 0; i < instanceCount; i++) {
dummy.position.set(
Math.random() * 10 - 5,
Math.random() * 10 - 5,
Math.random() * 10 - 5
)
dummy.updateMatrix()
instancedMeshRef.value.setMatrixAt(i, dummy.matrix)
}
instancedMeshRef.value.instanceMatrix.needsUpdate = true
})
</script>
<template>
<TresInstancedMesh ref="instancedMeshRef" :args="[null, null, instanceCount]">
<TresSphereGeometry :args="[0.05, 8, 8]" />
<TresMeshBasicMaterial color="#00ff41" />
</TresInstancedMesh>
</template>
4.5 テキスト付き HUD パネル
<script setup lang="ts">
import { Text } from '@tresjs/cientos'
const props = defineProps<{
title: string
value: number
}>()
// ✅ Sanitize text content
const safeTitle = computed(() =>
props.title.replace(/[<>]/g, '').slice(0, 50)
)
</script>
<template>
<TresGroup>
<TresMesh>
<TresPlaneGeometry :args="[2, 1]" />
<TresMeshBasicMaterial
color="#001122"
:transparent="true"
:opacity="0.8"
/>
</TresMesh>
<Text
:text="safeTitle"
:font-size="0.15"
color="#00ff41"
:position="[-0.8, 0.3, 0.01]"
/>
<Text
:text="String(props.value)"
:font-size="0.3"
color="#ffffff"
:position="[0, -0.1, 0.01]"
/>
</TresGroup>
</template>
5. 実装ワークフロー(TDD)
5.1 3D コンポーネントの TDD プロセス
ステップ 1:まず失敗するテストを書く
// tests/components/hud-panel.test.ts
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { mount, VueWrapper } from '@vue/test-utils'
import { Scene, WebGLRenderer } from 'three'
import HUDPanel from '~/components/hud/HUDPanel.vue'
describe('HUDPanel', () => {
let wrapper: VueWrapper
beforeEach(() => {
// Mock WebGL context for testing
const canvas = document.createElement('canvas')
const gl = canvas.getContext('webgl2')
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(gl)
})
afterEach(() => {
wrapper?.unmount()
vi.restoreAllMocks()
})
it('renders panel with correct dimensions', () => {
wrapper = mount(HUDPanel, {
props: { width: 2, height: 1, title: 'Status' }
})
// Test fails until component is implemented
expect(wrapper.exists()).toBe(true)
})
it('disposes resources on unmount', async () => {
wrapper = mount(HUDPanel, {
props: { width: 2, height: 1, title: 'Status' }
})
const disposeSpy = vi.fn()
wrapper.vm.meshRef.geometry.dispose = disposeSpy
wrapper.unmount()
expect(disposeSpy).toHaveBeenCalled()
})
})
ステップ 2:テストを通すために最小限の実装を行う
<script setup lang="ts">
import { shallowRef, onUnmounted } from 'vue'
import { Mesh } from 'three'
const props = defineProps<{
width: number
height: number
title: string
}>()
const meshRef = shallowRef<Mesh | null>(null)
onUnmounted(() => {
if (meshRef.value) {
meshRef.value.geometry.dispose()
;(meshRef.value.material as any).dispose()
}
})
</script>
<template>
<TresMesh ref="meshRef">
<TresPlaneGeometry :args="[props.width, props.height]" />
<TresMeshBasicMaterial color="#001122" :transparent="true" :opacity="0.8" />
</TresMesh>
</template>
ステップ 3:パターンに従ってリファクタリングする
// After tests pass, add performance optimizations
// - Use instancing for multiple panels
// - Add LOD for distant panels
// - Implement texture atlases for text
ステップ 4:完全な検証を実行する
# Run all tests
npm test
# Run with coverage
npm test -- --coverage
# Type check
npm run typecheck
# Performance benchmark
npm run test:perf
5.2 3D アニメーションのテスト
import { describe, it, expect, vi } from 'vitest'
import { useRenderLoop } from '@tresjs/core'
describe('Animation Loop', () => {
it('maintains 60fps during animation', async () => {
const frameTimes: number[] = []
let lastTime = performance.now()
const { onLoop } = useRenderLoop()
onLoop(() => {
const now = performance.now()
frameTimes.push(now - lastTime)
lastTime = now
})
// Simulate 60 frames
await new Promise(resolve => setTimeout(resolve, 1000))
const avgFrameTime = frameTimes.reduce((a, b) => a + b, 0) / frameTimes.length
expect(avgFrameTime).toBeLessThan(16.67) // 60fps = 16.67ms per frame
})
it('cleans up animation loop on unmount', () => {
const cleanup = vi.fn()
const { pause } = useRenderLoop()
// Component unmounts
pause()
expect(cleanup).not.toThrow()
})
})
5.3 リソース破棄のテスト
describe('Resource Management', () => {
it('disposes all GPU resources', () => {
const geometry = new BoxGeometry(1, 1, 1)
const material = new MeshStandardMaterial({ color: 0x00ff41 })
const mesh = new Mesh(geometry, material)
const geoDispose = vi.spyOn(geometry, 'dispose')
const matDispose = vi.spyOn(material, 'dispose')
// Cleanup function
mesh.geometry.dispose()
mesh.material.dispose()
expect(geoDispose).toHaveBeenCalled()
expect(matDispose).toHaveBeenCalled()
})
it('handles material arrays correctly', () => {
const materials = [
new MeshBasicMaterial(),
new MeshStandardMaterial()
]
const mesh = new Mesh(new BoxGeometry(), materials)
const spies = materials.map(m => vi.spyOn(m, 'dispose'))
materials.forEach(m => m.dispose())
spies.forEach(spy => expect(spy).toHaveBeenCalled())
})
})
6. パフォーマンスパターン
6.1 ジオメトリーのインスタンシング
// Good: Use InstancedMesh for repeated objects
import { InstancedMesh, Matrix4, Object3D } from 'three'
const COUNT = 1000
const mesh = new InstancedMesh(geometry, material, COUNT)
const dummy = new Object3D()
for (let i = 0; i < COUNT; i++) {
dummy.position.set(Math.random() * 10, Math.random() * 10, Math.random() * 10)
dummy.updateMatrix()
mesh.setMatrixAt(i, dummy.matrix)
}
mesh.instanceMatrix.needsUpdate = true
// Bad: Creating individual meshes
for (let i = 0; i < COUNT; i++) {
const mesh = new Mesh(geometry.clone(), material.clone()) // Memory waste!
scene.add(mesh)
}
6.2 テクスチャアトラス
// Good: Single texture atlas for multiple sprites
const atlas = new TextureLoader().load('/textures/hud-atlas.png')
const materials = {
panel: new SpriteMaterial({ map: atlas }),
icon: new SpriteMaterial({ map: atlas })
}
// Set UV offsets for different sprites
materials.panel.map.offset.set(0, 0.5)
materials.panel.map.repeat.set(0.5, 0.5)
// Bad: Loading separate textures
const panelTex = new TextureLoader().load('/textures/panel.png')
const iconTex = new TextureLoader().load('/textures/icon.png')
// Multiple draw calls, more GPU memory
6.3 詳細度(LOD)
// Good: Use LOD for complex objects
import { LOD } from 'three'
const lod = new LOD()
// High detail - close up
const highDetail = new Mesh(
new SphereGeometry(1, 32, 32),
material
)
lod.addLevel(highDetail, 0)
// Medium detail - mid range
const medDetail = new Mesh(
new SphereGeometry(1, 16, 16),
material
)
lod.addLevel(medDetail, 10)
// Low detail - far away
const lowDetail = new Mesh(
new SphereGeometry(1, 8, 8),
material
)
lod.addLevel(lowDetail, 20)
scene.add(lod)
// Bad: Always rendering high detail
const sphere = new Mesh(new SphereGeometry(1, 64, 64), material)
6.4 視錐台カリング
// Good: Enable frustum culling (default, but verify)
mesh.frustumCulled = true
// For custom bounds optimization
mesh.geometry.computeBoundingSphere()
mesh.geometry.computeBoundingBox()
// Manual visibility check for complex scenes
const frustum = new Frustum()
const matrix = new Matrix4().multiplyMatrices(
camera.projectionMatrix,
camera.matrixWorldInverse
)
frustum.setFromProjectionMatrix(matrix)
objects.forEach(obj => {
obj.visible = frustum.intersectsObject(obj)
})
// Bad: Disabling culling or rendering everything
mesh.frustumCulled = false // Renders even when off-screen
6.5 オブジェクトプーリング
// Good: Pool and reuse objects
class ParticlePool {
private pool: Mesh[] = []
private active: Set<Mesh> = new Set()
constructor(private geometry: BufferGeometry, private material: Material) {
// Pre-allocate pool
for (let i = 0; i < 100; i++) {
const mesh = new Mesh(geometry, material)
mesh.visible = false
this.pool.push(mesh)
}
}
acquire(): Mesh | null {
const mesh = this.pool.find(m => !this.active.has(m))
if (mesh) {
mesh.visible = true
this.active.add(mesh)
return mesh
}
return null
}
release(mesh: Mesh): void {
mesh.visible = false
this.active.delete(mesh)
}
}
// Bad: Creating/destroying objects each frame
function spawnParticle() {
const mesh = new Mesh(geometry, material) // GC pressure!
scene.add(mesh)
setTimeout(() => {
scene.remove(mesh)
mesh.geometry.dispose()
}, 1000)
}
6.6 RAF の最適化
// Good: Efficient render loop
let lastTime = 0
const targetFPS = 60
const frameInterval = 1000 / targetFPS
function animate(currentTime: number) {
requestAnimationFrame(animate)
const delta = currentTime - lastTime
// Skip frame if too soon (for battery saving)
if (delta < frameInterval) return
lastTime = currentTime - (delta % frameInterval)
// Update only what changed
if (needsUpdate) {
updateScene()
renderer.render(scene, camera)
}
}
// Bad: Rendering every frame unconditionally
function animate() {
requestAnimationFrame(animate)
// Always updates everything
updateAllObjects()
renderer.render(scene, camera) // Even if nothing changed
}
6.7 シェーダーの最適化
// Good: Simple, optimized shaders
const material = new ShaderMaterial({
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
varying vec2 vUv;
uniform vec3 color;
void main() {
gl_FragColor = vec4(color, 1.0);
}
`,
uniforms: {
color: { value: new Color(0x00ff41) }
}
})
// Bad: Complex calculations in fragment shader
// Avoid: loops, conditionals, texture lookups when possible
7. セキュリティ基準
7.1 既知の脆弱性
| CVE | 重大度 | 説明 | 緩和策 |
|---|---|---|---|
| CVE-2020-28496 | 高 | カラー解析における ReDoS | 0.125.0 以降に更新し、カラーを検証する |
| CVE-2022-0177 | 中 | ドキュメントにおける XSS | 0.137.0 以降に更新する |
7.2 OWASP Top 10 の対応
| OWASP カテゴリー | リスク | 緩和策 |
|---|---|---|
| A05 インジェクション | 中 | すべてのカラー/テキスト入力を検証する |
| A06 脆弱なコンポーネント | 高 | Three.js を最新の状態に保つ |
7.3 GPU リソースの保護
// composables/useResourceLimit.ts
export function useResourceLimit() {
const MAX_TRIANGLES = 1_000_000
const MAX_DRAW_CALLS = 100
let triangleCount = 0
function checkGeometry(geometry: BufferGeometry): boolean {
const triangles = geometry.index
? geometry.index.count / 3
: geometry.attributes.position.count / 3
if (triangleCount + triangles > MAX_TRIANGLES) {
console.error('Triangle limit exceeded')
return false
}
triangleCount += triangles
return true
}
return { checkGeometry }
}
6. テストと品質
6.1 コンポーネントテスト
import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
describe('HUD Panel', () => {
it('sanitizes malicious title input', () => {
const wrapper = mount(HUDPanel, {
props: {
title: '<script>alert("xss")</script>Status',
value: 75
}
})
expect(wrapper.vm.safeTitle).not.toContain('<script>')
})
})
6.2 パフォーマンステスト
describe('Instanced Mesh', () => {
it('handles 1000 instances without frame drop', async () => {
const scene = new Scene()
// Setup instanced mesh...
const startTime = performance.now()
renderer.render(scene, camera)
const renderTime = performance.now() - startTime
expect(renderTime).toBeLessThan(16.67) // 60fps target
})
})
8. よくある間違いとアンチパターン
8.1 重大なセキュリティ上のアンチパターン
絶対に避ける:ユーザーのカラーを直接解析する
// ❌ DANGEROUS - ReDoS vulnerability
const color = new Color(userInput)
// ✅ SECURE - Validated input
const color = safeParseColor(userInput)
絶対に避ける:リソースの破棄を省略する
// ❌ MEMORY LEAK
const mesh = new Mesh(geometry, material)
scene.remove(mesh)
// Geometry and material still in GPU memory!
// ✅ PROPER CLEANUP
scene.remove(mesh)
mesh.geometry.dispose()
mesh.material.dispose()
8.2 パフォーマンス上のアンチパターン
避ける:レンダーループ内でオブジェクトを作成する
// ❌ BAD - Creates garbage every frame
function animate() {
mesh.position.add(new Vector3(0, 0.01, 0)) // New object every frame!
}
// ✅ GOOD - Reuse objects
const velocity = new Vector3(0, 0.01, 0)
function animate() {
mesh.position.add(velocity)
}
13. デプロイ前チェックリスト
セキュリティ検証
- Three.js のバージョンが 0.137.0 以上(XSS の修正)
- すべてのカラー入力を解析前に検証している
- ユーザー入力を
new Color()に直接渡していない - リソース制限を適用している
パフォーマンスの検証
- アンマウント時にすべてのジオメトリ/マテリアルが破棄される
- 繰り返し使用するオブジェクトにインスタンシングを使用する
- レンダーループ内でオブジェクトを生成しない
- 複雑なシーンに LOD を実装する
14. まとめ
Three.js/TresJS は、JARVIS HUD 向けに 3D レンダリングを提供します。
- セキュリティ:すべての入力を検証します。特に ReDoS を防ぐため、色の入力を検証してください
- メモリ:コンポーネントのアンマウント時に、必ずリソースを破棄します
- パフォーマンス:インスタンシングを使用し、レンダーループ内での割り当てを避けます
- 統合:TresJS により、Vue 3 のリアクティビティをシームレスに利用できます
注意:WebGL は GPU に直接アクセスするため、常に入力を検証し、リソースを慎重に管理してください。
参考資料:
references/advanced-patterns.md- 複雑な 3D パターンreferences/security-examples.md- WebGL のセキュリティ対策