/* house3d-card v7 — 3D-модель дома (GLB) в Home Assistant. * Загружает three.js r140 + GLTFLoader (UMD) + /local/house3d/house.glb. * Клик по модели переключает сущность; оптимистичный отклик; фоновая сверка. * * Конфиг: type: custom:house3d-card, entity, domain, service, title, room */ const ROOM_NAMES = { zone_terrasa: "Терраса", zone_kitchen: "Кухня-гостиная", zone_postirochnaia: "Тех.пом.", zone_sanuzel: "Санузел", zone_tualet: "Туалет", zone_garderob: "Гардероб", zone_kladovaia: "Кладовая", zone_koridor: "Холл", zone_prihozhaya: "Прихожая", zone_tambur: "Тамбур", zone_kabinet: "Комната 11,45", zone_danina_komnata: "Комната 12,04", zone_spalnia: "Комната 14,34", zone_kryltso: "Крыльцо", }; class House3dCard extends HTMLElement { setConfig(config) { this._config = Object.assign( { entity: "", title: "Дом", room: "", domain: "switch", service: "toggle", model: "/local/house3d/house-web-v52.glb?v=52" }, config || {}, ); this._root = this.attachShadow({ mode: "open" }); this._onSelect = (ev) => { const room = ev && ev.detail ? ev.detail.room : null; this._room = room; if (this._roomNameEl) { this._roomNameEl.textContent = room ? (ROOM_NAMES[room] || room.replace("zone_", "")) : "обзор"; } this._highlightZone(room); }; document.addEventListener("house3d-select", this._onSelect); this._root.innerHTML = `
${this._config.title}обзор
—
12:00
клик по дому — вкл/выкл · тянуть — поворот · колесо — зум
загрузка модели…
`; this._wrap = this._root.querySelector(".wrap"); this._dot = this._root.querySelector(".dot"); this._txt = this._root.querySelector(".txt"); this._chip = this._root.querySelector(".chip"); if (!(this._config && this._config.entity) && this._chip) this._chip.style.display = "none"; this._roomNameEl = this._root.querySelector(".roomname"); this._night = false; this._nightBtn = this._root.querySelector(".nightbtn"); this._hour = 12; this._zones = {}; this._selZone = null; const sl = this._root.querySelector(".timeslider input"); const hr = this._root.querySelector(".timeslider .hr"); if (sl) { const upd = () => { this._hour = parseFloat(sl.value); if (hr) hr.textContent = String(Math.floor(this._hour)).padStart(2, "0") + ":00"; this._setHour(this._hour); }; sl.addEventListener("input", upd); this._setHour = (h) => { const day = h >= 6 && h <= 20; const k = day ? 1 : 0.15; if (this._sun) this._sun.intensity = 1.1 * k; if (this._amb) this._amb.intensity = 0.22 * (day ? 1 : 0.35); if (this._hemi) this._hemi.intensity = 0.45 * (day ? 1 : 0.3); const wrap = this._root.querySelector(".wrap"); if (wrap) wrap.classList.toggle("night", !day); if (this._model) { this._model.traverse((o) => { if (!o.isMesh || !o.material) return; const mats = Array.isArray(o.material) ? o.material : [o.material]; for (const m of mats) { const n = (m.name || "").toLowerCase(); if (n.indexOf("lamp") >= 0) { if (!m.emissive) continue; m.emissive.setHex(0xffd9a0); m.emissiveIntensity = day ? 0.0 : 2.6; m.needsUpdate = true; } } }); } }; setTimeout(() => upd(), 1200); } if (this._nightBtn) this._nightBtn.addEventListener("click", () => this._toggleNight()); this._load = this._root.querySelector(".load"); } set hass(hass) { this._hass = hass; if (!this._booted) this._boot(); this._syncState(); } _script(src) { return new Promise((res, rej) => { const s = document.createElement("script"); s.src = src; s.onload = res; s.onerror = () => rej(new Error(src)); document.head.appendChild(s); }); } async _boot() { this._booted = true; try { if (!window.THREE) await this._script("/local/house3d/three.min.js"); if (!window.THREE.GLTFLoader) await this._script("/local/house3d/GLTFLoader.js"); this._build(); } catch (e) { this._load.textContent = "не удалось загрузить three.js"; } } _build() { const T = window.THREE; const W = this._wrap.clientWidth || 900; const H = this._wrap.clientHeight || 520; this._scene = new T.Scene(); this._scene.background = null; this._scene.fog = new T.Fog(0x06090c, 40, 120); this._cam = new T.PerspectiveCamera(42, W / H, 0.1, 500); this._renderer = new T.WebGLRenderer({ antialias: true, alpha: true }); this._renderer.toneMapping = T.ACESFilmicToneMapping; this._renderer.toneMappingExposure = 1.15; this._renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.5)); this._renderer.setSize(W, H); this._renderer.outputEncoding = T.sRGBEncoding; this._renderer.toneMapping = T.ACESFilmicToneMapping; this._renderer.toneMappingExposure = 1.05; this._wrap.appendChild(this._renderer.domElement); this._amb = new T.AmbientLight(0xffffff, 0.22); this._scene.add(this._amb); this._hemi = new T.HemisphereLight(0xbcd6ee, 0x1a2028, 0.45); this._scene.add(this._hemi); const dir = new T.DirectionalLight(0xfff4e2, 1.1); this._sun = dir; dir.position.set(-24, 38, -18); this._scene.add(dir); const fill = new T.DirectionalLight(0x9cc4e8, 1.1); fill.position.set(26, 16, 26); this._scene.add(fill); const fill2 = new T.DirectionalLight(0xcfe0f0, 0.7); fill2.position.set(-10, 8, 30); this._scene.add(fill2); // земля + сетка const ground = new T.Mesh( new T.CircleGeometry(70, 64), new T.MeshStandardMaterial({ color: 0x0d1216, roughness: 1, metalness: 0 }), ); ground.rotation.x = -Math.PI / 2; ground.position.y = -0.02; this._scene.add(ground); this._rot = { y: -0.6, x: 0 }; this._pivot = new T.Group(); this._scene.add(this._pivot); const loader = new T.GLTFLoader(); loader.load( this._config.model, (gltf) => { const model = gltf.scene; // убираем землю и дорожку из GLB (в сцене свои) const drop = []; model.traverse((o) => { if (!o.isMesh) return; const n = (o.name || "").toLowerCase(); if (n === "plane" || n.includes("path") || n.includes("ground") || n === "plane_0") drop.push(o); o.castShadow = false; o.receiveShadow = false; }); drop.forEach((o) => o.parent && o.parent.remove(o)); const DOLLHOUSE = this._config.dollhouse !== false; const HIDE_INTERIOR = this._config.showInterior === false; const wallsFaded = true; if (DOLLHOUSE) { model.traverse((o) => { if (!o.isMesh) return; const n = o.name || ""; if (/^(r_north|r_south|tech_roof|porch_roof)$/.test(n) || n.indexOf("ceil_") === 0) { o.visible = false; } else if (wallsFaded && n.indexOf("ipart_") === 0 && o.material) { o.material.transparent = true; o.material.opacity = 0.32; o.material.depthWrite = false; o.material.needsUpdate = true; } }); } if (HIDE_INTERIOR) { model.traverse((o) => { if (!o.isMesh) return; const n = o.name || ""; if (n.indexOf("zone_") === 0) { o.material.transparent = true; o.material.opacity = 0; o.material.depthWrite = false; o.material.needsUpdate = true; } else if (/^(ceil_|ipart_|idoor_|ilamp_|ib_|ik_|io_|id_)/.test(n)) { o.visible = false; } }); } model.traverse((o) => { if (o.isMesh && o.name && o.name.indexOf("zone_") === 0) { const id = o.name.split(".")[0]; o.material = Array.isArray(o.material) ? o.material.map((m) => m.clone()) : o.material.clone(); this._zones[id] = o; } if (o.isMesh && o.material && /glass/i.test(o.material.name || "")) { o.material.transparent = true; o.material.opacity = 0.45; o.material.roughness = 0.15; o.material.metalness = 0.1; o.material.depthWrite = false; } }); model.traverse((o) => { if (o.isMesh && o.material) o.material.side = T.DoubleSide; }); this._pivot.add(model); this._model = model; // считаем габариты только по «домовым» мешам (без крупных плоскостей) model.updateWorldMatrix(true, true); const bb = new T.Box3(); model.traverse((o) => { if (!o.isMesh) return; const b = new T.Box3().setFromObject(o); const sz = b.getSize(new T.Vector3()); if (sz.x * sz.z > 400) return; bb.union(b); }); if (bb.isEmpty()) bb.setFromObject(model); const size = bb.getSize(new T.Vector3()); const center = bb.getCenter(new T.Vector3()); this._pivot.position.set(-center.x, -bb.min.y, -center.z); const dist = Math.max(size.x, size.z) * 1.05; this._cam.position.set(-dist * 1.05, size.y * 1.05 + 4.0, dist * 1.15); this._cam.lookAt(0, size.y * 0.28, 0); this._radius = dist; this._load.style.display = "none"; let meshCount = 0; model.traverse((o) => { if (o.isMesh) meshCount++; }); this._diag = "меши " + meshCount + " · " + size.x.toFixed(1) + "×" + size.y.toFixed(1) + "×" + size.z.toFixed(1) + " м" + " · камера " + this._cam.position.length().toFixed(1) + " м"; if (this._tm) this._tm.textContent = this._diag; // интерьер отдельным файлом (не ломает материалы экстерьера) const iloader = this._config.interior ? new T.GLTFLoader() : null; if (iloader) iloader.load(this._config.interior, (ig) => { const im = ig.scene; im.traverse((o) => { if (!o.isMesh) return; const mats = Array.isArray(o.material) ? o.material : [o.material]; for (const m of mats) { if (!m) continue; m.side = T.DoubleSide; if (typeof m.metalness === "number" && m.metalness > 0.15) m.metalness = 0.08; } if (o.name && o.name.indexOf("zone_") === 0) { const zid = o.name.split(".")[0]; o.material = Array.isArray(o.material) ? o.material.map((x) => x.clone()) : o.material.clone(); this._zones[zid] = o; } }); this._pivot.add(im); this._interior = im; this._dirty = true; }, undefined, (e) => { console.warn("interior", e); }); this._buildFromPlan(); this._buildFurniture(); this._ready = true; this._syncState(true); this._dirty = true; }, undefined, (err) => { this._load.textContent = "модель не загрузилась: " + (err && err.message ? err.message : "ошибка"); }, ); const el = this._renderer.domElement; el.style.touchAction = "none"; el.style.cursor = "grab"; this._drag = false; this._moved = 0; el.addEventListener("pointerdown", (e) => { this._drag = true; this._moved = 0; this._px = e.clientX; this._py = e.clientY; el.style.cursor = "grabbing"; }); el.addEventListener("pointerup", (e) => { this._drag = false; el.style.cursor = "grab"; if (this._moved < 14) this._click(e); }); el.addEventListener("pointermove", (e) => { if (!this._drag) return; const dx = e.clientX - this._px, dy = e.clientY - this._py; this._moved += Math.abs(dx) + Math.abs(dy); this._rot.y += dx * 0.005; this._rot.x = Math.max(-0.35, Math.min(0.35, this._rot.x + dy * 0.003)); this._px = e.clientX; this._py = e.clientY; this._dirty = true; }); el.addEventListener("wheel", (e) => { e.preventDefault(); const s = e.deltaY > 0 ? 1.07 : 0.93; this._cam.position.multiplyScalar(s); this._cam.position.clampLength(this._radius * 0.5, this._radius * 2.5); this._cam.lookAt(0, 1.5, 0); this._dirty = true; }, { passive: false }); new ResizeObserver(() => { const w = this._wrap.clientWidth, h = this._wrap.clientHeight; if (!w || !h) return; this._cam.aspect = w / h; this._cam.updateProjectionMatrix(); this._renderer.setSize(w, h); this._dirty = true; }).observe(this._wrap); const loop = () => { requestAnimationFrame(loop); if (this._pivot) { this._pivot.rotation.y = this._rot.y; this._pivot.rotation.x = this._rot.x; } if (!this._dirty) return; this._dirty = false; this._renderer.render(this._scene, this._cam); }; loop(); } _click(ev) { if (!this._hass || !this._ready || this._pending) return; const T = window.THREE; const r = this._renderer.domElement.getBoundingClientRect(); const p = new T.Vector2( ((ev.clientX - r.left) / r.width) * 2 - 1, -((ev.clientY - r.top) / r.height) * 2 + 1, ); const ray = new T.Raycaster(); ray.setFromCamera(p, this._cam); const hits = ray.intersectObject(this._model, true); if (!hits.length) return; let o = hits[0].object; let zone = null; while (o) { if (o.name && o.name.indexOf("zone_") === 0) { zone = o.name.split(".")[0]; break; } o = o.parent; } if (zone) { this._selectRoom(zone); return; } if (this._config.entity) this._toggle(); } // комнаты из зон, отредактированных на плане (localStorage) _buildFromPlan() { let saved = null; try { saved = JSON.parse(localStorage.getItem("house3d_room_px_v2") || "null"); } catch (e) { return false; } if (!saved || typeof saved !== "object" || !Object.keys(saved).length) return false; const X0 = 180, Y0 = 173, SX = 42.0, SY = 41.4, TER = 2.45, LY = 8.60; const ROOM_STYLE = { terrasa: { floor: 0xb08a5e, wall: 0x8a6a45 }, kitchen: { floor: 0x9fb08a, wall: 0xe6e1d6 }, spalnia: { floor: 0xb08a5e, wall: 0x5c6657 }, danina_komnata: { floor: 0xb08a5e, wall: 0xe6e1d6 }, kabinet: { floor: 0xb08a5e, wall: 0x3e4a56 }, sanuzel: { floor: 0x4a5a63, wall: 0x7fa8bd }, tualet: { floor: 0x4a5a63, wall: 0x7fa8bd }, garderob: { floor: 0xb08a5e, wall: 0xe6e1d6 }, kladovaia: { floor: 0x8d8a80, wall: 0xe6e1d6 }, koridor: { floor: 0x9aa88f, wall: 0xe6e1d6 }, prihozhaya: { floor: 0xb08a5e, wall: 0xe6e1d6 }, tambur: { floor: 0xb08a5e, wall: 0xe6e1d6 }, postirochnaia: { floor: 0x7fa8bd, wall: 0xe6e1d6 }, kryltso: { floor: 0xb08a5e, wall: 0x8a6a45 }, }; const COLORS = { terrasa: 0xb08a5e, kitchen: 0xb08a5e, spalnia: 0x8a7a68, danina_komnata: 0xb08a5e, kabinet: 0xb08a5e, sanuzel: 0x3a3d40, tualet: 0x3a3d40, garderob: 0xb08a5e, kladovaia: 0x3a3d40, koridor: 0x4a4a48, prihozhaya: 0x4a4a48, tambur: 0x3a3d40, postirochnaia: 0x3a3d40, kryltso: 0xb08a5e, }; const group = new T.Group(); group.name = "plan_rooms"; // hide baked: спрятать зоны из модели, чтобы не двоились for (const id of Object.keys(this._zones || {})) { const m = this._zones[id]; if (m) m.visible = false; } this._zones = {}; for (const id of Object.keys(saved)) { const px = saved[id]; if (!Array.isArray(px) || px.length < 3) continue; const pts = px.map(([x, y]) => new T.Vector2((x - X0) / SX - TER, LY - (y - Y0) / SY)); // пол const shape = new T.Shape(pts); const fg = new T.ExtrudeGeometry(shape, { depth: 0.05, bevelEnabled: false }); fg.rotateX(-Math.PI / 2); const fm = new T.Mesh(fg, new T.MeshStandardMaterial({ color: (ROOM_STYLE[id] || {}).floor || COLORS[id] || 0xb08a5e, roughness: 0.65, metalness: 0.0, transparent: true, opacity: 0.85, side: T.DoubleSide, })); fm.name = "zone_" + id; fm.position.y = 0.78; group.add(fm); this._zones[id] = fm; // стены по рёбрам for (let i = 0; i < pts.length; i++) { const a = pts[i], b = pts[(i + 1) % pts.length]; const len = a.distanceTo(b); if (len < 0.2) continue; const wg = new T.BoxGeometry(len + 0.06, 2.5, 0.06); const wm = new T.Mesh(wg, new T.MeshStandardMaterial({ color: (ROOM_STYLE[id] || {}).wall || 0xd8d2c4, roughness: 0.9, metalness: 0.0, side: T.DoubleSide, transparent: true, opacity: 0.38, depthWrite: false, })); // в three.js ось Z инвертирована относительно плана (как у пола) wm.position.set((a.x + b.x) / 2, 0.78 + 1.25, -(a.y + b.y) / 2); wm.rotation.y = -Math.atan2(b.y - a.y, b.x - a.x); group.add(wm); } } this._pivot.add(group); this._planRooms = group; return true; } // мебель из редактора (localStorage) — ручная расстановка владельца _buildFurniture() { let data = null; try { data = JSON.parse(localStorage.getItem("house3d_furniture_v1") || "null"); } catch (e) { return; } if (!data) return; const TYPES = { bath: [1.7, 0.75, 0.55, 0xf2f2ee], wc: [0.4, 0.45, 0.42, 0xf2f2ee], sink: [0.6, 0.45, 0.85, 0x8b5e3c], shower: [0.3, 0.3, 2.0, 0x16181a], shelf: [0.25, 0.9, 1.6, 0x8b5e3c], wardrobe: [1.0, 0.6, 2.2, 0xe6e1d6], bed: [1.6, 2.0, 0.5, 0x8e9a9e], desk: [1.6, 0.6, 0.75, 0xa9825a], chair: [0.45, 0.45, 0.45, 0x1e2024], sofa: [2.0, 0.9, 0.75, 0x4a3f45], tv: [1.2, 0.1, 1.1, 0x16181a], washer: [0.6, 0.6, 0.85, 0xf2f2ee], fridge: [0.65, 0.65, 1.8, 0x9aa3a8], stove: [0.6, 0.6, 0.85, 0x16181a], rug: [1.2, 0.8, 0.02, 0xc8b49a], door: [0.9, 0.06, 2.05, 0xf2f2ee], window: [1.2, 0.06, 1.1, 0xc9d4da], }; const group = new T.Group(); group.name = "owner_furniture"; for (const room of Object.keys(data)) { const list = data[room] || []; for (let i = 0; i < list.length; i++) { const it = list[i]; const t = TYPES[it.type]; if (!t) continue; const [dw, dh, h, col] = t; const w = it.w || dw, d = it.h || dh; const m = new T.Mesh( new T.BoxGeometry(w, h, d), new T.MeshStandardMaterial({ color: col, roughness: 0.75, metalness: 0.02 }), ); m.position.set(it.x + w / 2, 0.78 + h / 2, -(it.y + d / 2)); m.name = "fz_" + room + "_" + it.type + "_" + i; group.add(m); } } this._pivot.add(group); this._ownerFurniture = group; } _highlightZone(zone) { const zones = this._zones || {}; for (const id of Object.keys(zones)) { const mesh = zones[id]; if (!mesh || !mesh.material) continue; const mats = Array.isArray(mesh.material) ? mesh.material : [mesh.material]; for (const m of mats) { if (!m || !m.emissive) continue; if (id === zone) { m.emissive.setHex(0x2f7fe0); m.emissiveIntensity = 0.45; } else { m.emissive.setHex(0x000000); m.emissiveIntensity = 0; } m.needsUpdate = true; } } } _selectRoom(zone) { this._room = this._room === zone ? null : zone; if (this._roomNameEl) { this._roomNameEl.textContent = this._room ? (ROOM_NAMES[this._room] || this._room.replace("zone_", "")) : "обзор"; } this._highlightZone(this._room); document.dispatchEvent(new CustomEvent("house3d-room", { detail: { room: this._room } })); } async _toggle() { const _c0 = performance.now(); this._pending = true; this._optimistic = !this._visualOn; this._paint(); this._setChip("pending", "применяется…"); if (navigator.vibrate) navigator.vibrate(10); try { await this._hass.callService(this._config.domain, this._config.service, { entity_id: this._config.entity }); this._pending = false; this._lastClickMs = Math.round(performance.now() - _c0); this._setChip("ok", "применено"); setTimeout(() => this._setChip("", this._visualOn ? "включено" : "выключено"), 700); this._reconcile(this._config.entity, this._optimistic); } catch (e) { this._pending = false; this._optimistic = null; this._setChip("err", "не применено"); this._syncState(true); } } _setChip(kind, text) { this._chip.classList.toggle("pending", kind === "pending"); this._chip.classList.toggle("ok", kind === "ok"); this._chip.classList.toggle("err", kind === "err"); this._txt.textContent = text; } async _reconcile(entity, expected) { const deadline = Date.now() + 8000; while (Date.now() < deadline) { const st = this._hass && this._hass.states[entity]; if (st && (st.state === "on") === expected) { this._optimistic = null; this._syncState(true); return; } await new Promise((r) => setTimeout(r, 400)); } this._optimistic = null; this._syncState(true); } _paint() { const on = this._optimistic !== null && this._optimistic !== undefined ? this._optimistic : this._visualOn; this._visualOn = on; this._dot.classList.toggle("on", !!on); // подсветка модели при включении if (this._model) { this._model.traverse((o) => { if (o.isMesh && o.material && o.material.emissive) { o.material.emissive.setHex(0x000000); } }); } this._dirty = true; } _syncState() { if (!this._ready || !this._hass) return; const st = this._hass.states[this._config.entity]; const on = !!st && st.state === "on"; if (this._optimistic !== null && this._optimistic !== undefined && this._optimistic === on) this._optimistic = null; if (this._optimistic === null || this._optimistic === undefined) this._visualOn = on; this._paint(); if (!this._pending) this._txt.textContent = st ? (this._visualOn ? "включено" : "выключено") : "нет сущности"; } } customElements.define("house3d-card", House3dCard);