Implementou DevKit isolado
X-Lovable-Edit-ID: edt-5cd66b02-8a4a-489b-9895-4d1636083a15 Co-authored-by: Reifonas <211114984+Reifonas@users.noreply.github.com>
This commit is contained in:
+89
-56
@@ -1,78 +1,111 @@
|
|||||||
## Plano: Grab nativo dos controles Touch Plus (Quest 3) para "vestir" a peça virtual
|
## Objetivo
|
||||||
|
|
||||||
Objetivo: permitir que o usuário **agarre a peça virtual com o grip** do Touch Plus e a movimente em 6 graus de liberdade junto com a mão (translação + rotação simultâneas), e use **as duas mãos juntas** para girar/escalar com naturalidade. Joystick atual continua existindo como ajuste fino.
|
Construir uma **"giga de teste"** (DevKit) que vista o app com simulação completa de XR + instrumentação, permitindo:
|
||||||
|
|
||||||
### 1. Camada de input nova: `useControllerGrab`
|
1. **Você (sem Quest):** validar quase 100% do fluxo direto no navegador, incluindo grab, posicionamento e medição.
|
||||||
|
2. **Testador (com Quest):** receber um build com painel de diagnóstico visível e log persistente, devolvendo feedback objetivo.
|
||||||
|
3. **Remoção limpa:** quando o app estiver maduro, apagar 1 pasta + remover 3 imports + apagar 1 flag → app puro restaurado.
|
||||||
|
|
||||||
Novo hook em `src/hooks/useControllerGrab.ts` que encapsula tudo que falta hoje:
|
## Princípios de isolamento
|
||||||
|
|
||||||
- Lê `session.inputSources` a cada frame e identifica os `XRInputSource` "left" e "right".
|
- Todo código do DevKit vive em **`src/devkit/`** (pasta nova). Nada de código de simulação espalhado pelo app.
|
||||||
- Para cada controle, expõe:
|
- Ativação por **flag única** `?devkit=1` na URL **OU** `localStorage.setItem('devkit', '1')`. Sem flag → app roda exatamente como hoje.
|
||||||
- `gripValue` (0..1, analógico, vindo de `gamepad.buttons[2].value`).
|
- Componentes do DevKit são montados condicionalmente em **3 pontos de injeção** apenas (todos em `XRSession.tsx`). Esses pontos ficam marcados com comentário `// DEVKIT: remove this block` para facilitar a limpeza futura.
|
||||||
- `triggerValue` (0..1, `buttons[1].value`).
|
- Zero alteração de lógica de negócio. Tudo que o DevKit faz é **observar** (logger), **simular** (fake inputs) ou **adicionar UI extra** (painel).
|
||||||
- `isGrabbing` (boolean com histerese: começa em `value > 0.7`, termina em `< 0.3` — evita flicker).
|
|
||||||
- `gripPose`: matrix4 da pose do `inputSource.gripSpace` no `referenceSpace` atual, atualizada por frame via `XRFrame.getPose()`.
|
|
||||||
- Também escuta os eventos nativos `squeezestart` / `squeezeend` da `XRSession` como fallback caso o gamepad não exponha valor analógico.
|
|
||||||
|
|
||||||
### 2. Componente `XRGrabbable` em volta da peça
|
## Componentes do DevKit
|
||||||
|
|
||||||
Novo arquivo `src/components/three/XRGrabbable.tsx`. Wrappa o `<XRModel/>` em um `<group>` controlado e implementa as três modalidades de grab:
|
### 1. `devkit/DevKitFlag.ts` — detector de modo
|
||||||
|
Hook `useDevKit()` retorna `boolean`. Lê `URLSearchParams` + `localStorage`. Se `true`, ativa todo o resto.
|
||||||
|
|
||||||
- **One-hand grab**: quando `isGrabbing` de uma mão dispara, calcula matrix relativa `M_offset = gripPose⁻¹ · modelPose`. A cada frame, enquanto segura, faz `modelPose = gripPose · M_offset`. Resultado: a peça vira "extensão da mão", com translação + rotação simultâneas.
|
### 2. `devkit/SimXRSession.tsx` — modo "Faux-XR" pra desktop
|
||||||
- **Two-hand grab** (quando ambas as mãos estão segurando):
|
**Resolve seu problema #1:** validar tudo sem headset.
|
||||||
- Pivô = ponto médio entre os dois `gripPose`.
|
|
||||||
- Rotação = orientação do vetor entre as duas mãos (mantém o cabo da viga sempre alinhado com o eixo entre os punhos).
|
|
||||||
- Escala = razão entre a distância atual e a distância no momento em que a 2ª mão agarrou (com clamp 0.1× a 10×). **Opcional**: pode ser desabilitada na HUD para usos onde a escala 1:1 é obrigatória (caso "vestir" sobre peça real).
|
|
||||||
- Ao soltar (`isGrabbing` cai), grava a pose final em `useModelStore.fineTuning` (decompõe em `posX/Y/Z`, `rotX/Y/Z`, e `scale` se two-hand estiver ativo) — assim o estado fica consistente com o joystick e os controles do HUD.
|
|
||||||
|
|
||||||
### 3. Joystick continua, agora modulado pelo grip analógico
|
Quando ativado (botão "🧪 Simular XR" no header, só aparece com `?devkit=1`):
|
||||||
|
- Não chama `store.enterAR()` (que falha sem HTTPS/headset compatível).
|
||||||
|
- Em vez disso, força `inXR=true` num estado paralelo `simXR`.
|
||||||
|
- Renderiza a árvore `XRGrabbable + XRModel` **sem** `XRHitTestPlacement` (auto-posiciona em `[0,0,-1.5]`).
|
||||||
|
- Substitui leitura de `session.inputSources` por uma fonte **fake** (ver #3).
|
||||||
|
- Câmera fica controlável por `OrbitControls` (você navega como quiser).
|
||||||
|
|
||||||
Em `ControllerFineTuning` (dentro de `XRSession.tsx`):
|
### 3. `devkit/FakeControllers.tsx` — controles virtuais com mouse/teclado
|
||||||
|
**Resolve seu problema #2:** testar grab sem Touch Plus.
|
||||||
|
|
||||||
- Mantém o mapeamento atual mas **só ativa quando NENHUM grip está apertado** (para não brigar com o grab).
|
- Desenha 2 esferas coloridas (L=azul, R=vermelho) na cena, posicionáveis por **arrastar com mouse**.
|
||||||
- `posStep` e `rotStep` ganham multiplicador derivado de `triggerValue` da mesma mão: trigger leve = passo fino (×0.3), trigger forte = passo rápido (×3). Resolve a queixa de "movimento mecânico".
|
- Atalhos teclado:
|
||||||
- Mapeamento corrigido para o padrão VR (já discutido):
|
- `Q` / `W` → segurar grip esquerdo / direito (analógico simulado em 1.0)
|
||||||
- Esquerdo: X horizontal / Z vertical (frente-trás).
|
- `A` / `S` → segurar trigger esquerdo / direito
|
||||||
- Direito: rotY horizontal / Y altura vertical.
|
- `Setas` → mover controle ativo
|
||||||
- Adiciona aceleração proporcional (curva quadrática no input do thumbstick) e deadzone de 0.15.
|
- `Shift + Setas` → mover controle no eixo Z
|
||||||
|
- Expõe um `FakeInputProvider` (Context) que `useControllerGrab` consome **quando em modo DevKit**. Sem DevKit, hook continua lendo `session.inputSources` real.
|
||||||
|
- **Mudança mínima em `useControllerGrab.ts`:** uma linha checando `if (devkit) return useFakeInputs()`. Removível.
|
||||||
|
|
||||||
### 4. Escala no store
|
### 4. `devkit/DevPanel.tsx` — painel de diagnóstico flutuante
|
||||||
|
Painel HTML overlay (canto direito), só visível com `?devkit=1`:
|
||||||
|
- **Aba "Inputs":** valores ao vivo de cada controle (real ou fake) — grip, trigger, axes, hasPose
|
||||||
|
- **Aba "Cena":** posição/rotação/escala do grupo grabável, contagem de meshes, bbox
|
||||||
|
- **Aba "XR":** `session?.mode`, hit-test ativo, planos detectados (count + labels), FPS
|
||||||
|
- **Aba "Logs":** últimos 100 console.logs com timestamp, filtro por tag (`[XR]`, `[grab]`, `[HitTest]`)
|
||||||
|
- Botão **"Exportar relatório"** → baixa JSON com snapshot atual + screenshot do canvas. **Você pede pro testador clicar isso e te enviar o arquivo.**
|
||||||
|
|
||||||
`src/stores/useModelStore.ts`: adicionar `scale: number` ao `FineTuning` (default 1). `XRModel` e `ModelViewer` aplicam `scale={[s,s,s]}` no `<group>`.
|
### 5. `devkit/XRDevHud.tsx` — HUD in-world expandido (substitui o `XRDebugHud` atual quando ativo)
|
||||||
|
Painel 3D maior, ancorado no pulso esquerdo (não na câmera, pra não atrapalhar). Mostra mesmas infos da aba "Inputs" + "XR" do DevPanel. Visível **dentro do headset**, essencial pro testador.
|
||||||
|
|
||||||
### 5. UI: feedback visual e ajuda
|
### 6. `devkit/SmokeTest.tsx` — roteiro automático
|
||||||
|
Rota nova `/devkit/smoke` (só roteada com `?devkit=1`):
|
||||||
|
- Sequência scriptada: carrega demo → simula grip esquerdo → move 50cm → solta → mede 2 pontos → screenshot → checklist.
|
||||||
|
- Cada passo mostra ✅/❌ + tempo.
|
||||||
|
- Você roda antes de mandar build pro testador.
|
||||||
|
|
||||||
- `XRGrabbable` mostra um halo sutil ao redor da peça quando `gripValue > 0.1` em qualquer mão (intensidade proporcional → o usuário sente a pressão analógica).
|
### 7. `devkit/RecordSession.tsx` — gravador de "macros"
|
||||||
- `src/components/XRHud.tsx`: na seção de Ajuda (?), adicionar bloco "Agarrar a peça":
|
Botão "Gravar" no DevPanel: captura por 30s todos inputs + posições da cena num JSON. Botão "Reproduzir": replay do macro. Útil pra reproduzir um bug que o testador relatou ("clico aqui, viro assim, peça desaparece").
|
||||||
- "Aperte o grip lateral de um controle perto da peça → ela vira extensão da sua mão."
|
|
||||||
- "Agarre com os dois grips ao mesmo tempo → rotacione girando os punhos / aproxime-afaste para escalar."
|
|
||||||
- "Solte o grip para fixar."
|
|
||||||
- "Trigger modula a velocidade do joystick (leve = fino, forte = rápido)."
|
|
||||||
- Adicionar toggle "Permitir escala (two-hand)" — default OFF para preservar 1:1.
|
|
||||||
|
|
||||||
### 6. Integração e ordem de aplicação
|
## Pontos de injeção em `XRSession.tsx`
|
||||||
|
|
||||||
No `XRSession.tsx`, a árvore vira:
|
Apenas 3 blocos curtos, todos cercados por `{devkit && <... />}`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// DEVKIT: remove this block
|
||||||
|
{devkit && <SimXRButton onActivate={setSimXR} />}
|
||||||
|
|
||||||
|
// DEVKIT: remove this block
|
||||||
|
{devkit && simXR && <FakeControllers />}
|
||||||
|
|
||||||
|
// DEVKIT: remove this block
|
||||||
|
{devkit && <DevPanel />}
|
||||||
```
|
```
|
||||||
<XRHitTestPlacement> (posicionamento inicial)
|
|
||||||
<XRGrabbable> (grab 6DOF + two-hand)
|
E uma linha em `useControllerGrab.ts`:
|
||||||
<XRModel/>
|
```ts
|
||||||
|
// DEVKIT: remove this conditional
|
||||||
|
if (typeof window !== 'undefined' && useDevKitFake()) return fakeRef;
|
||||||
```
|
```
|
||||||
Hit-test só atua enquanto `placementMode = true`. Quando o usuário agarra pela primeira vez, `placementMode` é desligado automaticamente.
|
|
||||||
|
|
||||||
### Detalhes técnicos
|
## Como remover o DevKit no futuro (1 minuto)
|
||||||
|
|
||||||
- Tudo via WebXR Gamepad API + `XRFrame.getPose(gripSpace, referenceSpace)`. Sem dependências novas.
|
1. `rm -rf src/devkit/`
|
||||||
- Histerese do grip evita perder o grab por tremor de mão.
|
2. Em `XRSession.tsx`: deletar 3 blocos marcados `// DEVKIT:` + import.
|
||||||
- Decomposição de matrix usa `THREE.Matrix4.decompose()` para gravar de volta no store sem perder rotação composta.
|
3. Em `useControllerGrab.ts`: deletar linha marcada `// DEVKIT:`.
|
||||||
- Plane snapping continua ativo durante o grab (snap acontece no `onRelease`, não a cada frame, para não travar o movimento).
|
4. Pronto — app puro, zero resíduo.
|
||||||
- Logs `[XR][grab]` para diagnóstico (start/end, qual mão, valor analógico).
|
|
||||||
|
|
||||||
### Arquivos afetados
|
## Entregas desta primeira leva (priorizadas)
|
||||||
|
|
||||||
- **Novo**: `src/hooks/useControllerGrab.ts`
|
Pra não fazer tudo de uma vez, **proponho entregar nesta ordem**, validando cada etapa antes da próxima:
|
||||||
- **Novo**: `src/components/three/XRGrabbable.tsx`
|
|
||||||
- **Editado**: `src/pages/XRSession.tsx` — envolver modelo, ajustar `ControllerFineTuning` (mapeamento + modulação por trigger + bypass quando grip ativo)
|
**Fase 1 (essencial — destrava você hoje):**
|
||||||
- **Editado**: `src/stores/useModelStore.ts` — campo `scale`
|
- DevKitFlag + SimXRSession + FakeControllers + DevPanel (aba Inputs + Logs)
|
||||||
- **Editado**: `src/components/three/ModelViewer.tsx` — aplicar `scale`
|
|
||||||
- **Editado**: `src/components/XRHud.tsx` — toggle "permitir escala", ajuda nova
|
**Fase 2 (essencial — instrumenta o testador):**
|
||||||
|
- XRDevHud expandido + DevPanel aba Cena/XR + Exportar relatório
|
||||||
|
|
||||||
|
**Fase 3 (qualidade de vida):**
|
||||||
|
- SmokeTest + RecordSession
|
||||||
|
|
||||||
|
Posso entregar a **Fase 1 inteira** agora numa única leva, e as fases 2 e 3 sob demanda quando você validar que a 1 te serve. Cabe?
|
||||||
|
|
||||||
|
## Detalhes técnicos
|
||||||
|
|
||||||
|
- **Sem novas dependências.** Tudo com Three.js, R3F, Zustand já presentes.
|
||||||
|
- **TypeScript rigoroso.** Tipos compartilhados entre real e fake (mesma interface `ControllerGrabSnapshot`).
|
||||||
|
- **Zero impacto em produção:** sem flag, bundle do DevKit nem é importado se usarmos `React.lazy()` na entrada.
|
||||||
|
- **Hot-swappable:** ligar/desligar o DevKit não recarrega a página (estado da cena preservado).
|
||||||
|
|||||||
@@ -0,0 +1,166 @@
|
|||||||
|
/**
|
||||||
|
* DEVKIT — HTML overlay panel with diagnostics.
|
||||||
|
*
|
||||||
|
* Tabs:
|
||||||
|
* - Inputs: live grip/trigger/pose values for both controllers (real or fake)
|
||||||
|
* - Logs: captures last 100 console.log/warn/error entries with filter
|
||||||
|
*
|
||||||
|
* Always visible when ?devkit=1, top-right corner.
|
||||||
|
*/
|
||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { fakeInput, isFakeActive } from './fakeInputStore';
|
||||||
|
|
||||||
|
interface LogEntry {
|
||||||
|
ts: number;
|
||||||
|
level: 'log' | 'warn' | 'error';
|
||||||
|
msg: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const logBuffer: LogEntry[] = [];
|
||||||
|
let installed = false;
|
||||||
|
|
||||||
|
function installLogger() {
|
||||||
|
if (installed) return;
|
||||||
|
installed = true;
|
||||||
|
(['log', 'warn', 'error'] as const).forEach((level) => {
|
||||||
|
const orig = console[level].bind(console);
|
||||||
|
console[level] = (...args: unknown[]) => {
|
||||||
|
try {
|
||||||
|
const msg = args.map((a) => {
|
||||||
|
if (typeof a === 'string') return a;
|
||||||
|
try { return JSON.stringify(a); } catch { return String(a); }
|
||||||
|
}).join(' ');
|
||||||
|
logBuffer.push({ ts: Date.now(), level, msg });
|
||||||
|
if (logBuffer.length > 200) logBuffer.shift();
|
||||||
|
} catch { /* noop */ }
|
||||||
|
orig(...args);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
type Tab = 'inputs' | 'logs';
|
||||||
|
|
||||||
|
interface DevPanelProps {
|
||||||
|
simXR: boolean;
|
||||||
|
onToggleSimXR: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DevPanel({ simXR, onToggleSimXR }: DevPanelProps) {
|
||||||
|
const [tab, setTab] = useState<Tab>('inputs');
|
||||||
|
const [collapsed, setCollapsed] = useState(false);
|
||||||
|
const [, tick] = useState(0);
|
||||||
|
const [logFilter, setLogFilter] = useState('');
|
||||||
|
const rafRef = useRef<number | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => { installLogger(); }, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let last = 0;
|
||||||
|
const loop = (t: number) => {
|
||||||
|
if (t - last > 150) { tick((n) => n + 1); last = t; }
|
||||||
|
rafRef.current = requestAnimationFrame(loop);
|
||||||
|
};
|
||||||
|
rafRef.current = requestAnimationFrame(loop);
|
||||||
|
return () => { if (rafRef.current) cancelAnimationFrame(rafRef.current); };
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (collapsed) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onClick={() => setCollapsed(false)}
|
||||||
|
className="fixed top-20 right-2 z-50 rounded bg-black/85 px-2 py-1 font-mono text-[10px] text-green-400 border border-green-500/40 hover:bg-black"
|
||||||
|
>
|
||||||
|
🧪 DevKit
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed top-20 right-2 z-50 w-72 rounded-lg border border-green-500/40 bg-black/90 font-mono text-[10px] text-green-300 shadow-2xl backdrop-blur">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between border-b border-green-500/30 px-2 py-1.5">
|
||||||
|
<span className="font-bold text-green-400">🧪 DEVKIT</span>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<button
|
||||||
|
onClick={onToggleSimXR}
|
||||||
|
className={`rounded px-1.5 py-0.5 text-[9px] ${simXR ? 'bg-green-500 text-black' : 'border border-green-500/40 text-green-300 hover:bg-green-500/20'}`}
|
||||||
|
>
|
||||||
|
{simXR ? 'SIM ON' : 'Simular XR'}
|
||||||
|
</button>
|
||||||
|
<button onClick={() => setCollapsed(true)} className="px-1 hover:text-white">✕</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div className="flex border-b border-green-500/20">
|
||||||
|
{(['inputs', 'logs'] as Tab[]).map((t) => (
|
||||||
|
<button
|
||||||
|
key={t}
|
||||||
|
onClick={() => setTab(t)}
|
||||||
|
className={`flex-1 px-2 py-1 text-[10px] uppercase ${tab === t ? 'bg-green-500/20 text-green-200' : 'text-green-500/70 hover:text-green-300'}`}
|
||||||
|
>
|
||||||
|
{t}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Content */}
|
||||||
|
<div className="max-h-[55vh] overflow-y-auto p-2">
|
||||||
|
{tab === 'inputs' && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="text-green-500/70">
|
||||||
|
fake: {isFakeActive() ? 'ATIVO' : 'inativo'}
|
||||||
|
</div>
|
||||||
|
{(['left', 'right'] as const).map((h) => {
|
||||||
|
const s = fakeInput[h];
|
||||||
|
const grabbing = s.gripValue > 0.7;
|
||||||
|
const p = [s.gripWorld.elements[12], s.gripWorld.elements[13], s.gripWorld.elements[14]];
|
||||||
|
return (
|
||||||
|
<div key={h} className="rounded border border-green-500/20 p-1.5">
|
||||||
|
<div className={`font-bold ${grabbing ? 'text-yellow-300' : 'text-green-300'}`}>
|
||||||
|
{h.toUpperCase()} {grabbing && '✊ GRAB'}
|
||||||
|
</div>
|
||||||
|
<div>grip: {s.gripValue.toFixed(2)} trg: {s.triggerValue.toFixed(2)}</div>
|
||||||
|
<div>pose: {p.map((v) => v.toFixed(2)).join(', ')}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<div className="border-t border-green-500/20 pt-2 text-green-500/70">
|
||||||
|
<div className="font-bold text-green-400 mb-1">Atalhos teclado</div>
|
||||||
|
<div>Q/W = grip L/R · A/S = trigger L/R</div>
|
||||||
|
<div>1/2 = ativar mão · setas = mover</div>
|
||||||
|
<div>Shift+↑/↓ = Z (frente/trás) · R = reset</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{tab === 'logs' && (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<input
|
||||||
|
value={logFilter}
|
||||||
|
onChange={(e) => setLogFilter(e.target.value)}
|
||||||
|
placeholder="filtro… (ex: [XR])"
|
||||||
|
className="w-full rounded border border-green-500/30 bg-black/60 px-1 py-0.5 text-green-300"
|
||||||
|
/>
|
||||||
|
<div className="space-y-0.5">
|
||||||
|
{logBuffer
|
||||||
|
.filter((l) => !logFilter || l.msg.toLowerCase().includes(logFilter.toLowerCase()))
|
||||||
|
.slice(-80)
|
||||||
|
.reverse()
|
||||||
|
.map((l, i) => (
|
||||||
|
<div
|
||||||
|
key={i}
|
||||||
|
className={`break-all leading-tight ${
|
||||||
|
l.level === 'error' ? 'text-red-400' : l.level === 'warn' ? 'text-yellow-300' : 'text-green-300/90'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{l.msg}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{logBuffer.length === 0 && <div className="text-green-500/50 italic">sem logs ainda…</div>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
/**
|
||||||
|
* DEVKIT — Visual fake controllers + keyboard driver.
|
||||||
|
*
|
||||||
|
* Renders two spheres (L=blue, R=red) at the fake controller positions and
|
||||||
|
* listens to global keyboard for grip/trigger/movement. Mounted only when
|
||||||
|
* SimXR is active.
|
||||||
|
*
|
||||||
|
* Keys:
|
||||||
|
* Q / W → hold grip Left / Right (analog = 1.0)
|
||||||
|
* A / S → hold trigger Left / Right (analog = 1.0)
|
||||||
|
* 1 / 2 → select Left / Right as the active hand
|
||||||
|
* Arrows → move active hand on X (←→) / Y (↑↓)
|
||||||
|
* Shift+Arrows→ move active hand on Z (↑=forward, ↓=back)
|
||||||
|
* R → reset hand poses
|
||||||
|
*/
|
||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { useFrame } from '@react-three/fiber';
|
||||||
|
import * as THREE from 'three';
|
||||||
|
import { fakeInput, setFakeActive } from './fakeInputStore';
|
||||||
|
|
||||||
|
const STEP = 0.03; // m per keypress
|
||||||
|
|
||||||
|
export function FakeControllers() {
|
||||||
|
const leftMesh = useRef<THREE.Mesh>(null);
|
||||||
|
const rightMesh = useRef<THREE.Mesh>(null);
|
||||||
|
const [, force] = useState(0);
|
||||||
|
const activeHand = useRef<'left' | 'right'>('right');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setFakeActive(true);
|
||||||
|
return () => setFakeActive(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const keys = new Set<string>();
|
||||||
|
|
||||||
|
const apply = () => {
|
||||||
|
const pos = new THREE.Vector3();
|
||||||
|
const quat = new THREE.Quaternion();
|
||||||
|
const scl = new THREE.Vector3();
|
||||||
|
const hand = fakeInput[activeHand.current];
|
||||||
|
hand.gripWorld.decompose(pos, quat, scl);
|
||||||
|
|
||||||
|
const dx = (keys.has('ArrowRight') ? STEP : 0) - (keys.has('ArrowLeft') ? STEP : 0);
|
||||||
|
const dyOrZ = (keys.has('ArrowUp') ? STEP : 0) - (keys.has('ArrowDown') ? STEP : 0);
|
||||||
|
const shift = keys.has('Shift');
|
||||||
|
pos.x += dx;
|
||||||
|
if (shift) pos.z -= dyOrZ; // up = forward (-Z)
|
||||||
|
else pos.y += dyOrZ;
|
||||||
|
|
||||||
|
hand.gripWorld.compose(pos, quat, scl);
|
||||||
|
|
||||||
|
// grip / trigger
|
||||||
|
fakeInput.left.gripValue = keys.has('q') ? 1 : 0;
|
||||||
|
fakeInput.right.gripValue = keys.has('w') ? 1 : 0;
|
||||||
|
fakeInput.left.triggerValue = keys.has('a') ? 1 : 0;
|
||||||
|
fakeInput.right.triggerValue = keys.has('s') ? 1 : 0;
|
||||||
|
|
||||||
|
force((n) => n + 1);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onDown = (e: KeyboardEvent) => {
|
||||||
|
const k = e.key === 'Shift' ? 'Shift' : e.key;
|
||||||
|
keys.add(k);
|
||||||
|
if (k === '1') activeHand.current = 'left';
|
||||||
|
else if (k === '2') activeHand.current = 'right';
|
||||||
|
else if (k === 'r' || k === 'R') {
|
||||||
|
fakeInput.left.gripWorld.makeTranslation(-0.25, 1.2, -0.5);
|
||||||
|
fakeInput.right.gripWorld.makeTranslation(0.25, 1.2, -0.5);
|
||||||
|
force((n) => n + 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
apply();
|
||||||
|
};
|
||||||
|
const onUp = (e: KeyboardEvent) => {
|
||||||
|
const k = e.key === 'Shift' ? 'Shift' : e.key;
|
||||||
|
keys.delete(k);
|
||||||
|
apply();
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('keydown', onDown);
|
||||||
|
window.addEventListener('keyup', onUp);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('keydown', onDown);
|
||||||
|
window.removeEventListener('keyup', onUp);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Sync mesh visuals to fake state each frame
|
||||||
|
useFrame(() => {
|
||||||
|
if (leftMesh.current) {
|
||||||
|
const p = new THREE.Vector3().setFromMatrixPosition(fakeInput.left.gripWorld);
|
||||||
|
leftMesh.current.position.copy(p);
|
||||||
|
const grabbing = fakeInput.left.gripValue > 0.7;
|
||||||
|
const mat = leftMesh.current.material as THREE.MeshStandardMaterial;
|
||||||
|
mat.emissiveIntensity = grabbing ? 1.5 : 0.4;
|
||||||
|
}
|
||||||
|
if (rightMesh.current) {
|
||||||
|
const p = new THREE.Vector3().setFromMatrixPosition(fakeInput.right.gripWorld);
|
||||||
|
rightMesh.current.position.copy(p);
|
||||||
|
const grabbing = fakeInput.right.gripValue > 0.7;
|
||||||
|
const mat = rightMesh.current.material as THREE.MeshStandardMaterial;
|
||||||
|
mat.emissiveIntensity = grabbing ? 1.5 : 0.4;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<mesh ref={leftMesh}>
|
||||||
|
<sphereGeometry args={[0.04, 16, 16]} />
|
||||||
|
<meshStandardMaterial color="#3b82f6" emissive="#3b82f6" emissiveIntensity={0.4} />
|
||||||
|
</mesh>
|
||||||
|
<mesh ref={rightMesh}>
|
||||||
|
<sphereGeometry args={[0.04, 16, 16]} />
|
||||||
|
<meshStandardMaterial color="#ef4444" emissive="#ef4444" emissiveIntensity={0.4} />
|
||||||
|
</mesh>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
/**
|
||||||
|
* DEVKIT — global mutable store for fake controller inputs.
|
||||||
|
*
|
||||||
|
* Lives outside React (plain object + listeners) so useControllerGrab can
|
||||||
|
* read it from inside useFrame with zero re-render cost. Mirrors the shape
|
||||||
|
* of a real WebXR XRInputSource just enough to feed our grab logic.
|
||||||
|
*/
|
||||||
|
import * as THREE from 'three';
|
||||||
|
|
||||||
|
export interface FakeHandState {
|
||||||
|
gripValue: number; // 0..1
|
||||||
|
triggerValue: number; // 0..1
|
||||||
|
hasPose: boolean; // true if controller is "tracked"
|
||||||
|
gripWorld: THREE.Matrix4; // world pose of the gripSpace
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FakeInputState {
|
||||||
|
active: boolean;
|
||||||
|
left: FakeHandState;
|
||||||
|
right: FakeHandState;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeHand(): FakeHandState {
|
||||||
|
return {
|
||||||
|
gripValue: 0,
|
||||||
|
triggerValue: 0,
|
||||||
|
hasPose: true,
|
||||||
|
gripWorld: new THREE.Matrix4(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const fakeInput: FakeInputState = {
|
||||||
|
active: false,
|
||||||
|
left: makeHand(),
|
||||||
|
right: makeHand(),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Initial poses — a bit in front of the camera, hands apart at chest height
|
||||||
|
fakeInput.left.gripWorld.makeTranslation(-0.25, 1.2, -0.5);
|
||||||
|
fakeInput.right.gripWorld.makeTranslation(0.25, 1.2, -0.5);
|
||||||
|
|
||||||
|
export function setFakeActive(on: boolean) {
|
||||||
|
fakeInput.active = on;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isFakeActive(): boolean {
|
||||||
|
return fakeInput.active;
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
/**
|
||||||
|
* DEVKIT entry point. The whole devkit is gated by this single flag.
|
||||||
|
*
|
||||||
|
* Activation: append `?devkit=1` to URL OR run in console:
|
||||||
|
* localStorage.setItem('devkit', '1')
|
||||||
|
* Deactivation: `?devkit=0` OR localStorage.removeItem('devkit')
|
||||||
|
*
|
||||||
|
* To remove DevKit from the project entirely:
|
||||||
|
* 1. rm -rf src/devkit/
|
||||||
|
* 2. Strip `// DEVKIT:` blocks in XRSession.tsx & useControllerGrab.ts
|
||||||
|
*/
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
const KEY = 'devkit';
|
||||||
|
|
||||||
|
function readFlag(): boolean {
|
||||||
|
if (typeof window === 'undefined') return false;
|
||||||
|
const params = new URLSearchParams(window.location.search);
|
||||||
|
const urlVal = params.get(KEY);
|
||||||
|
if (urlVal === '1') {
|
||||||
|
localStorage.setItem(KEY, '1');
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (urlVal === '0') {
|
||||||
|
localStorage.removeItem(KEY);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return localStorage.getItem(KEY) === '1';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDevKit(): boolean {
|
||||||
|
const [enabled, setEnabled] = useState(readFlag);
|
||||||
|
useEffect(() => {
|
||||||
|
const onStorage = () => setEnabled(readFlag());
|
||||||
|
window.addEventListener('storage', onStorage);
|
||||||
|
return () => window.removeEventListener('storage', onStorage);
|
||||||
|
}, []);
|
||||||
|
return enabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDevKit(): boolean {
|
||||||
|
return readFlag();
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
import { useRef } from 'react';
|
import { useRef } from 'react';
|
||||||
import { useFrame, useThree } from '@react-three/fiber';
|
import { useFrame, useThree } from '@react-three/fiber';
|
||||||
import * as THREE from 'three';
|
import * as THREE from 'three';
|
||||||
|
// DEVKIT: remove this import + the fake-input block in useFrame to strip devkit
|
||||||
|
import { fakeInput, isFakeActive } from '@/devkit/fakeInputStore';
|
||||||
|
|
||||||
export interface GrabState {
|
export interface GrabState {
|
||||||
/** Analog grip pressure (0..1) */
|
/** Analog grip pressure (0..1) */
|
||||||
@@ -50,6 +52,26 @@ export function useControllerGrab() {
|
|||||||
const { gl } = useThree();
|
const { gl } = useThree();
|
||||||
|
|
||||||
useFrame((_state, _delta, frame: XRFrame | undefined) => {
|
useFrame((_state, _delta, frame: XRFrame | undefined) => {
|
||||||
|
// DEVKIT: fake-input branch — bypasses real WebXR when SimXR is active.
|
||||||
|
if (isFakeActive()) {
|
||||||
|
for (const hand of ['left', 'right'] as const) {
|
||||||
|
const fake = fakeInput[hand];
|
||||||
|
const slot = ref.current[hand];
|
||||||
|
slot.gripValue = fake.gripValue;
|
||||||
|
slot.triggerValue = fake.triggerValue;
|
||||||
|
slot.hasPose = fake.hasPose;
|
||||||
|
slot.gripWorld.copy(fake.gripWorld);
|
||||||
|
if (!slot.isGrabbing && fake.gripValue > GRAB_ON) {
|
||||||
|
slot.isGrabbing = true;
|
||||||
|
console.log(`[XR][grab] ▶ ${hand} START (fake v=${fake.gripValue.toFixed(2)})`);
|
||||||
|
} else if (slot.isGrabbing && fake.gripValue < GRAB_OFF) {
|
||||||
|
slot.isGrabbing = false;
|
||||||
|
console.log(`[XR][grab] ◼ ${hand} END (fake)`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!frame) return;
|
if (!frame) return;
|
||||||
const session = frame.session;
|
const session = frame.session;
|
||||||
const referenceSpace = gl.xr.getReferenceSpace();
|
const referenceSpace = gl.xr.getReferenceSpace();
|
||||||
|
|||||||
+52
-17
@@ -13,6 +13,10 @@ import { XRHud } from '@/components/XRHud';
|
|||||||
import { findNearestVertex } from '@/components/three/SmartMeasure';
|
import { findNearestVertex } from '@/components/three/SmartMeasure';
|
||||||
import { XRHitTestPlacement } from '@/components/three/XRHitTestPlacement';
|
import { XRHitTestPlacement } from '@/components/three/XRHitTestPlacement';
|
||||||
import { XRGrabbable } from '@/components/three/XRGrabbable';
|
import { XRGrabbable } from '@/components/three/XRGrabbable';
|
||||||
|
// DEVKIT: remove these imports + all `// DEVKIT:` blocks below to strip devkit
|
||||||
|
import { useDevKit } from '@/devkit/useDevKit';
|
||||||
|
import { DevPanel } from '@/devkit/DevPanel';
|
||||||
|
import { FakeControllers } from '@/devkit/FakeControllers';
|
||||||
|
|
||||||
// --- Diagnóstico XR ---
|
// --- Diagnóstico XR ---
|
||||||
console.log('[XR] Inicializando store...');
|
console.log('[XR] Inicializando store...');
|
||||||
@@ -400,6 +404,10 @@ const XRSession = () => {
|
|||||||
const [placementMode, setPlacementMode] = useState(true); // start in placement mode
|
const [placementMode, setPlacementMode] = useState(true); // start in placement mode
|
||||||
const [snapToPlanes, setSnapToPlanes] = useState(true);
|
const [snapToPlanes, setSnapToPlanes] = useState(true);
|
||||||
const [allowScale, setAllowScale] = useState(false);
|
const [allowScale, setAllowScale] = useState(false);
|
||||||
|
// DEVKIT: simXR forces in-XR rendering on desktop without a real WebXR session
|
||||||
|
const devkit = useDevKit();
|
||||||
|
const [simXR, setSimXR] = useState(false);
|
||||||
|
const effectiveInXR = inXR || simXR;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!model) navigate('/');
|
if (!model) navigate('/');
|
||||||
@@ -491,30 +499,52 @@ const XRSession = () => {
|
|||||||
|
|
||||||
<XROrigin />
|
<XROrigin />
|
||||||
|
|
||||||
{inXR ? (
|
{effectiveInXR ? (
|
||||||
<>
|
<>
|
||||||
{/* In XR: hit-test placement → grab wrapper → model */}
|
{/* In XR (or SimXR): grab wrapper → model. Skip hit-test in SimXR mode. */}
|
||||||
<XRHitTestPlacement
|
{simXR ? (
|
||||||
placementMode={placementMode}
|
<group position={[0, 1.0, -1.2]}>
|
||||||
snapToPlanes={snapToPlanes}
|
<XRGrabbable
|
||||||
onPlace={() => {
|
allowScale={allowScale}
|
||||||
setPlacementMode(false);
|
onGrabStart={() => { if (placementMode) setPlacementMode(false); }}
|
||||||
toast.success('Modelo posicionado na superfície!');
|
>
|
||||||
}}
|
<XRModel url={model.url} />
|
||||||
>
|
</XRGrabbable>
|
||||||
<XRGrabbable
|
</group>
|
||||||
allowScale={allowScale}
|
) : (
|
||||||
onGrabStart={() => {
|
<XRHitTestPlacement
|
||||||
if (placementMode) setPlacementMode(false);
|
placementMode={placementMode}
|
||||||
|
snapToPlanes={snapToPlanes}
|
||||||
|
onPlace={() => {
|
||||||
|
setPlacementMode(false);
|
||||||
|
toast.success('Modelo posicionado na superfície!');
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<XRModel url={model.url} />
|
<XRGrabbable
|
||||||
</XRGrabbable>
|
allowScale={allowScale}
|
||||||
</XRHitTestPlacement>
|
onGrabStart={() => { if (placementMode) setPlacementMode(false); }}
|
||||||
|
>
|
||||||
|
<XRModel url={model.url} />
|
||||||
|
</XRGrabbable>
|
||||||
|
</XRHitTestPlacement>
|
||||||
|
)}
|
||||||
|
|
||||||
<XRMeasurementOverlay />
|
<XRMeasurementOverlay />
|
||||||
<ControllerFineTuning freeMove={freeMove} />
|
<ControllerFineTuning freeMove={freeMove} />
|
||||||
<XRDebugHud />
|
<XRDebugHud />
|
||||||
|
{/* DEVKIT: fake controllers visible in scene + keyboard driver */}
|
||||||
|
{devkit && simXR && <FakeControllers />}
|
||||||
|
{/* DEVKIT: orbit camera in SimXR so you can navigate around the model */}
|
||||||
|
{simXR && (
|
||||||
|
<OrbitControls
|
||||||
|
makeDefault
|
||||||
|
enableDamping
|
||||||
|
dampingFactor={0.1}
|
||||||
|
minDistance={0.05}
|
||||||
|
maxDistance={50}
|
||||||
|
target={[0, 1.0, -1.2]}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
@@ -550,6 +580,11 @@ const XRSession = () => {
|
|||||||
allowScale={allowScale}
|
allowScale={allowScale}
|
||||||
onToggleAllowScale={() => setAllowScale(!allowScale)}
|
onToggleAllowScale={() => setAllowScale(!allowScale)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* DEVKIT: floating diagnostic panel + SimXR toggle */}
|
||||||
|
{devkit && (
|
||||||
|
<DevPanel simXR={simXR} onToggleSimXR={() => setSimXR((v) => !v)} />
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
Reference in New Issue
Block a user