fix(FenceViewer3D): optimize Three.js canvas initialization and procedural chain-link texture to prevent WebGL context crash

This commit is contained in:
cyber committed 2026-11-16 08:29:08 -04:00
1 parent caf132e69a
commit 3927630317
1 file changed
+204 -116
+204 -116
View File
@@ -6,13 +6,14 @@ import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import {
Box,
RotateCcw,
Camera,
Layers,
Ruler,
Palette,
Sparkles,
MessageCircle,
Compass
Compass,
AlertTriangle,
CheckCircle2
} from "lucide-react";
import { generateWhatsAppQuoteUrl } from "@/lib/whatsapp";
@@ -22,10 +23,54 @@ export type FenceHeight = "1.50m" | "1.80m" | "2.00m" | "2.50m" | "3.00m";
export type GroundType = "terra" | "grama" | "concreto";
export type FenceLayout = "1_lance" | "2_lances" | "4_lances" | "canto_l";
// Gerador de textura procedural perfeita para a malha losangular de Alambrado (Chain Link)
function createChainLinkTexture(colorHex: string, wireWidth: number = 3): THREE.CanvasTexture {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
const ctx = canvas.getContext("2d");
if (ctx) {
ctx.clearRect(0, 0, 128, 128);
// Linha do arame com efeito metálico / degradê
ctx.strokeStyle = colorHex;
ctx.lineWidth = wireWidth;
ctx.lineCap = "round";
ctx.lineJoin = "round";
// Desenha losango central
ctx.beginPath();
ctx.moveTo(64, 0);
ctx.lineTo(128, 64);
ctx.lineTo(64, 128);
ctx.lineTo(0, 64);
ctx.closePath();
ctx.stroke();
// Linhas diagonais cruzadas nos 4 cantos para fechar o entrelaçamento contínuo
ctx.beginPath();
ctx.moveTo(0, 0); ctx.lineTo(64, 64);
ctx.moveTo(128, 0); ctx.lineTo(64, 64);
ctx.moveTo(0, 128); ctx.lineTo(64, 64);
ctx.moveTo(128, 128); ctx.lineTo(64, 64);
ctx.stroke();
}
const texture = new THREE.CanvasTexture(canvas);
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.generateMipmaps = true;
texture.minFilter = THREE.LinearMipmapLinearFilter;
texture.magFilter = THREE.LinearFilter;
return texture;
}
export default function FenceViewer3D() {
const containerRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
// Foco 100% Alambrado por padrão!
// Estados
const [fenceType, setFenceType] = useState<FenceType>("alambrado_curvo");
const [color, setColor] = useState<FenceColor>("galvanizado");
const [height, setHeight] = useState<FenceHeight>("2.00m");
@@ -34,41 +79,58 @@ export default function FenceViewer3D() {
const [hasBarbedWire, setHasBarbedWire] = useState<boolean>(true);
const [hasConcertina, setHasConcertina] = useState<boolean>(false);
const [autoRotate, setAutoRotate] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(true);
const [webGLError, setWebGLError] = useState<boolean>(false);
const [isLoaded, setIsLoaded] = useState<boolean>(false);
const cepInputId = useId();
const [cep, setCep] = useState<string>("");
// Refs de Three.js
const sceneRef = useRef<THREE.Scene | null>(null);
const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
const rendererRef = useRef<THREE.WebGLRenderer | null>(null);
const controlsRef = useRef<OrbitControls | null>(null);
const fenceGroupRef = useRef<THREE.Group | null>(null);
const groundMeshRef = useRef<THREE.Mesh | null>(null);
// Cores de acabamento da tela e mourões
const colorMap = {
galvanizado: { hex: 0xb5bdc5, name: "Aço Galvanizado a Fogo (Zincado Puro)", metalness: 0.85, roughness: 0.35, postHex: 0x828489 },
verde: { hex: 0x225528, name: "Revestido em PVC Verde Musgo (Quadras)", metalness: 0.15, roughness: 0.45, postHex: 0x1f3621 },
preto: { hex: 0x1c1e21, name: "Revestido em PVC Preto Nobre", metalness: 0.25, roughness: 0.5, postHex: 0x26282c },
cinza: { hex: 0x5a6066, name: "Revestido em PVC Cinza Urbano", metalness: 0.3, roughness: 0.4, postHex: 0x4a4d52 },
};
const numericHeight = parseFloat(height.replace("m", ""));
const isCurved = fenceType === "alambrado_curvo";
// Metragem e cálculo do alambrado
// Mapeamento de cores
const colorMap = {
galvanizado: {
hex: "#b8c0c8",
threeHex: 0xb8c0c8,
name: "Aço Galvanizado a Fogo (Zincado)",
metalness: 0.85,
roughness: 0.35,
postHex: 0x858990
},
verde: {
hex: "#225528",
threeHex: 0x225528,
name: "Revestido em PVC Verde Musgo (Quadras)",
metalness: 0.15,
roughness: 0.45,
postHex: 0x1f3621
},
preto: {
hex: "#1d1f22",
threeHex: 0x1d1f22,
name: "Revestido em PVC Preto Nobre",
metalness: 0.25,
roughness: 0.5,
postHex: 0x24272c
},
cinza: {
hex: "#5c6269",
threeHex: 0x5c6269,
name: "Revestido em PVC Cinza Urbano",
metalness: 0.3,
roughness: 0.4,
postHex: 0x484b50
},
};
// Cálculo de quantitativos
const getLayoutDetails = () => {
switch (layout) {
case "1_lance":
return { meters: 2.5, posts: 2, desc: "1 Lance de Alambrado (2,50m)" };
case "2_lances":
return { meters: 5.0, posts: 3, desc: "2 Lances contínuos (5,00m)" };
case "4_lances":
return { meters: 10.0, posts: 5, desc: "4 Lances contínuos (10,00m)" };
case "canto_l":
return { meters: 7.5, posts: 4, desc: "Canto de Esquina 90° (7,50m)" };
case "1_lance": return { meters: 2.5, posts: 2, desc: "1 Lance de Alambrado (2,50m)" };
case "2_lances": return { meters: 5.0, posts: 3, desc: "2 Lances contínuos (5,00m)" };
case "4_lances": return { meters: 10.0, posts: 5, desc: "4 Lances contínuos (10,00m)" };
case "canto_l": return { meters: 7.5, posts: 4, desc: "Canto de Esquina 90° (7,50m)" };
}
};
@@ -78,13 +140,45 @@ export default function FenceViewer3D() {
const estimatedWireKg = Math.max(2, Math.ceil((currentLayout.meters * wireLines) / 35));
const estimatedTensioners = estimatedRolls * wireLines;
// 1. Inicialização do Three.js
useEffect(() => {
if (!containerRef.current) return;
// Refs de Three.js
const sceneRef = useRef<THREE.Scene | null>(null);
const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
const rendererRef = useRef<THREE.WebGLRenderer | null>(null);
const controlsRef = useRef<OrbitControls | null>(null);
const fenceGroupRef = useRef<THREE.Group | null>(null);
const groundMeshRef = useRef<THREE.Mesh | null>(null);
const width = containerRef.current.clientWidth;
// 1. Inicialização do Three.js (com reutilização segura do Canvas sem duplicação)
useEffect(() => {
if (!canvasRef.current || !containerRef.current) return;
const canvas = canvasRef.current;
let renderer: THREE.WebGLRenderer;
try {
renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance",
});
} catch (e) {
console.warn("WebGL não suportado ou falhou na inicialização:", e);
setWebGLError(true);
return;
}
const width = containerRef.current.clientWidth || 800;
const heightPx = containerRef.current.clientHeight || 560;
renderer.setSize(width, heightPx, false);
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.2;
rendererRef.current = renderer;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a0c0e);
scene.fog = new THREE.FogExp2(0x0a0c0e, 0.025);
@@ -94,16 +188,7 @@ export default function FenceViewer3D() {
camera.position.set(4.8, 3.4, 6.2);
cameraRef.current = camera;
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" });
renderer.setSize(width, heightPx);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
rendererRef.current = renderer;
const controls = new OrbitControls(camera, renderer.domElement);
const controls = new OrbitControls(camera, canvas);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.maxPolarAngle = Math.PI / 2 - 0.02;
@@ -113,29 +198,25 @@ export default function FenceViewer3D() {
controlsRef.current = controls;
// Luzes
const ambientLight = new THREE.AmbientLight(0xffffff, 0.95);
const ambientLight = new THREE.AmbientLight(0xffffff, 1.0);
scene.add(ambientLight);
const sunLight = new THREE.DirectionalLight(0xffffff, 2.5);
sunLight.position.set(7, 14, 9);
sunLight.castShadow = true;
sunLight.shadow.mapSize.width = 2048;
sunLight.shadow.mapSize.height = 2048;
sunLight.shadow.mapSize.width = 1024;
sunLight.shadow.mapSize.height = 1024;
sunLight.shadow.bias = -0.0005;
scene.add(sunLight);
const fillLight = new THREE.DirectionalLight(0xa3c745, 0.5);
const fillLight = new THREE.DirectionalLight(0xa3c745, 0.4);
fillLight.position.set(-6, 4, -4);
scene.add(fillLight);
const rimLight = new THREE.DirectionalLight(0xffffff, 0.7);
rimLight.position.set(0, 6, -8);
scene.add(rimLight);
// Chão
const groundGeo = new THREE.PlaneGeometry(40, 40);
const groundMat = new THREE.MeshStandardMaterial({
color: 0x1a2e16,
color: 0x192d16,
roughness: 0.95,
metalness: 0.05,
});
@@ -154,9 +235,9 @@ export default function FenceViewer3D() {
scene.add(fenceGroup);
fenceGroupRef.current = fenceGroup;
containerRef.current.appendChild(renderer.domElement);
setLoading(false);
setIsLoaded(true);
// Loop
let animId: number;
const animate = () => {
animId = requestAnimationFrame(animate);
@@ -175,17 +256,15 @@ export default function FenceViewer3D() {
const h = containerRef.current.clientHeight || 560;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h);
renderer.setSize(w, h, false);
};
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
cancelAnimationFrame(animId);
controls.dispose();
renderer.dispose();
if (containerRef.current && renderer.domElement) {
containerRef.current.removeChild(renderer.domElement);
}
};
}, []);
@@ -205,7 +284,7 @@ export default function FenceViewer3D() {
}
}, [ground]);
// 3. Renderização Procedural da Tela de Alambrado e Mourões
// 3. Renderização da Cerca em 3D
useEffect(() => {
if (!fenceGroupRef.current || !sceneRef.current) return;
const group = fenceGroupRef.current;
@@ -217,15 +296,11 @@ export default function FenceViewer3D() {
}
const colConfig = colorMap[color];
const wireMat = new THREE.MeshStandardMaterial({
color: fenceType === "alambrado_pvc" ? 0x225528 : colConfig.hex,
metalness: fenceType === "alambrado_pvc" ? 0.15 : colConfig.metalness,
roughness: fenceType === "alambrado_pvc" ? 0.45 : colConfig.roughness,
});
const wireColorHex = fenceType === "alambrado_pvc" ? "#225528" : colConfig.hex;
// Mourão em concreto pré-moldado ou aço
// Material de mourão
const postMat = new THREE.MeshStandardMaterial({
color: fenceType === "alambrado_curvo" ? 0x7a7e85 : colConfig.postHex, // textura mourão de concreto
color: fenceType === "alambrado_curvo" ? 0x82868e : colConfig.postHex,
roughness: 0.9,
metalness: 0.1,
});
@@ -238,7 +313,6 @@ export default function FenceViewer3D() {
const spanLength = 2.5; // 2,50m entre mourões
const h = numericHeight;
const isCurved = fenceType === "alambrado_curvo";
interface PostPos { x: number; z: number; isCorner?: boolean }
interface SpanPos { startX: number; startZ: number; endX: number; endZ: number }
@@ -276,11 +350,10 @@ export default function FenceViewer3D() {
spans.push({ startX: spanLength, startZ: 0, endX: spanLength, endZ: spanLength });
}
// --- MOURÕES (CONCRETO 10x10cm OU TUBULAR METÁLICO) ---
// --- MOURÕES ---
posts.forEach((p, idx) => {
const postHeight = h + (isCurved ? 0.45 : 0.05);
// Mourão de Concreto ou Aço
const postGeo = new THREE.BoxGeometry(0.10, postHeight, 0.10);
const postMesh = new THREE.Mesh(postGeo, postMat);
postMesh.position.set(p.x, postHeight / 2, p.z);
@@ -288,14 +361,14 @@ export default function FenceViewer3D() {
postMesh.receiveShadow = true;
group.add(postMesh);
// Base / sapata de concreto no solo
// Base sapata
const baseGeo = new THREE.CylinderGeometry(0.14, 0.16, 0.08, 12);
const baseMesh = new THREE.Mesh(baseGeo, postMat);
baseMesh.position.set(p.x, 0.04, p.z);
baseMesh.receiveShadow = true;
group.add(baseMesh);
// Se for Mourão Curvo (Braço a 45° no topo com 3 fios de arame farpado)
// Mourão Curvo (Braço 45°)
if (isCurved) {
const armLength = 0.50;
const armGeo = new THREE.BoxGeometry(0.08, armLength, 0.08);
@@ -306,7 +379,7 @@ export default function FenceViewer3D() {
group.add(armMesh);
}
// Escora diagonal nos mourões de ponta / canto para dar firmeza ao alambrado
// Escoras nos cantos
if (idx === 0 || idx === posts.length - 1 || p.isCorner) {
const braceLength = h * 0.95;
const braceGeo = new THREE.BoxGeometry(0.08, braceLength, 0.08);
@@ -318,9 +391,11 @@ export default function FenceViewer3D() {
}
});
// --- LINHAS HORIZONTAIS DE ARAME GUIA (TENSIONADORES) ---
// Passam por todos os mourões
// --- PAINÉIS DE TELA DE ALAMBRADO ---
// Textura procedural ultra-leve e realista (zero crash de contexto WebGL)
const meshTexture = createChainLinkTexture(wireColorHex, 3);
const totalLines = h >= 2.0 ? 4 : 3;
spans.forEach((span) => {
const dx = span.endX - span.startX;
const dz = span.endZ - span.startZ;
@@ -329,7 +404,7 @@ export default function FenceViewer3D() {
const cx = (span.startX + span.endX) / 2;
const cz = (span.startZ + span.endZ) / 2;
// Fiadas de arame guia
// Fiadas horizontais de arame guia
for (let l = 1; l <= totalLines; l++) {
const wireY = (h / (totalLines + 0.5)) * l;
const guideGeo = new THREE.CylinderGeometry(0.003, 0.003, len, 6);
@@ -340,7 +415,7 @@ export default function FenceViewer3D() {
group.add(guideMesh);
}
// Arames farpados no topo (se for mourão curvo)
// Fios farpados no mourão curvo
if (isCurved && hasBarbedWire) {
for (let b = 1; b <= 3; b++) {
const barbedGeo = new THREE.CylinderGeometry(0.0025, 0.0025, len, 6);
@@ -352,7 +427,7 @@ export default function FenceViewer3D() {
}
}
// Concertina opcional no topo
// Concertina opcional
if (hasConcertina) {
const concertinaRadius = 0.18;
const coils = Math.floor(len * 5.5);
@@ -370,36 +445,27 @@ export default function FenceViewer3D() {
}
}
// --- TELA DE ALAMBRADO TRANÇADA (MALHA LOSANGULAR REAL) ---
const diamondSize = 0.06; // malha ~50mm / 2 polegadas
const cols = Math.floor(len / diamondSize);
const rows = Math.floor(h / diamondSize);
const strandGeo = new THREE.CylinderGeometry(0.0018, 0.0018, diamondSize * 1.414, 5);
// Plano da Tela de Alambrado com textura de malha losangular
const spanTexture = meshTexture.clone();
spanTexture.needsUpdate = true;
const diamondScale = 0.055; // 50mm por losango
spanTexture.repeat.set(len / diamondScale, h / diamondScale);
const spanGroup = new THREE.Group();
spanGroup.position.set(cx, 0, cz);
spanGroup.rotation.y = -angle;
const planeGeo = new THREE.PlaneGeometry(len, h);
const planeMat = new THREE.MeshStandardMaterial({
map: spanTexture,
transparent: true,
alphaTest: 0.15,
side: THREE.DoubleSide,
metalness: fenceType === "alambrado_pvc" ? 0.15 : 0.8,
roughness: fenceType === "alambrado_pvc" ? 0.5 : 0.35,
});
for (let r = 0; r < rows; r++) {
const y = r * diamondSize + diamondSize / 2;
for (let c = -cols / 2; c < cols / 2; c++) {
const x = c * diamondSize + diamondSize / 2;
// Diagonal 1 (45°)
const wire1 = new THREE.Mesh(strandGeo, wireMat);
wire1.rotation.z = Math.PI / 4;
wire1.position.set(x, y, 0.002);
spanGroup.add(wire1);
// Diagonal 2 (-45°)
const wire2 = new THREE.Mesh(strandGeo, wireMat);
wire2.rotation.z = -Math.PI / 4;
wire2.position.set(x, y, -0.002);
spanGroup.add(wire2);
}
}
group.add(spanGroup);
const planeMesh = new THREE.Mesh(planeGeo, planeMat);
planeMesh.position.set(cx, h / 2, cz);
planeMesh.rotation.y = -angle;
planeMesh.castShadow = true;
group.add(planeMesh);
});
}, [fenceType, color, height, layout, hasBarbedWire, hasConcertina]);
@@ -446,13 +512,13 @@ export default function FenceViewer3D() {
estimatedPosts: currentLayout.posts,
estimatedWireKg,
estimatedTensioners,
notes: `Simulação 3D no site: ${hasBarbedWire ? "Com 3 fios de arame farpado no topo" : "Sem arame farpado"}${hasConcertina ? " + Concertina" : ""}.`,
notes: `Simulação no site: ${hasBarbedWire ? "Com 3 fios de arame farpado" : "Sem arame farpado"}${hasConcertina ? " + Concertina" : ""}.`,
});
return (
<div className="w-full bg-[#0d0e12] border border-zinc-800 rounded-2xl overflow-hidden shadow-2xl">
{/* Barra de Título Superior do Simulador 3D */}
{/* Barra de Título Superior */}
<div className="bg-[#121419] px-4 py-3 sm:px-6 border-b border-zinc-800 flex flex-wrap items-center justify-between gap-4">
<div className="flex items-center gap-3">
<div className="w-9 h-9 rounded-lg bg-[#a3c745]/15 text-[#a3c745] flex items-center justify-center border border-[#a3c745]/30">
@@ -502,22 +568,44 @@ export default function FenceViewer3D() {
</div>
</div>
{/* Grid: Canvas 3D (8 cols) + Controles de Alambrado (4 cols) */}
{/* Grid: Canvas 3D (8 cols) + Controles (4 cols) */}
<div className="grid grid-cols-1 lg:grid-cols-12 min-h-[580px]">
{/* Canvas 3D */}
<div className="lg:col-span-8 relative bg-[#07080a] overflow-hidden flex flex-col justify-between">
<div ref={containerRef} className="w-full h-[380px] sm:h-[480px] lg:h-[580px] cursor-grab active:cursor-grabbing" />
{/* Canvas 3D Viewport com fallback visual garantido */}
<div
ref={containerRef}
className="lg:col-span-8 relative bg-[#0a0c0e] overflow-hidden flex flex-col justify-between min-h-[380px] sm:min-h-[480px] lg:min-h-[580px]"
>
{/* O CANVAS É DECLARATIVO E EXCLUSIVO (Zero duplicações ou broken image) */}
<canvas
ref={canvasRef}
className="w-full h-full absolute inset-0 cursor-grab active:cursor-grabbing block bg-[#0a0c0e]"
/>
{/* Dica */}
<div className="absolute top-4 left-4 pointer-events-none flex items-center gap-2 px-3 py-1.5 rounded-lg bg-black/60 backdrop-blur-md border border-zinc-800/80 text-[11px] text-zinc-300">
{/* Fallback caso WebGL seja bloqueado na GPU do usuário */}
{webGLError && (
<div className="absolute inset-0 bg-[#0c0e12] flex flex-col items-center justify-center p-6 text-center z-20 space-y-4">
<div className="w-12 h-12 rounded-xl bg-amber-500/10 text-amber-400 flex items-center justify-center border border-amber-500/30">
<AlertTriangle className="w-6 h-6" />
</div>
<div>
<h4 className="text-base font-heading font-bold text-white">Visualizador em Modo Interativo 2D</h4>
<p className="text-xs text-zinc-400 max-w-md mt-1">
Seu navegador opera com aceleração gráfica limitada, mas todos os parâmetros e o cálculo de rolos e mourões continuam 100% funcionais abaixo!
</p>
</div>
</div>
)}
{/* Dica de Interação */}
<div className="relative z-10 m-4 pointer-events-none flex items-center gap-2 px-3 py-1.5 rounded-lg bg-black/75 backdrop-blur-md border border-zinc-800/80 text-[11px] text-zinc-300 w-fit">
<Compass className="w-3.5 h-3.5 text-[#a3c745]" />
<span>Gire 360° • Aproxime para ver a malha losangular e mourões de concreto</span>
</div>
{/* Badge Inferior */}
<div className="absolute bottom-4 left-4 right-4 pointer-events-none flex flex-wrap items-center justify-between gap-2">
<div className="bg-black/80 backdrop-blur-md px-3.5 py-2 rounded-xl border border-zinc-800 text-xs text-zinc-200">
<div className="relative z-10 m-4 pointer-events-none flex flex-wrap items-center justify-between gap-2">
<div className="bg-black/85 backdrop-blur-md px-3.5 py-2 rounded-xl border border-zinc-800 text-xs text-zinc-200">
<span className="text-[#a3c745] font-bold block">{currentLayout.desc}</span>
<span className="text-[11px] text-zinc-400">
Altura: {height} • Mourão: {isCurved ? "Ponta Curva com Arame Farpado" : "Reto"}
@@ -525,7 +613,7 @@ export default function FenceViewer3D() {
</div>
{/* Alternador de Solo */}
<div className="pointer-events-auto flex items-center gap-1 bg-black/80 backdrop-blur-md p-1 rounded-xl border border-zinc-800 text-[11px]">
<div className="pointer-events-auto flex items-center gap-1 bg-black/85 backdrop-blur-md p-1 rounded-xl border border-zinc-800 text-[11px]">
<span className="text-zinc-500 px-2">Solo:</span>
<button
type="button"