From 3927630317519c2542f816e6a3f196b5227555cd Mon Sep 17 00:00:00 2001 From: cyber Date: Mon, 16 Nov 2026 08:29:08 -0400 Subject: [PATCH] fix(FenceViewer3D): optimize Three.js canvas initialization and procedural chain-link texture to prevent WebGL context crash --- src/components/FenceViewer3D.tsx | 322 ++++++++++++++++++++----------- 1 file changed, 205 insertions(+), 117 deletions(-) diff --git a/src/components/FenceViewer3D.tsx b/src/components/FenceViewer3D.tsx index 1e5395c..217f881 100644 --- a/src/components/FenceViewer3D.tsx +++ b/src/components/FenceViewer3D.tsx @@ -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(null); - - // Foco 100% Alambrado por padrão! + const canvasRef = useRef(null); + + // Estados const [fenceType, setFenceType] = useState("alambrado_curvo"); const [color, setColor] = useState("galvanizado"); const [height, setHeight] = useState("2.00m"); @@ -34,41 +79,58 @@ export default function FenceViewer3D() { const [hasBarbedWire, setHasBarbedWire] = useState(true); const [hasConcertina, setHasConcertina] = useState(false); const [autoRotate, setAutoRotate] = useState(false); - const [loading, setLoading] = useState(true); + const [webGLError, setWebGLError] = useState(false); + const [isLoaded, setIsLoaded] = useState(false); const cepInputId = useId(); const [cep, setCep] = useState(""); - // Refs de Three.js - const sceneRef = useRef(null); - const cameraRef = useRef(null); - const rendererRef = useRef(null); - const controlsRef = useRef(null); - const fenceGroupRef = useRef(null); - const groundMeshRef = useRef(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(null); + const cameraRef = useRef(null); + const rendererRef = useRef(null); + const controlsRef = useRef(null); + const fenceGroupRef = useRef(null); + const groundMeshRef = useRef(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 (
- {/* Barra de Título Superior do Simulador 3D */} + {/* Barra de Título Superior */}
@@ -502,22 +568,44 @@ export default function FenceViewer3D() {
- {/* Grid: Canvas 3D (8 cols) + Controles de Alambrado (4 cols) */} + {/* Grid: Canvas 3D (8 cols) + Controles (4 cols) */}
- {/* Canvas 3D */} -
-
+ {/* Canvas 3D Viewport com fallback visual garantido */} +
+ {/* O CANVAS É DECLARATIVO E EXCLUSIVO (Zero duplicações ou broken image) */} + - {/* Dica */} -
+ {/* Fallback caso WebGL seja bloqueado na GPU do usuário */} + {webGLError && ( +
+
+ +
+
+

Visualizador em Modo Interativo 2D

+

+ 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! +

+
+
+ )} + + {/* Dica de Interação */} +
Gire 360° • Aproxime para ver a malha losangular e mourões de concreto
{/* Badge Inferior */} -
-
+
+
{currentLayout.desc} Altura: {height} • Mourão: {isCurved ? "Ponta Curva com Arame Farpado" : "Reto"} @@ -525,7 +613,7 @@ export default function FenceViewer3D() {
{/* Alternador de Solo */} -
+
Solo: