PGE-06Pages

three.jsの3Dヒーロー|金属・陶器・ガラスのPBR切替サンプル(モデル不要)

モデルデータもテクスチャ画像も要らない three.js の3Dヒーロー。金属・陶磁・アンバーガラスの3標本をボタンで切り替え、「3つを並べる」で同じ光・同じ画角のまま見比べられる。ガラスの後ろには罫線と文字を描いた背景板を置き、屈折で線と文字が曲がって見える(MeshPhysicalMaterial の transmission は不透明な物体だけを透かして映すので、背景板は不透明にする。板の絵は canvas 2D で描いて CanvasTexture にするので画像ファイルは持たない)。形は TorusKnot / Lathe(回転体のプロファイルを関数で作る)/ Extrude(角丸シェイプ+ベベル)でコード生成し、映り込みは白い箱の内側に発光板を4枚置いた"撮影スタジオ"を PMREMGenerator.fromScene() で環境マップに畳む(HDRI を読まない・アンバーの背面パネルで反射の色をブランドに寄せる)。光源は方向光(影あり)+アンバーの点光源+半球光の3灯、影は ShadowMaterial の床1枚。登場・退場・浮遊は AnimationMixer に手組みのキーフレームを流す。作って確かめたこと: ①scene.environment だけで環境マップを渡すと、材質ごとの envMapIntensity は効かない(three 0.185.1 の WebGLMaterials は material.envMap を持つ材質にだけ値を渡す)。金属向けに明るく作ったスタジオを陶磁器がそのまま受けると全面が白く飛ぶので、各材質に envMap を持たせ、陶磁器だけ映り込みを 0.3 に弱めて側面に陰を残した ②シェーダーは初めて描くときに組み立てられ、透過の材質は初めて画面に出たときにもう一枚の描画先を作る。起動時に3標本を並べた状態で compile と1回の描画を済ませてから見せるので、切り替えた後に止まらない ③WebGL の対応確認に作った文脈をそのまま three に渡す(確認用に別の canvas を作ると文脈を2回作ることになり、ソフトウェア描画の検証環境ではその分だけ起動が遅れた)④GL の命令は出した時点ではまだ描かれておらず、ソフトウェア描画の環境では GPU 側で数秒かかることがある。その間に canvas を見せると舞台が空白に見えるので、1枚目を描いた後に requestAnimationFrame が2回呼ばれる(=描き終わった)のを待ってから見せ、それまでは CSS で描いた3標本の静止見本を出す。リサイズで描画先の大きさを変えたときも同じ処理の中で1枚描き直す⑤低速な端末では解像度を落とし、それでも遅ければ自動の動きだけを止めて最後の3Dの絵を残し、押したときだけ描き直す(静止パネルへ降りるのは WebGL 非対応とコンテキストロストのときだけ)。押した直後はボタンの色・下線・舞台の標本名が同じ描画で変わり、舞台全体が0.22秒で小さく沈んで戻り(切り替えの始まりと終わりの合図)、下端をアンバーの線が0.42秒で走る。⑥押した状態の3Dが実際に画面へ出たか(登場が3割を超えて描いた後に rAF が2回呼ばれたか)を切り替えごとの通し番号で確かめ、0.3秒たっても出ていなければ同じ状態の静止見本(紙の地と背景板の線つき・並べるときは3つ)を3Dの上に重ねる。描画の遅い端末でも、選んだ素材と舞台の絵が食い違わない。狭い幅では舞台→切り替え→文言の順に並べ、立体と3つの切り替えを最初の画面に入れる。768px以上では切り替えを舞台の右上に重ね、押してもページがスクロールしない位置に置く(材質パラメータの台帳は舞台の下に表示だけ残す)。three を使うのはこのギャラリーの依存ゼロ方針の例外で、PBR・環境マップ・影・アニメーションを素の WebGL で書くと割に合わないため。追加コスト(three 0.185.1・本番ビルドで実測)は、3Dを表示する画面でだけ読み込む別チャンク2本で計 752,089バイト(約734KB)・gzip 187,108バイト(約183KB)。useEffect 内の動的 import で切り出し、縮小プレビューでは親の scale を rect.width÷offsetWidth で検出して読み込まない。prefers-reduced-motion では自動回転もタイムラインも動かさず1枚だけ描く。文言・配色・シェイプはすべて First CH のオリジナル。出典(いずれも2026-10-29確認): three.js 公式ドキュメント MeshPhysicalMaterial(transmission は0〜1・既定0、ior は1.0〜2.333・既定1.5、thickness は既定0で0なら薄い壁扱い、attenuationDistance は既定 Infinity)https://threejs.org/docs/pages/MeshPhysicalMaterial.html / PMREMGenerator(fromScene の sigma 既定0・size 既定256)https://threejs.org/docs/pages/PMREMGenerator.html / WebGLRenderer の compile・compileAsync(初回描画の前にシェーダーを組み立てる。compileAsync は KHR_parallel_shader_compile 拡張を使う)https://threejs.org/docs/pages/WebGLRenderer.html / npm レジストリの three の公開履歴(最新は 0.186.1・2026-09-24 公開。本作は 0.185.1・2026-07-01 公開で組んで確かめている)https://www.npmjs.com/package/three

プレビュー

3D OBJECT STUDY

Real-time 3D

Depth,
on demand.

モデルデータなしで、金属・陶磁・ガラスの質感をコードだけで描くヒーローです。光と影、動きまで案件のトーンに合わせて作れます。

3D演出を相談する

01メタル・トーラスノットDrag

three.js は3Dを実際に表示する画面でのみ動的読み込み(別チャンク)。縮小プレビュー・非対応環境・描画が追いつかない間は同じ状態の静止見本を表示します。

X でシェア

説明の全文を読む

モデルデータもテクスチャ画像も要らない three.js の3Dヒーロー。金属・陶磁・アンバーガラスの3標本をボタンで切り替え、「3つを並べる」で同じ光・同じ画角のまま見比べられる。ガラスの後ろには罫線と文字を描いた背景板を置き、屈折で線と文字が曲がって見える(MeshPhysicalMaterial の transmission は不透明な物体だけを透かして映すので、背景板は不透明にする。板の絵は canvas 2D で描いて CanvasTexture にするので画像ファイルは持たない)。形は TorusKnot / Lathe(回転体のプロファイルを関数で作る)/ Extrude(角丸シェイプ+ベベル)でコード生成し、映り込みは白い箱の内側に発光板を4枚置いた"撮影スタジオ"を PMREMGenerator.fromScene() で環境マップに畳む(HDRI を読まない・アンバーの背面パネルで反射の色をブランドに寄せる)。光源は方向光(影あり)+アンバーの点光源+半球光の3灯、影は ShadowMaterial の床1枚。登場・退場・浮遊は AnimationMixer に手組みのキーフレームを流す。作って確かめたこと: ①scene.environment だけで環境マップを渡すと、材質ごとの envMapIntensity は効かない(three 0.185.1 の WebGLMaterials は material.envMap を持つ材質にだけ値を渡す)。金属向けに明るく作ったスタジオを陶磁器がそのまま受けると全面が白く飛ぶので、各材質に envMap を持たせ、陶磁器だけ映り込みを 0.3 に弱めて側面に陰を残した ②シェーダーは初めて描くときに組み立てられ、透過の材質は初めて画面に出たときにもう一枚の描画先を作る。起動時に3標本を並べた状態で compile と1回の描画を済ませてから見せるので、切り替えた後に止まらない ③WebGL の対応確認に作った文脈をそのまま three に渡す(確認用に別の canvas を作ると文脈を2回作ることになり、ソフトウェア描画の検証環境ではその分だけ起動が遅れた)④GL の命令は出した時点ではまだ描かれておらず、ソフトウェア描画の環境では GPU 側で数秒かかることがある。その間に canvas を見せると舞台が空白に見えるので、1枚目を描いた後に requestAnimationFrame が2回呼ばれる(=描き終わった)のを待ってから見せ、それまでは CSS で描いた3標本の静止見本を出す。リサイズで描画先の大きさを変えたときも同じ処理の中で1枚描き直す⑤低速な端末では解像度を落とし、それでも遅ければ自動の動きだけを止めて最後の3Dの絵を残し、押したときだけ描き直す(静止パネルへ降りるのは WebGL 非対応とコンテキストロストのときだけ)。押した直後はボタンの色・下線・舞台の標本名が同じ描画で変わり、舞台全体が0.22秒で小さく沈んで戻り(切り替えの始まりと終わりの合図)、下端をアンバーの線が0.42秒で走る。⑥押した状態の3Dが実際に画面へ出たか(登場が3割を超えて描いた後に rAF が2回呼ばれたか)を切り替えごとの通し番号で確かめ、0.3秒たっても出ていなければ同じ状態の静止見本(紙の地と背景板の線つき・並べるときは3つ)を3Dの上に重ねる。描画の遅い端末でも、選んだ素材と舞台の絵が食い違わない。狭い幅では舞台→切り替え→文言の順に並べ、立体と3つの切り替えを最初の画面に入れる。768px以上では切り替えを舞台の右上に重ね、押してもページがスクロールしない位置に置く(材質パラメータの台帳は舞台の下に表示だけ残す)。three を使うのはこのギャラリーの依存ゼロ方針の例外で、PBR・環境マップ・影・アニメーションを素の WebGL で書くと割に合わないため。追加コスト(three 0.185.1・本番ビルドで実測)は、3Dを表示する画面でだけ読み込む別チャンク2本で計 752,089バイト(約734KB)・gzip 187,108バイト(約183KB)。useEffect 内の動的 import で切り出し、縮小プレビューでは親の scale を rect.width÷offsetWidth で検出して読み込まない。prefers-reduced-motion では自動回転もタイムラインも動かさず1枚だけ描く。文言・配色・シェイプはすべて First CH のオリジナル。出典(いずれも2026-10-29確認): three.js 公式ドキュメント MeshPhysicalMaterial(transmission は0〜1・既定0、ior は1.0〜2.333・既定1.5、thickness は既定0で0なら薄い壁扱い、attenuationDistance は既定 Infinity)https://threejs.org/docs/pages/MeshPhysicalMaterial.html / PMREMGenerator(fromScene の sigma 既定0・size 既定256)https://threejs.org/docs/pages/PMREMGenerator.html / WebGLRenderer の compile・compileAsync(初回描画の前にシェーダーを組み立てる。compileAsync は KHR_parallel_shader_compile 拡張を使う)https://threejs.org/docs/pages/WebGLRenderer.html / npm レジストリの three の公開履歴(最新は 0.186.1・2026-09-24 公開。本作は 0.185.1・2026-07-01 公開で組んで確かめている)https://www.npmjs.com/package/three

追加日:
2026-08-19
更新日:
2026-10-29
依存:
three
tags
#hero #page #threejs #3d #webgl #pbr #material #glass #refraction #environment-map #shadow #animation #interactive #motion #no-image #dynamic-import
"use client";

import { useEffect, useRef, useState } from "react";
import { Montserrat } from "next/font/google";
// 型だけの import。tsc が消すので three のコードは1バイトも入らない(実体は下の dynamic import)。
import type * as THREE from "three";

const montserrat = Montserrat({
  weight: ["700"],
  subsets: ["latin"],
  display: "swap",
});

/**
 * three.js オブジェクト・ギャラリーHero(PGE-06)
 *
 * このギャラリーで唯一 3D ライブラリを使う標本。素の WebGL で書くと割に合わない領域
 * (PBR・環境マップ・影・アニメーション)だけを担当させ、「3Dを載せたい」案件に
 * コードだけで応えられることを示す。
 *
 * 汎用技法メモ:
 * 1. **重いライブラリは静的 import しない**。three はこの構成の実測(three 0.185.1・本番ビルド)で
 *    追加チャンク2本・計 752,089バイト(約734KB・gzip 187,108バイト=約183KB)あり、
 *    静的 import すると読み込んだページ全部に乗る。`useEffect` の中で
 *    `await import("three")` すればバンドラが別チャンクに切り出し、
 *    「3Dを実際に動かすときだけ」ネットワークに出る(サーバ側では実行されないので
 *    ssr:false と同じ効果になる。1ファイルで配布したいのでこの形にしている)。
 * 2. **モデルデータは要らない**。TorusKnot / Lathe(回転体)/ Extrude(押し出し+ベベル)
 *    の3つで「金属・陶磁・ガラス」の質感実証には足りる。プロファイルを配列で持てば
 *    形はコードで作れるので、glTF もテクスチャも配布物に含めなくていい。
 * 3. **環境マップも画像を持たない**。白い箱の内側に発光板(emissive のみの
 *    MeshLambertMaterial)を数枚置いた"スタジオ"を組み、`PMREMGenerator.fromScene()`
 *    で畳んで `scene.environment` に渡す。金属とガラスに映り込む「面光源の形」が
 *    出るのがPBRらしさの正体で、HDRI ファイルを読むより軽くて色も自由に決められる。
 * 4. **ガラスは「後ろに何があるか」で読める**。標本の背後に罫線と文字を描いた背景板
 *    (canvas 2D で描いて CanvasTexture にする=画像ファイルは持たない)を不透明で置く。
 *    transmission の材質は不透明な物体だけを屈折させて映すので、背景板を透明にすると
 *    線が曲がって見えない。3標本とも同じ背景板・同じ光で撮るので、並べて比べられる。
 * 5. **切り替えで待たせない**。シェーダーは初回描画の時に組み立てられ、ガラス(透過)は
 *    初めて画面に出た時にもう一枚の描画先を作る。起動時に3標本を全部出した状態で
 *    `renderer.compileAsync()` と1回の描画を済ませてから見せると、押した後に止まらない。
 * 6. **AnimationMixer はモデルが無くても使える**。`VectorKeyframeTrack('.scale', …)`
 *    のようにトラックを手で組んで `AnimationClip` にすれば、登場・退場・浮遊を
 *    タイムラインとして扱える(rAF の中に手続きを書き散らさずに済む)。
 * 7. 影は `ShadowMaterial` の床1枚。床のマテリアル自体は透明なので、接地影だけが落ちる。
 * 8. 停止条件は WebGL 標本と同じ3つ(reduced-motion / 画面外 / タブ非表示)に
 *    「縮小プレビューでは起動しない」を足す。親に transform:scale が掛かっているかは
 *    `getBoundingClientRect().width ÷ offsetWidth` で測れる(前者は変形後、
 *    後者はレイアウト幅)。一覧のカードで重いライブラリを読ませないための保険。
 * 9. コンテキストロストは必ず `preventDefault()` で握り、アンマウント時は
 *    geometry / material / renderer を dispose して `forceContextLoss()` する。
 *    描画先の大きさを変えると canvas は消えるので、リサイズの後は必ず同じ処理の中で1枚描く
 *    (次のフレームを待つと、その間だけ舞台が空白に見える)。
 *
 * 文言・配色・構図・シェイプはすべて First CH のオリジナル。
 */

type ThreeModule = typeof import("three");

const AMBER = 0xd97706;
const INK = 0x221e19;
// 背景板の紙の色。読み込み前の舞台(CSS)も同じ色にして、3Dへの切り替わりで色が跳ねないようにする
const PAPER = "#f1ece3";

type Specimen = {
  no: string;
  ja: string;
  short: string;
  en: string;
  spec: string;
};

const SPECIMENS: Specimen[] = [
  {
    no: "01",
    ja: "メタル・トーラスノット",
    short: "メタル",
    en: "Metal / knot",
    spec: "metalness 1.00 / roughness 0.18",
  },
  {
    no: "02",
    ja: "セラミック・ベッセル",
    short: "陶器",
    en: "Ceramic / lathe",
    spec: "clearcoat 1.00 / roughness 0.42",
  },
  {
    no: "03",
    ja: "アンバーガラス・プレート",
    short: "ガラス",
    en: "Glass / extrude",
    spec: "transmission 1.00 / ior 1.52",
  },
];

// 並べて比べるときの横位置と縮尺(同じ画角・同じ光のまま3つを1枚に入れる)
const COMPARE_X = [-1.3, 0, 1.3];
const COMPARE_SCALE = 0.6;

type StudioApi = {
  setView: (index: number, compare: boolean, seq?: number) => void;
  setRunning: (running: boolean) => void;
  dispose: () => void;
};

type StudioOptions = {
  canvas: HTMLCanvasElement;
  context: WebGL2RenderingContext;
  host: HTMLElement;
  index: number;
  compare: boolean;
  seq: number;
  fontFamily: string;
  isCancelled: () => boolean;
  onFirstFrame: () => void;
  /** 押した切り替え(seq)の絵が実際に画面へ出たら呼ぶ。それまでは舞台に同じ状態の静止見本を重ねる */
  onViewPainted: (seq: number) => void;
  onFail: () => void;
};

/**
 * 背景板の絵(罫線・目盛り・文字)を canvas 2D で描く。ガラスの屈折と金属の隙間から
 * 線と文字が見えるように、標本の真後ろ(板の中央より少し下)に濃い線を集めている。
 */
function drawBackdrop(fontFamily: string) {
  const c = document.createElement("canvas");
  c.width = 2048;
  c.height = 1280;
  const g = c.getContext("2d");
  if (!g) return c;
  const W = c.width;
  const H = c.height;
  const cy = H / 2 + 22; // 標本の中心が板に重なる高さ(カメラの高さ0.42から逆算した位置)
  g.fillStyle = PAPER;
  g.fillRect(0, 0, W, H);
  // 方眼(細)と、4マスごとの太い線
  for (let x = 0; x <= W; x += 32) {
    g.fillStyle = x % 128 === 0 ? "rgba(34,30,25,0.12)" : "rgba(34,30,25,0.05)";
    g.fillRect(x, 0, x % 128 === 0 ? 2 : 1.5, H);
  }
  for (let y = 0; y <= H; y += 32) {
    g.fillStyle = y % 128 === 0 ? "rgba(34,30,25,0.12)" : "rgba(34,30,25,0.05)";
    g.fillRect(0, y, W, y % 128 === 0 ? 2 : 1.5);
  }
  // 舞台に映るのは板の中央の約600px四方だけなので、線と文字はそこへ集める(cx±300)
  const cx = W / 2;
  // 大きな文字(ガラス越しに歪んで見える主役の線)
  g.textAlign = "center";
  g.textBaseline = "middle";
  g.fillStyle = "rgba(34,30,25,0.16)";
  g.font = `700 150px ${fontFamily}, Arial, sans-serif`;
  g.fillText("DEPTH", cx, cy - 4);
  // 標本の真後ろを横切る濃い線(3本+アンバー1本)と目盛り
  g.fillStyle = "rgba(34,30,25,0.6)";
  for (const dy of [-96, 0, 96]) g.fillRect(cx - 300, cy + dy, 600, 2);
  g.fillStyle = "rgba(217,119,6,0.9)";
  g.fillRect(cx - 300, cy + 48, 600, 3);
  g.fillStyle = "rgba(34,30,25,0.5)";
  for (let i = 0; i <= 40; i++) {
    const major = i % 5 === 0;
    g.fillRect(
      cx - 300 + i * 15,
      cy - 96 - (major ? 18 : 8),
      1.5,
      major ? 18 : 8,
    );
  }
  g.font = "700 15px ui-monospace, SFMono-Regular, Menlo, monospace";
  g.fillStyle = "rgba(34,30,25,0.6)";
  g.fillText("SAME LIGHT  ·  SAME LENS", cx, cy + 122);
  g.fillText("NO MODEL FILE  ·  NO TEXTURE IMAGE", cx, cy - 136);
  return c;
}

/**
 * 描いた1枚が画面に出るまで待つ。GL の命令は出した時点ではまだ描かれておらず、GPU が詰まっている間は
 * requestAnimationFrame も呼ばれない(ソフトウェア描画の環境で実測)ので、2回呼ばれるのを待てば描き終わっている。
 * WebGL2 の fenceSync も試したが、Chrome では状態の問い合わせ1回ごとに長く止まり、終わりも返らなかった
 */
function nextPaint() {
  return new Promise<void>((resolve) => {
    requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
  });
}

/**
 * 3つの標本を並べた"撮影スタジオ"を組む。React には触れず、返した API 経由でのみ操作する
 * (毎フレームの再レンダーを避けるため、状態は全てクロージャに閉じ込める)。
 * シェーダーの組み立てまで済ませてから返す(途中で取り消されたら片付けて null)。
 */
async function createStudio(
  T: ThreeModule,
  opts: StudioOptions,
): Promise<StudioApi | null> {
  const { canvas, host, onFirstFrame, onViewPainted, onFail, isCancelled } =
    opts;

  const renderer = new T.WebGLRenderer({ canvas, context: opts.context });
  let dpr = Math.min(window.devicePixelRatio || 1, 1.75);
  renderer.setPixelRatio(dpr);
  renderer.toneMapping = T.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.04;
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = T.PCFShadowMap; // r185 で PCFSoft は非推奨。ぼけ幅は shadow.radius で作る

  const scene = new T.Scene();
  const camera = new T.PerspectiveCamera(34, 1, 0.1, 60);
  camera.position.set(0, 0.42, 4.35);
  camera.lookAt(0, 0.06, 0);

  const geometries: THREE.BufferGeometry[] = [];
  const materials: THREE.Material[] = [];
  const textures: THREE.Texture[] = [];

  // --- 環境マップ: 画像を読まず、白い箱+発光板の"スタジオ"を畳んで作る ---------
  const envScene = new T.Scene();
  const envBox = new T.BoxGeometry();
  envBox.deleteAttribute("uv");
  const envResources: Array<{ dispose: () => void }> = [envBox];
  const panel = (
    intensity: number,
    color: number,
    x: number,
    y: number,
    z: number,
    sx: number,
    sy: number,
    sz: number,
  ) => {
    // 発光のみのマテリアル(色を黒にして emissive だけを持たせるのが定石)
    const mat = new T.MeshLambertMaterial({
      color: 0x000000,
      emissive: color,
      emissiveIntensity: intensity,
    });
    envResources.push(mat);
    const mesh = new T.Mesh(envBox, mat);
    mesh.position.set(x, y, z);
    mesh.scale.set(sx, sy, sz);
    envScene.add(mesh);
  };
  // 箱自体は「常に明るい面」でよいので unlit(MeshStandardMaterial だと envScene に光源が無く真っ黒になり、
  // 金属が暗く沈む)。地明かりはやや落とし、金属の面に暗い部分を残す(全面が明るいと白く飛ぶ)。
  const roomMat = new T.MeshBasicMaterial({
    color: 0xd9d3c9,
    side: T.BackSide,
  });
  envResources.push(roomMat);
  const room = new T.Mesh(envBox, roomMat);
  room.scale.set(20, 14, 20);
  envScene.add(room);
  panel(26, 0xffffff, -3.4, 3.2, 2.6, 0.1, 3.4, 4.2); // キーの面光源(左上)
  panel(12, 0xfff6ea, 4.2, 1.4, 1.2, 0.1, 3.0, 3.4); // フィル(右)
  panel(18, 0xffffff, 0, 6.4, 0, 5.0, 0.1, 5.0); // トップライト
  panel(16, AMBER, -0.6, -0.4, -5.6, 4.4, 2.6, 0.1); // アンバーの背面パネル(映り込みの色)
  const pmrem = new T.PMREMGenerator(renderer);
  const envMap = pmrem.fromScene(envScene, 0.02).texture;
  scene.environment = envMap;
  for (const r of envResources) r.dispose();
  pmrem.dispose();

  // --- ライト(複数光源)--------------------------------------------------------
  const key = new T.DirectionalLight(0xffffff, 2.5);
  key.position.set(1.3, 4.6, 2.2); // 影が標本の真下寄りに落ちる高さ(横に長く伸びると床の汚れに見える)
  key.castShadow = true;
  key.shadow.mapSize.set(1024, 1024);
  key.shadow.camera.near = 1;
  key.shadow.camera.far = 12;
  key.shadow.camera.left = -2.6;
  key.shadow.camera.right = 2.6;
  key.shadow.camera.top = 2.6;
  key.shadow.camera.bottom = -2.6;
  key.shadow.bias = -0.0012;
  key.shadow.radius = 6;
  scene.add(key);

  const rim = new T.PointLight(AMBER, 14, 10, 2); // アンバーのリム(輪郭に色を差す)
  rim.position.set(-2.3, 0.7, -1.9);
  scene.add(rim);

  // 半球光は弱め(強いと陶磁器の側面まで均一に明るくなり、紙の背景に輪郭が溶ける)
  const fill = new T.HemisphereLight(0xffffff, 0xd8cdbb, 0.32);
  scene.add(fill);

  // --- 背景板(罫線と文字。ガラスの屈折を見せる)と、接地影だけを受ける床 ------------
  const fontFamily = opts.fontFamily;
  try {
    await Promise.race([
      document.fonts.load(`700 190px ${fontFamily}`),
      new Promise((r) => setTimeout(r, 400)),
    ]);
  } catch {
    // 文字の書体が取れなくても代わりの書体で描く
  }
  if (isCancelled()) {
    renderer.dispose();
    renderer.forceContextLoss();
    return null;
  }
  const backdropTex = new T.CanvasTexture(drawBackdrop(fontFamily));
  backdropTex.colorSpace = T.SRGBColorSpace;
  backdropTex.anisotropy = 4;
  const backdropGeo = new T.PlaneGeometry(12, 7.5);
  // 背景板は光を受けない(toneMapped も切る)ので、どの標本を出しても同じ紙の色のまま
  const backdropMat = new T.MeshBasicMaterial({
    map: backdropTex,
    toneMapped: false,
  });
  const backdrop = new T.Mesh(backdropGeo, backdropMat);
  backdrop.position.set(0, 0.02, -1.45);
  scene.add(backdrop);

  const groundGeo = new T.PlaneGeometry(14, 14);
  const groundMat = new T.ShadowMaterial({ opacity: 0.11, color: INK });
  const ground = new T.Mesh(groundGeo, groundMat);
  ground.rotation.x = -Math.PI / 2;
  ground.position.y = -1.22;
  ground.receiveShadow = true;
  scene.add(ground);

  textures.push(backdropTex);
  geometries.push(backdropGeo, groundGeo);
  materials.push(backdropMat, groundMat);

  // --- 標本3種(ジオメトリはすべてコード生成)----------------------------------
  const knotGeo = new T.TorusKnotGeometry(0.62, 0.205, 190, 28, 2, 3);
  const knotMat = new T.MeshPhysicalMaterial({
    color: AMBER,
    metalness: 1,
    roughness: 0.18,
    envMapIntensity: 1,
  });

  // 回転体のプロファイル(半径をtの関数で作る=壺の輪郭をコードで持つ)
  const profile: THREE.Vector2[] = [new T.Vector2(0.001, -0.92)];
  for (let i = 0; i <= 28; i++) {
    const t = i / 28;
    const y = -0.92 + t * 1.84;
    const r =
      0.3 +
      0.5 * Math.sin(Math.PI * Math.pow(t, 0.8)) -
      0.13 * Math.pow(t, 2.6);
    profile.push(new T.Vector2(Math.max(0.05, r), y));
  }
  const vesselGeo = new T.LatheGeometry(profile, 96);
  // 釉薬の地色は紙(PAPER)より少し暗く置く。光が当たる面だけが紙より白くなり、側面の陰で輪郭が出る
  const vesselMat = new T.MeshPhysicalMaterial({
    color: 0xece6dc,
    metalness: 0,
    roughness: 0.42,
    clearcoat: 1,
    clearcoatRoughness: 0.06,
    side: T.DoubleSide,
    // 発光板のスタジオは金属向けに明るく作ってあり、拡散面がそのまま受けると全面が白く飛ぶ。
    // 陶磁器は映り込みを弱め、キーライトの当たり方で陰影を作る
    envMapIntensity: 0.3,
  });
  // 帯は「その高さの本体半径」より外に置かないと中に埋まって見えない。
  // プロファイル配列から実際の半径を引いて決める(形を関数で持つ利点)。
  const bandY = 0.62;
  const bandSeat = profile.reduce((best, v) =>
    Math.abs(v.y - bandY) < Math.abs(best.y - bandY) ? v : best,
  );
  const bandGeo = new T.TorusGeometry(bandSeat.x + 0.022, 0.02, 12, 96);
  const bandMat = new T.MeshPhysicalMaterial({
    color: AMBER,
    metalness: 1,
    roughness: 0.22,
  });

  // 角丸プレート+中央の抜き。押し出しにベベルを付けると縁がハイライトを拾う
  const plate = new T.Shape();
  const w = 0.68;
  const r0 = 0.3;
  plate.moveTo(-w + r0, -w);
  plate.lineTo(w - r0, -w);
  plate.quadraticCurveTo(w, -w, w, -w + r0);
  plate.lineTo(w, w - r0);
  plate.quadraticCurveTo(w, w, w - r0, w);
  plate.lineTo(-w + r0, w);
  plate.quadraticCurveTo(-w, w, -w, w - r0);
  plate.lineTo(-w, -w + r0);
  plate.quadraticCurveTo(-w, -w, -w + r0, -w);
  const hole = new T.Path();
  hole.absarc(0, 0, 0.235, 0, Math.PI * 2, true);
  plate.holes.push(hole);
  const plateGeo = new T.ExtrudeGeometry(plate, {
    depth: 0.34,
    bevelEnabled: true,
    bevelThickness: 0.07,
    bevelSize: 0.07,
    bevelSegments: 5,
    curveSegments: 34,
  });
  plateGeo.center();
  const plateMat = new T.MeshPhysicalMaterial({
    color: 0xffffff,
    metalness: 0,
    roughness: 0.02,
    transmission: 1,
    ior: 1.52,
    thickness: 0.7,
    attenuationDistance: 1.3,
    attenuationColor: new T.Color(AMBER),
    clearcoat: 1,
    clearcoatRoughness: 0.04,
    envMapIntensity: 1.1,
  });

  geometries.push(knotGeo, vesselGeo, bandGeo, plateGeo);
  materials.push(knotMat, vesselMat, bandMat, plateMat);
  // envMapIntensity は material.envMap を持つ材質にしか渡らない(scene.environment だけだと無視される。
  // three 0.185 の WebGLMaterials で確認)。材質ごとに映り込みの強さを変えるので、各材質に直接持たせる
  for (const m of [knotMat, vesselMat, bandMat, plateMat]) m.envMap = envMap;

  // 入れ子: slot(並べる位置・縮尺)→ group(AnimationMixer が動かす)→ spin(ドラッグの回転)
  // それぞれ別の Object3D にすると、3つの動きが同じ値を取り合わない。
  const buildRig = (build: (spin: THREE.Group) => void) => {
    const slot = new T.Group();
    const group = new T.Group();
    const spin = new T.Group();
    build(spin);
    group.add(spin);
    slot.add(group);
    spin.traverse((o) => {
      const mesh = o as THREE.Mesh;
      if (mesh.isMesh) {
        mesh.castShadow = true;
        mesh.receiveShadow = false;
      }
    });
    group.visible = false;
    group.scale.setScalar(0.001);
    scene.add(slot);
    return { slot, group, spin };
  };

  const parts = [
    buildRig((s) => {
      const m = new T.Mesh(knotGeo, knotMat);
      m.rotation.set(0.3, 0.4, 0);
      s.add(m);
    }),
    buildRig((s) => {
      const m = new T.Mesh(vesselGeo, vesselMat);
      s.add(m);
      const band = new T.Mesh(bandGeo, bandMat);
      band.rotation.x = Math.PI / 2;
      band.position.y = bandSeat.y;
      s.add(band);
    }),
    buildRig((s) => {
      const m = new T.Mesh(plateGeo, plateMat);
      m.rotation.set(-0.16, 0.42, 0.1);
      s.add(m);
    }),
  ];

  // --- AnimationMixer: モデルが無くてもトラックを手で組めばタイムラインになる ----
  // 切り替えは短く(退場0.2秒・登場0.45秒)。押した結果を待たせない長さに揃える
  const enterClip = new T.AnimationClip("enter", 0.45, [
    new T.VectorKeyframeTrack(
      ".scale",
      [0, 0.26, 0.45],
      [0.001, 0.001, 0.001, 1.06, 1.06, 1.06, 1, 1, 1],
    ),
    new T.NumberKeyframeTrack(".rotation[y]", [0, 0.45], [-0.7, 0]),
  ]);
  const exitClip = new T.AnimationClip("exit", 0.2, [
    new T.VectorKeyframeTrack(
      ".scale",
      [0, 0.2],
      [1, 1, 1, 0.001, 0.001, 0.001],
    ),
    new T.NumberKeyframeTrack(".rotation[y]", [0, 0.2], [0, 0.5]),
  ]);
  const floatTrack = new T.VectorKeyframeTrack(
    ".position",
    [0, 1.9, 3.8],
    [0, -0.045, 0, 0, 0.055, 0, 0, -0.045, 0],
  );
  floatTrack.setInterpolation(T.InterpolateSmooth);
  const floatClip = new T.AnimationClip("float", 3.8, [floatTrack]);

  const rigs = parts.map((p) => {
    const mixer = new T.AnimationMixer(p.group);
    const enter = mixer.clipAction(enterClip);
    enter.setLoop(T.LoopOnce, 1);
    enter.clampWhenFinished = true;
    const exit = mixer.clipAction(exitClip);
    exit.setLoop(T.LoopOnce, 1);
    exit.clampWhenFinished = true;
    const drift = mixer.clipAction(floatClip);
    return { ...p, mixer, enter, exit, drift };
  });

  // --- 状態 ---------------------------------------------------------------------
  const motionQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
  let motionOK = !motionQuery.matches;
  let current = opts.index;
  let comparing = opts.compare;
  let shownNow = rigs.map(() => false);
  let raf = 0;
  let running = false;
  let initialized = false;
  let last = performance.now();
  let yaw = -0.3;
  let pitch = 0.1;
  let yawTarget = -0.3;
  let pitchTarget = 0.1;
  let dragging = false;
  let pointerId: number | null = null;
  let lastX = 0;
  let lastY = 0;
  let frames = 0;
  let elapsed = 0;
  let degraded = false;
  let longGaps = 0;
  // 低速の端末では自動の動きをやめて「押したときだけ1枚描く」に切り替える(3Dの絵は残す)
  let still = false;
  let stillPending = false;
  // まだ画面に出たと確かめていない切り替えの番号。描いた後に rAF を2回待ってから React へ知らせる
  let pendingSeq: number | null = opts.seq;
  let disposed = false;
  // 画角に収めたい半幅(1つなら1.75・並べるなら2.45)。切り替えで滑らかに寄せる
  let halfW = comparing ? 2.45 : 1.75;
  let aspect = 1;

  const animated = () => motionOK && !still;
  const shown = (i: number) => comparing || i === current;
  const slotTarget = (i: number) =>
    comparing ? { x: COMPARE_X[i], s: COMPARE_SCALE } : { x: 0, s: 1 };

  const fit = () => {
    camera.aspect = aspect;
    // 縦長でも標本が切れないよう、収めたい"幅"から縦画角を逆算する
    const dist = camera.position.z;
    let vfov = 2 * Math.atan(1.75 / dist);
    const needed = 2 * Math.atan(halfW / (dist * aspect));
    if (needed > vfov) vfov = needed;
    camera.fov = Math.min(64, (vfov * 180) / Math.PI);
    camera.updateProjectionMatrix();
  };

  const resize = () => {
    const rect = host.getBoundingClientRect();
    const width = Math.max(1, Math.round(rect.width));
    const height = Math.max(1, Math.round(rect.height));
    aspect = width / height;
    fit();
    renderer.setSize(width, height, false);
  };

  const renderOnce = () => {
    renderer.render(scene, camera);
  };

  const confirmPainted = () => {
    if (pendingSeq === null) return;
    const s = pendingSeq;
    pendingSeq = null;
    void nextPaint().then(() => {
      if (!disposed) onViewPainted(s);
    });
  };

  // 動かしているとき、新しい状態が「見て分かる」ところまで来たか(登場が3割を超え、退場が半分を過ぎ、並べる位置に寄った)
  const viewSettled = () =>
    rigs.every((rig, i) => {
      if (!shown(i)) return !rig.group.visible || rig.group.scale.x < 0.5;
      const t = slotTarget(i);
      return (
        rig.group.visible &&
        rig.group.scale.x > 0.3 &&
        Math.abs(rig.slot.position.x - t.x) < 0.3 &&
        Math.abs(rig.slot.scale.x - t.s) < 0.2
      );
    });

  // 動かさないときの描き直し。押した描画(ボタンの色・下線)を先に画面へ出してから描く
  // (同じ処理の中で描くと、重い1枚の分だけボタンの変化まで遅れる)
  const requestStill = () => {
    if (stillPending || !initialized) return;
    stillPending = true;
    requestAnimationFrame(() =>
      setTimeout(() => {
        stillPending = false;
        if (disposed) return;
        renderOnce();
        confirmPainted();
      }, 0),
    );
  };

  // 板(ガラス)は一周させると真横を向いて厚みしか見えない時間が長いので、正面の前後で振るだけにする
  const applySpin = () => {
    rigs.forEach((rig, i) => {
      rig.spin.rotation.set(pitch, i === 2 ? Math.sin(yaw) * 0.55 : yaw, 0);
    });
  };

  const frame = (now: number) => {
    raf = requestAnimationFrame(frame);
    const prevNow = last;
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;

    if (!dragging) yawTarget += 0.26 * dt; // 自動回転(モーション許可時のみループが回る)
    const ease = 1 - Math.pow(0.0018, dt);
    const snap = 1 - Math.pow(0.0004, dt); // 並べる・戻すの移動(約0.4秒で寄る)
    yaw += (yawTarget - yaw) * ease;
    pitch += (pitchTarget - pitch) * ease;
    applySpin();

    rigs.forEach((rig, i) => {
      rig.mixer.update(dt);
      const t = slotTarget(i);
      rig.slot.position.x += (t.x - rig.slot.position.x) * snap;
      rig.slot.scale.setScalar(
        rig.slot.scale.x + (t.s - rig.slot.scale.x) * snap,
      );
      // 退場しきった標本は描画から外す(スケール0のメッシュを回し続けない)
      if (!shown(i) && rig.group.scale.x < 0.02) rig.group.visible = false;
    });
    const wantHalfW = comparing ? 2.45 : 1.75;
    if (Math.abs(wantHalfW - halfW) > 1e-4) {
      halfW += (wantHalfW - halfW) * snap;
      fit();
    }

    renderOnce();
    if (pendingSeq !== null && viewSettled()) confirmPainted();

    // 低スペック対策: 立ち上がり5フレームを捨て、続く20フレームの間隔の平均で落とす。
    // 32ms超なら解像度を0.6倍にして測り直し、それでも超える(または最初から80ms超の)ときは
    // 自動の動きだけを止める(静止パネルへは降りず、最後に描いた3Dの絵を残して押したときだけ描く)。
    // ソフトウェア描画では命令が GPU 側に溜まり、平均は速いまま後から数秒の止まりがまとめて出る(実測)ので、
    // 400ms を超える間隔が2回出たときも同じく止める(1回だけなら GC などの一時的な詰まりとみなす)
    frames += 1;
    if (frames > 5 && now - prevNow > 400) longGaps += 1;
    if (longGaps >= 2) {
      still = true;
      renderer.transmissionResolutionScale = 0.5;
      stop();
      shownNow = rigs.map(() => false);
      setView(current, comparing);
      return;
    }
    if (frames > 5 && frames <= 25) {
      elapsed += now - prevNow;
      if (frames === 25) {
        const avg = elapsed / 20;
        if (avg > 80 || (avg > 32 && degraded)) {
          still = true;
          renderer.transmissionResolutionScale = 0.5;
          stop();
          shownNow = rigs.map(() => false);
          setView(current, comparing);
        } else if (avg > 32) {
          degraded = true;
          // ガラスの透過は、画面と同じ大きさの描画先(4倍MSAA・ミップマップ付き)へもう一度描くので重い。半分の大きさにする
          renderer.transmissionResolutionScale = 0.5;
          dpr = Math.max(1, dpr * 0.6);
          renderer.setPixelRatio(dpr);
          resize();
          renderOnce();
          frames = 0;
          elapsed = 0;
        }
      }
    }
  };

  const start = () => {
    if (raf || !animated()) return;
    last = performance.now();
    raf = requestAnimationFrame(frame);
  };

  const stop = () => {
    if (!raf) return;
    cancelAnimationFrame(raf);
    raf = 0;
  };

  const setView = (index: number, compare: boolean, seq?: number) => {
    if (index < 0 || index >= rigs.length) return;
    if (seq !== undefined) pendingSeq = seq;
    current = index;
    comparing = compare;
    const next = rigs.map((_, i) => shown(i));
    if (animated()) {
      rigs.forEach((rig, i) => {
        if (next[i] && !shownNow[i]) {
          // 新しく出す標本は、置き場所へ直接置いてから登場させる
          const t = slotTarget(i);
          rig.slot.position.x = t.x;
          rig.slot.scale.setScalar(t.s);
          rig.exit.stop();
          rig.group.visible = true;
          rig.enter.reset().play();
          rig.drift.reset().play();
        } else if (!next[i] && shownNow[i]) {
          rig.enter.stop();
          rig.drift.stop();
          rig.exit.reset().play();
        }
      });
    } else {
      // モーション低減時・低速時はタイムラインを使わず、最終状態を直接置いて1枚だけ描く
      rigs.forEach((rig, i) => {
        rig.mixer.stopAllAction();
        const t = slotTarget(i);
        rig.group.visible = next[i];
        rig.group.scale.setScalar(next[i] ? 1 : 0.001);
        rig.group.position.set(0, 0, 0);
        rig.group.rotation.set(0, 0, 0);
        rig.slot.position.x = t.x;
        rig.slot.scale.setScalar(t.s);
      });
      halfW = comparing ? 2.45 : 1.75;
      fit();
    }
    shownNow = next;
    if (!animated()) requestStill();
  };

  const applyMotion = () => {
    if (animated()) {
      start();
    } else {
      stop();
      shownNow = rigs.map(() => false);
      setView(current, comparing);
    }
  };

  const onMotionChange = () => {
    motionOK = !motionQuery.matches;
    if (running) applyMotion();
  };
  motionQuery.addEventListener("change", onMotionChange);

  // --- ポインタ操作(ユーザー起因の回転はモーション低減時も許可=1フレームずつ描く)--
  const onPointerDown = (e: PointerEvent) => {
    if (pointerId !== null) return;
    pointerId = e.pointerId;
    dragging = true;
    lastX = e.clientX;
    lastY = e.clientY;
    canvas.setPointerCapture(e.pointerId);
  };
  const onPointerMove = (e: PointerEvent) => {
    if (!dragging || e.pointerId !== pointerId) return;
    yawTarget += (e.clientX - lastX) * 0.007;
    pitchTarget = Math.max(
      -0.42,
      Math.min(0.42, pitchTarget + (e.clientY - lastY) * 0.005),
    );
    lastX = e.clientX;
    lastY = e.clientY;
    if (!animated()) {
      yaw = yawTarget;
      pitch = pitchTarget;
      applySpin();
      requestStill();
    }
  };
  const onPointerUp = (e: PointerEvent) => {
    if (e.pointerId !== pointerId) return;
    dragging = false;
    pointerId = null;
    if (canvas.hasPointerCapture(e.pointerId))
      canvas.releasePointerCapture(e.pointerId);
  };
  canvas.addEventListener("pointerdown", onPointerDown);
  canvas.addEventListener("pointermove", onPointerMove);
  canvas.addEventListener("pointerup", onPointerUp);
  canvas.addEventListener("pointercancel", onPointerUp);

  const onContextLost = (e: Event) => {
    e.preventDefault();
    stop();
    onFail();
  };
  canvas.addEventListener("webglcontextlost", onContextLost);

  // 大きさを変えると描画バッファが消えるので、同じ処理の中で必ず描き直す
  const ro = new ResizeObserver(() => {
    resize();
    if (initialized) renderOnce();
  });
  ro.observe(host);

  const dispose = () => {
    disposed = true;
    stop();
    ro.disconnect();
    motionQuery.removeEventListener("change", onMotionChange);
    canvas.removeEventListener("pointerdown", onPointerDown);
    canvas.removeEventListener("pointermove", onPointerMove);
    canvas.removeEventListener("pointerup", onPointerUp);
    canvas.removeEventListener("pointercancel", onPointerUp);
    canvas.removeEventListener("webglcontextlost", onContextLost);
    for (const rig of rigs) rig.mixer.stopAllAction();
    for (const g of geometries) g.dispose();
    for (const m of materials) m.dispose();
    for (const t of textures) t.dispose();
    envMap.dispose();
    renderer.dispose();
    renderer.forceContextLoss();
  };

  resize();
  applySpin();

  // シェーダーの事前組み立て: 3標本を並べた状態で compileAsync → 1回描く(ガラスの透過用の
  // 描画先もここで作られる)。canvas はまだ透明なので、この1枚は利用者には見えない。
  rigs.forEach((rig, i) => {
    rig.group.visible = true;
    rig.group.scale.setScalar(1);
    rig.slot.position.x = COMPARE_X[i];
    rig.slot.scale.setScalar(COMPARE_SCALE);
  });
  // compileAsync は KHR_parallel_shader_compile が無い環境では警告を出して同期の compile と同じになるので、
  // 拡張の有無で呼び分ける
  if (renderer.extensions.has("KHR_parallel_shader_compile")) {
    await renderer.compileAsync(scene, camera);
  } else {
    renderer.compile(scene, camera);
  }
  if (isCancelled()) {
    dispose();
    return null;
  }
  renderer.render(scene, camera);
  for (const rig of rigs) {
    rig.group.visible = false;
    rig.group.scale.setScalar(0.001);
  }

  initialized = true;
  setView(current, comparing);
  if (animated()) {
    // 登場の最初の1コマ(スケールほぼ0)ではなく、少し進めた形を最初の1枚にする
    for (const rig of rigs) rig.mixer.update(0.12);
  }
  renderOnce();
  // ソフトウェア描画の環境では、ここから GPU 側で数秒かかることがあり、その間に canvas を見せると
  // 舞台が空白に見える(実測)。描き終わってから見せ、それまでは静止見本を出しておく
  await nextPaint();
  if (isCancelled()) {
    dispose();
    return null;
  }
  // 1枚目は起動時の状態を描いて画面に出たところなので、その番号をここで知らせる
  if (pendingSeq !== null) onViewPainted(pendingSeq);
  pendingSeq = null;
  onFirstFrame();

  return {
    setView,
    setRunning: (next: boolean) => {
      running = next;
      if (next) applyMotion();
      else stop();
    },
    dispose,
  };
}

/**
 * 読み込み前・非対応・切り替えの描画待ちに出す静止見本(CSSだけで3標本の形と質感の手がかりを描く)。
 * ガラスは半透明+背景のぼかしにして、後ろの線が透けて見えるようにする
 */
function StillSpecimen({
  index,
  small = false,
}: {
  index: number;
  small?: boolean;
}) {
  const size = small ? "size-16 sm:size-20" : "size-32 sm:size-36";
  return (
    <span className="relative flex flex-col items-center">
      {index === 0 && (
        <span
          className={`${size} rounded-full bg-[conic-gradient(from_200deg,#fde68a,#d97706_22%,#78350f_40%,#f59e0b_58%,#fef3c7_70%,#b45309_86%,#fde68a)] [mask:radial-gradient(circle,transparent_38%,#000_39%)]`}
        />
      )}
      {index === 1 && (
        <span
          className={`${size} relative rounded-[46%_46%_38%_38%/58%_58%_42%_42%] bg-[radial-gradient(circle_at_34%_28%,#ffffff_0%,#f6f3ee_34%,#d8d0c3_78%,#b9ae9d_100%)] shadow-[inset_-10px_-6px_18px_rgba(34,30,25,0.16)]`}
        >
          <span className="absolute inset-x-[22%] top-[9%] h-[3px] rounded-full bg-amber-600/80" />
        </span>
      )}
      {index === 2 && (
        <span
          className={`${size} rotate-6 rounded-[24%] border border-amber-700/40 bg-[linear-gradient(135deg,rgba(254,243,199,0.55)_0%,rgba(245,158,11,0.45)_45%,rgba(180,83,9,0.6)_100%)] backdrop-blur-[3px] [mask:radial-gradient(circle,transparent_17%,#000_18%)]`}
        />
      )}
      <span
        className={`mt-3 h-2 rounded-full bg-gray-900/15 blur-[5px] ${small ? "w-12" : "w-24"}`}
      />
    </span>
  );
}

export default function ThreeObjectGalleryHero({
  headingTag: Heading = "h2",
}: {
  headingTag?: "h1" | "h2" | "p";
}) {
  const stageRef = useRef<HTMLDivElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fxRef = useRef<HTMLDivElement>(null);
  const sweepRef = useRef<HTMLSpanElement>(null);
  const apiRef = useRef<StudioApi | null>(null);
  // seq は押した切り替えの通し番号。3Dの絵がその番号の状態を画面に出したら paintedSeq が追いつく
  const viewRef = useRef({ index: 0, compare: false, seq: 0 });
  const [live, setLive] = useState(false);
  const [inView, setInView] = useState(false);
  const [pageVisible, setPageVisible] = useState(true);
  const [ready, setReady] = useState(false);
  const [failed, setFailed] = useState(false);
  const [active, setActive] = useState(0);
  const [compare, setCompare] = useState(false);
  const [viewSeq, setViewSeq] = useState(0);
  const [paintedSeq, setPaintedSeq] = useState(0);

  // 起動条件: 画面内 かつ 実寸表示。一覧のカードは親に scale が掛かっているので
  // rect.width(変形後)÷ offsetWidth(レイアウト幅)が 1 未満になり、three を読み込まない。
  useEffect(() => {
    const el = stageRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const fullSize =
      el.offsetWidth > 0 ? rect.width / el.offsetWidth > 0.75 : true;
    const io = new IntersectionObserver(
      ([entry]) => {
        setInView(entry.isIntersecting);
        if (entry.isIntersecting && fullSize) setLive(true);
      },
      { rootMargin: "160px" },
    );
    io.observe(el);
    const onVisibility = () =>
      setPageVisible(document.visibilityState === "visible");
    document.addEventListener("visibilitychange", onVisibility);
    return () => {
      io.disconnect();
      document.removeEventListener("visibilitychange", onVisibility);
    };
  }, []);

  // three 本体はここで初めてネットワークに出る(別チャンク・詳細ページのみ)
  useEffect(() => {
    if (!live) return;
    const canvas = canvasRef.current;
    const host = stageRef.current;
    if (!canvas || !host) return;

    let cancelled = false;
    // 対応可否の判定 → 動的import → 起動、までを1本の非同期手続きにまとめる
    // (effect の本体から setState を直に呼ばない)
    const boot = async () => {
      // 先に対応可否を確かめる(非対応なら重いライブラリを取りに行く意味がない)。
      // 確かめに使った文脈をそのまま three に渡す。確認用の canvas を別に作ると文脈を2回作ることになり、
      // ソフトウェア描画の環境ではその1回だけで2秒ほど止まる(実測)
      const gl = canvas.getContext("webgl2", {
        antialias: true,
        alpha: true,
        powerPreference: "low-power",
      });
      if (!gl) {
        setFailed(true);
        return;
      }

      const T = await import("three");
      if (cancelled) return;
      const first = viewRef.current;
      const api = await createStudio(T, {
        canvas,
        context: gl,
        host,
        // 起動を待つ間に押された切り替えも引き継ぐ
        index: first.index,
        compare: first.compare,
        seq: first.seq,
        fontFamily: montserrat.style.fontFamily,
        isCancelled: () => cancelled,
        onFirstFrame: () => setReady(true),
        onViewPainted: (seq) => setPaintedSeq(seq),
        onFail: () => setFailed(true),
      });
      if (cancelled) {
        api?.dispose();
        return;
      }
      apiRef.current = api;
      // シェーダーの組み立て中に押された切り替えを引き継ぐ
      const now = viewRef.current;
      if (api && now.seq !== first.seq)
        api.setView(now.index, now.compare, now.seq);
    };
    boot().catch(() => {
      if (!cancelled) setFailed(true);
    });

    return () => {
      cancelled = true;
      apiRef.current?.dispose();
      apiRef.current = null;
    };
  }, [live]);

  useEffect(() => {
    apiRef.current?.setRunning(inView && pageVisible && !failed);
  }, [inView, pageVisible, failed, ready]);

  // 押した直後の合図は2つ: 舞台全体が0.22秒で小さく沈んで戻る(切り替えの始まりと終わり)と、
  // 舞台の下端を走るアンバーの線。ボタンの色・下線・舞台の名前は同じ描画で変わる
  const choose = (index: number, nextCompare: boolean) => {
    const prev = viewRef.current;
    if (index === prev.index && nextCompare === prev.compare) return;
    const seq = prev.seq + 1;
    viewRef.current = { index, compare: nextCompare, seq };
    setActive(index);
    setCompare(nextCompare);
    setViewSeq(seq);
    apiRef.current?.setView(index, nextCompare, seq);
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    fxRef.current?.animate(
      [
        { transform: "scale(1)", opacity: 1 },
        { transform: "scale(0.94)", opacity: 0.72, offset: 0.45 },
        { transform: "scale(1)", opacity: 1 },
      ],
      { duration: 220, easing: "cubic-bezier(0.3, 0, 0.2, 1)" },
    );
    sweepRef.current?.animate(
      [
        { transform: "scaleX(0)", opacity: 1 },
        { transform: "scaleX(1)", opacity: 1, offset: 0.7 },
        { transform: "scaleX(1)", opacity: 0 },
      ],
      { duration: 420, easing: "cubic-bezier(0.2, 0.7, 0.2, 1)" },
    );
  };

  const specimen = SPECIMENS[active];
  const on3d = ready && !failed;
  // 押した状態の3Dがまだ画面に出ていない(描画の遅い端末)。0.3秒待っても出なければ同じ状態の静止見本を重ねる
  const stale = on3d && paintedSeq !== viewSeq;

  return (
    <section className="w-full max-w-4xl overflow-hidden rounded-2xl border border-gray-200 bg-white">
      <div className="flex items-center justify-between gap-4 border-b border-gray-200 px-5 py-3 sm:px-8 sm:py-4">
        <p className="flex items-center gap-2 text-[11px] font-bold tracking-[0.16em] whitespace-nowrap text-gray-900">
          <span
            className="inline-block size-1 bg-amber-600"
            aria-hidden="true"
          />
          3D OBJECT STUDY
        </p>
        {/* 狭幅では2本並べると入らないので右は畳む(overflow-hidden で切れるのを見せない) */}
        <p className="hidden font-mono text-[10px] font-bold tracking-[0.18em] whitespace-nowrap text-gray-400 uppercase sm:block">
          PBR / IBL / SHADOW
        </p>
      </div>

      {/* 狭い幅は 舞台 → 切り替え → 文言 の順(最初の画面に立体と3つの切り替えを入れる)。
          md 以上は 文言|舞台 の2列で、切り替えは舞台の上端に重ねる(押してもページが動かない位置に置く)。
          下に敷く台帳は材質パラメータの表示だけ */}
      <div className="relative grid sm:grid-cols-[1fr_1fr]">
        <div className="order-3 border-t border-gray-200 px-5 pt-6 pb-7 sm:order-1 sm:border-t-0 sm:px-8 sm:py-11 md:pt-12">
          <p className="text-[11px] font-bold tracking-[0.25em] text-amber-600 uppercase">
            Real-time 3D
          </p>
          <Heading
            className={`${montserrat.className} mt-3 text-[clamp(1.6rem,4.6vw,2.4rem)] leading-[1.12] font-bold tracking-tight text-gray-900 sm:mt-4`}
          >
            Depth,
            <br />
            on demand.
          </Heading>
          <p className="mt-4 max-w-sm text-[13.5px] leading-[1.9] font-medium tracking-[0.03em] text-gray-600 sm:mt-5">
            モデルデータなしで、金属・陶磁・ガラスの質感をコードだけで描くヒーローです。光と影、動きまで案件のトーンに合わせて作れます。
          </p>
          <a
            href="#contact"
            className="group mt-5 inline-flex items-center gap-2 text-[13px] font-bold tracking-[0.06em] text-gray-900 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-amber-600 sm:mt-7"
          >
            <span className="relative py-1">
              3D演出を相談する
              <span
                className="absolute inset-x-0 bottom-0 h-px origin-left scale-x-100 bg-gray-900 transition-transform duration-500 ease-out group-hover:scale-x-0 motion-reduce:transition-none"
                aria-hidden="true"
              />
              <span
                className="absolute inset-x-0 bottom-0 h-px origin-right scale-x-0 bg-amber-600 transition-transform delay-150 duration-500 ease-out group-hover:origin-left group-hover:scale-x-100 motion-reduce:transition-none"
                aria-hidden="true"
              />
            </span>
            <span
              className="transition-transform duration-300 group-hover:translate-x-1 motion-reduce:transition-none"
              aria-hidden="true"
            >
              →
            </span>
          </a>
        </div>

        <div
          ref={stageRef}
          data-view={stale ? "pending" : "painted"}
          className="relative order-1 h-[17rem] overflow-hidden bg-[linear-gradient(rgba(34,30,25,0.05)_1px,transparent_1px),linear-gradient(90deg,rgba(34,30,25,0.05)_1px,transparent_1px)] bg-[size:14px_14px] sm:order-2 sm:h-auto sm:min-h-[22rem] sm:border-l sm:border-gray-200"
          style={{ backgroundColor: PAPER }}
        >
          {/* 切り替えの演出(縮んで戻る)は3Dと静止見本をまとめて動かす */}
          <div ref={fxRef} className="absolute inset-0">
            <canvas
              ref={canvasRef}
              aria-hidden="true"
              className={`absolute inset-0 block size-full touch-pan-y transition-opacity duration-300 motion-reduce:transition-none ${
                on3d ? "opacity-100" : "opacity-0"
              }`}
            />

            {/* 静止見本(読み込み中・WebGL非対応・コンテキストロスト・切り替えの描画待ち)。
                3Dの絵より上に重ね、紙の地と背景板の線も描いて「いま選んでいる状態」だけを見せる */}
            <div
              className={`pointer-events-none absolute inset-0 flex items-center justify-center gap-5 bg-[linear-gradient(rgba(34,30,25,0.05)_1px,transparent_1px),linear-gradient(90deg,rgba(34,30,25,0.05)_1px,transparent_1px)] bg-[size:14px_14px] pb-6 transition-opacity motion-reduce:transition-none ${
                !on3d
                  ? "opacity-100 duration-300"
                  : stale
                    ? "opacity-100 delay-300 duration-150"
                    : "opacity-0 delay-150 duration-300"
              }`}
              style={{ backgroundColor: PAPER }}
              aria-hidden="true"
            >
              <span className="absolute inset-x-[14%] top-1/2 -mt-3 flex flex-col gap-6">
                <span className="h-px bg-gray-900/45" />
                <span className="h-px bg-gray-900/45" />
                <span className="-mt-[13px] h-0.5 bg-amber-600/80" />
                <span className="h-px bg-gray-900/45" />
              </span>
              <span
                className={`${montserrat.className} absolute inset-x-0 top-1/2 -mt-10 text-center text-[64px] leading-none font-bold text-gray-900/10`}
              >
                DEPTH
              </span>
              {compare ? (
                SPECIMENS.map((s, i) => (
                  <StillSpecimen key={s.no} index={i} small />
                ))
              ) : (
                <StillSpecimen index={active} />
              )}
            </div>
          </div>

          {/* 左上に「並べて比べる」。下端: 左にいま見ている標本の名前、右に操作ヒント */}
          <button
            type="button"
            aria-pressed={compare}
            data-action="compare"
            onClick={() => choose(active, !compare)}
            className={`absolute top-3 left-3 inline-flex min-h-9 items-center gap-1.5 rounded-full border px-3 font-mono text-[10px] font-bold tracking-[0.12em] whitespace-nowrap uppercase transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-amber-600 motion-reduce:transition-none ${
              compare
                ? "border-gray-900 bg-gray-900 text-white"
                : "border-gray-300 bg-white/85 text-gray-700 hover:border-gray-900"
            }`}
          >
            <span className="flex gap-0.5" aria-hidden="true">
              <span
                className={`size-1.5 rounded-full ${compare ? "bg-amber-400" : "bg-amber-600"}`}
              />
              <span
                className={`size-1.5 rounded-full ${compare ? "bg-white" : "bg-gray-300"}`}
              />
              <span className="size-1.5 rounded-full bg-amber-200" />
            </span>
            {compare ? "1つに戻す" : "3つを並べる"}
          </button>
          <p
            className="pointer-events-none absolute inset-x-4 bottom-3 flex items-baseline gap-2 whitespace-nowrap"
            aria-live="polite"
          >
            <span className="font-mono text-[10px] font-bold tracking-[0.16em] text-amber-600">
              {compare ? "01–03" : specimen.no}
            </span>
            <span className="text-[12px] font-bold tracking-[0.04em] text-gray-900">
              {compare ? "同じ光・同じ画角で比較" : specimen.ja}
            </span>
            <span
              className={`ml-auto font-mono text-[9.5px] tracking-[0.14em] text-gray-500 uppercase transition-opacity duration-500 motion-reduce:transition-none ${
                on3d ? "opacity-100" : "opacity-0"
              }`}
            >
              <span className="[@media(pointer:coarse)]:hidden">Drag</span>
              <span className="hidden [@media(pointer:coarse)]:inline">
                Swipe
              </span>
            </span>
          </p>
          <span
            ref={sweepRef}
            className="pointer-events-none absolute inset-x-0 bottom-0 h-0.5 origin-left scale-x-0 bg-amber-600"
            aria-hidden="true"
          />
        </div>

        {/* 切り替え(canvasは装飾なので、内容はDOM側が正)。md 未満は舞台の下の3等分のタブ、
            md 以上は舞台の右上に重ねた3つのボタン(グリッドの右列=舞台の上端に絶対配置) */}
        <ol className="order-2 grid grid-cols-3 border-t border-gray-200 sm:order-3 sm:col-span-2 md:absolute md:top-3 md:right-3 md:z-10 md:flex md:gap-0.5 md:rounded-full md:border md:border-gray-300 md:bg-white/85 md:p-0.5">
          {SPECIMENS.map((item, i) => {
            const on = !compare && i === active;
            return (
              <li
                key={item.no}
                className="border-gray-200 not-first:border-l md:not-first:border-l-0"
              >
                <button
                  type="button"
                  aria-pressed={on}
                  aria-label={item.ja}
                  data-specimen={item.no}
                  onClick={() => choose(i, false)}
                  className={`group relative flex h-full w-full flex-col items-start gap-0.5 px-4 py-3 text-left transition-colors focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-amber-600 motion-reduce:transition-none md:min-h-8 md:flex-row md:items-center md:rounded-full md:px-2.5 md:py-0 ${
                    on
                      ? "bg-amber-50/60 md:bg-gray-900"
                      : "md:hover:bg-gray-100"
                  }`}
                >
                  {/* 狭い幅の選択中の印(上端のアンバーの線) */}
                  <span
                    className={`absolute inset-x-0 top-0 h-0.5 origin-left bg-amber-600 transition-transform duration-200 ease-out md:hidden motion-reduce:transition-none ${
                      on ? "scale-x-100" : "scale-x-0"
                    }`}
                    aria-hidden="true"
                  />
                  <span
                    className={`font-mono text-[11px] font-bold tracking-[0.1em] md:hidden ${
                      on
                        ? "text-amber-600"
                        : "text-gray-400 group-hover:text-amber-600"
                    }`}
                  >
                    {item.no}
                  </span>
                  <span
                    className={`text-[13px] font-bold tracking-[0.04em] whitespace-nowrap md:text-[11px] ${
                      on
                        ? "text-gray-900 md:text-white"
                        : "text-gray-500 group-hover:text-gray-900"
                    }`}
                  >
                    {item.short}
                  </span>
                  <span
                    className={`font-mono text-[9.5px] tracking-[0.1em] whitespace-nowrap uppercase md:hidden ${
                      on ? "text-amber-700" : "text-gray-400"
                    }`}
                  >
                    {item.en.split(" / ")[1]}
                  </span>
                </button>
              </li>
            );
          })}
        </ol>

        {/* 標本台帳(md 以上)。いま舞台に出ている標本の行がアンバーになる(並べているときは3行とも) */}
        <ol className="hidden border-t border-gray-200 px-8 md:order-4 md:col-span-2 md:block">
          {SPECIMENS.map((item, i) => {
            const on = compare || i === active;
            return (
              <li
                key={item.no}
                className="grid grid-cols-[2.25rem_1fr_auto] items-baseline gap-x-4 border-b border-gray-200 py-3.5 last:border-b-0"
              >
                <span
                  className={`font-mono text-[11px] font-bold tracking-[0.1em] ${on ? "text-amber-600" : "text-gray-400"}`}
                >
                  {item.no}
                </span>
                <span className="flex items-center gap-2">
                  <span
                    className={`inline-block h-0.5 w-5 shrink-0 origin-left bg-amber-600 transition-transform duration-200 ease-out motion-reduce:transition-none ${
                      on ? "scale-x-100" : "scale-x-0"
                    }`}
                    aria-hidden="true"
                  />
                  <span
                    className={`text-[13px] font-bold tracking-[0.04em] ${on ? "text-gray-900" : "text-gray-500"}`}
                  >
                    {item.ja}
                  </span>
                </span>
                <span
                  className={`text-right font-mono text-[10px] tracking-[0.1em] whitespace-nowrap uppercase ${
                    on ? "text-amber-700" : "text-gray-400"
                  }`}
                >
                  {item.spec}
                </span>
              </li>
            );
          })}
        </ol>
      </div>

      <p className="border-t border-gray-200 px-5 py-3.5 font-mono text-[10px] leading-[1.7] tracking-[0.08em] text-gray-400 sm:px-8">
        three.js
        は3Dを実際に表示する画面でのみ動的読み込み(別チャンク)。縮小プレビュー・非対応環境・描画が追いつかない間は同じ状態の静止見本を表示します。
      </p>
    </section>
  );
}

shadcn CLI でプロジェクトに追加

npx shadcn@latest add https://designs.first-ch.com/r/three-object-gallery-hero.json