all repos — simplyrpg @ 05a250383b5037effb602fc3ca4d2bb1cdf4da90

Fork of https://github.com/harperd1/simplyRPG — multi-map VTT, token visibility, dark theme, stream HUD

index.html (view raw)

   1<!DOCTYPE html>
   2
   3<html lang="ru">
   4<head>
   5    <meta charset="utf-8">
   6    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
   7    <meta name="description" content="simplyRPG VTT — multi-map tabletop board, tokens with visibility toggle, reality density meter, and live GM notes in Player View.">
   8    <title>simplyRPG — rpg.peajack.net</title>
   9    <link rel="icon" href="assets/images/small-logo.png">
  10
  11    <!-- Bootstrap CSS -->
  12    <link href="./libraries/bootstrap/bootstrap.css" rel="stylesheet">
  13    <!-- Modern Dark VTT CSS -->
  14    <link rel="stylesheet" type="text/css" href="gmView.css">
  15</head>
  16
  17<body onload="init()" id="mainBody">
  18
  19<header class="topHeader">
  20    <div class="container d-flex align-items-center justify-content-between">
  21        <div class="d-flex align-items-center">
  22            <img src="assets/images/logo1-white.png" class="logo" alt="">
  23            <a class="topHeaderBrand" href="./">rpg.peajack.net</a>
  24        </div>
  25        <div class="d-flex align-items-center" style="gap: .5rem;">
  26            <span id="autosaveStatus" class="fieldLabel" style="margin-right: .35rem;" title="Фоновый автосейв в IndexedDB — сессия восстанавливается после F5"></span>
  27            <button type="button" class="btn-modern btn-modern-sm" onclick="clearCurrentScene()">Clear Map</button>
  28            <button type="button" class="btn-modern btn-modern-primary btn-modern-sm" onclick="createMirrorWindow()">Launch Player View</button>
  29        </div>
  30    </div>
  31</header>
  32
  33<main>
  34    <div class="container">
  35
  36        <!-- Top Controls Grid -->
  37        <div class="topToolbarGrid">
  38            <!-- Save / Load -->
  39            <section class="panelCard">
  40                <div class="panelCardTitle">Session Save / Load</div>
  41                <div class="toolbarRow">
  42                    <input type="text" name="saveName" id="saveName" placeholder="session" style="flex: 1 1 110px; min-width: 90px;">
  43                    <button id="save" type="button" class="btn-modern btn-modern-sm" onclick="saveCanvas()">Save</button>
  44                    <button id="load" type="button" class="btn-modern btn-modern-sm" onclick="loadCanvas()">Load</button>
  45                </div>
  46            </section>
  47
  48            <!-- Map Setup -->
  49            <section class="panelCard">
  50                <div class="panelCardTitle">Map &amp; Grid Setup</div>
  51                <div class="toolbarRow justify-content-between">
  52                    <div>
  53                        <label for="mapImageFile" class="buttonMimic btn-modern-sm">Import Map Image(s)</label>
  54                        <input type="file" accept="image/*" multiple name="mapImageFile" id="mapImageFile" onchange="loadMapImageFromButton(event)" class="fileUpload">
  55                    </div>
  56
  57                    <div class="fieldGroup">
  58                        <input type="checkbox" id="includeGrid" onchange="updateGridFromButton()">
  59                        <label for="includeGrid" style="margin: 0; cursor: pointer; font-size: .86rem;">Draw Grid</label>
  60                    </div>
  61
  62                    <div class="fieldStack" style="min-width: 155px;">
  63                        <span id="canvasScaleLabel" class="fieldLabel">Map Scale: 5px/ft</span>
  64                        <input type="range" min="1" max="15" value="5" id="canvasScale" oninput="updateCanvasScaleFromSlider()">
  65                    </div>
  66                </div>
  67            </section>
  68        </div>
  69
  70        <!-- Unified Map Workspace -->
  71        <section class="workspaceFrame">
  72            <!-- Scene / Map Switcher -->
  73            <div id="sceneBar" class="sceneBar">
  74                <div class="sceneTabs" id="sceneTabs"></div>
  75                <div class="sceneActions">
  76                    <button type="button" id="addSceneBtn" class="sceneActionBtn" title="Добавить новую карту" onclick="addEmptyScene()">+ Карта</button>
  77                    <button type="button" id="renameSceneBtn" class="sceneActionBtn" title="Переименовать текущую карту" onclick="renameCurrentScene()">✎</button>
  78                    <button type="button" id="deleteSceneBtn" class="sceneActionBtn" title="Удалить текущую карту" onclick="deleteCurrentScene()">×</button>
  79                </div>
  80            </div>
  81
  82            <!-- Canvas Mode & Brush -->
  83            <div class="upperMapSettings">
  84                <div class="btn-group btn-group-toggle" data-toggle="buttons">
  85                    <label class="btn btn-secondary active">
  86                        <input type="radio" id="circleMoving" onclick="circleMoving()" autocomplete="off" checked> Move
  87                    </label>
  88                    <label class="btn btn-secondary">
  89                        <input type="radio" id="measureMode" onclick="measureMode()" autocomplete="off"> Measure
  90                    </label>
  91                    <label class="btn btn-secondary">
  92                        <input type="radio" id="lineDrawing" onclick="lineDrawing()" autocomplete="off"> Draw
  93                    </label>
  94                    <label class="btn btn-secondary">
  95                        <input type="radio" onclick="lineErasing()" autocomplete="off"> Erase
  96                    </label>
  97                </div>
  98
  99                <div class="toolbarRow">
 100                    <div class="fieldGroup">
 101                        <span class="fieldLabel">Brush:</span>
 102                        <select name="drawSize" id="drawSize" class="dropdown">
 103                            <option value="2">Small</option>
 104                            <option value="5">Medium</option>
 105                            <option value="10">Large</option>
 106                        </select>
 107                        <select name="drawColor" id="drawColor" class="dropdown">
 108                            <option value="white">white</option>
 109                            <option value="yellow">yellow</option>
 110                            <option value="red">red</option>
 111                            <option value="blue">blue</option>
 112                            <option value="green">green</option>
 113                            <option value="black">black</option>
 114                        </select>
 115                    </div>
 116                </div>
 117            </div>
 118
 119            <!-- Encounter Canvas -->
 120            <div id='canvasHolder' class="centering">
 121                <canvas id="canvas" width="320" height="180"></canvas>
 122            </div>
 123
 124            <!-- Token Creator Bar -->
 125            <div class="lowerMapSettings">
 126                <button type="button" class="btn-modern btn-modern-primary btn-modern-sm" onclick="drawNewCircleFromButton()">+ Add Token</button>
 127
 128                <div class="fieldGroup">
 129                    <label for="circleShape" class="fieldLabel">Type:</label>
 130                    <select name="circleShape" id="circleShape" class="dropdown">
 131                        <option value="circle">Circle</option>
 132                        <option value="square">Square</option>
 133                        <option value="cone">Cone</option>
 134                        <option value="customCircle">Character Token</option>
 135                        <option value="custom">Custom</option>
 136                    </select>
 137                </div>
 138
 139                <div class="fieldGroup">
 140                    <label for="circleColor" class="fieldLabel">Color:</label>
 141                    <select name="circleColor" id="circleColor" class="dropdown">
 142                        <option value="red">Red</option>
 143                        <option value="green">Green</option>
 144                        <option value="blue">Blue</option>
 145                        <option value="black">Black</option>
 146                    </select>
 147                </div>
 148
 149                <div class="fieldStack" style="min-width: 120px;">
 150                    <span id="circleTransparencyLabel" class="fieldLabel">Opacity: 100%</span>
 151                    <input type="range" min="0" max="100" value="100" step="10" id="circleTransparency" oninput="updateCircleTransparencyLabel()">
 152                </div>
 153
 154                <div class="fieldStack" style="min-width: 120px;">
 155                    <span id="circleSizeLabel" class="fieldLabel">Size: 5ft</span>
 156                    <input type="range" min="2.5" max="50" value="5" step="2.5" id="circleSize" oninput="updateCircleSliderLabel()">
 157                </div>
 158            </div>
 159        </section>
 160
 161        <!-- Lower Two-Column Workspace: Token Manager + Player View HUD -->
 162        <div class="bottomPanelsGrid">
 163            <!-- Token Manager -->
 164            <section id='symbolMenu' class="tilePane scrollable">
 165                <div class="tileHeader">
 166                    <h6>Token Manager</h6>
 167                    <span class="fieldLabel">👁 скрывает в Player View</span>
 168                </div>
 169            </section>
 170
 171            <!-- Player View Broadcast Panel: Reality Density + GM Notes -->
 172            <section class="tilePane">
 173                <div class="tileHeader">
 174                    <h6>Трансляция в Player View</h6>
 175                    <button type="button" class="btn-modern btn-modern-sm" onclick="clearGMNotes()">Очистить текст</button>
 176                </div>
 177
 178                <!-- Reality Density Meter (Hume / Юм) -->
 179                <div class="humeCard">
 180                    <div class="humeHeader">
 181                        <span class="humeTitle">Плотность реальности</span>
 182                        <div class="humeReadout">
 183                            <span id="humeStatusBadge" class="humeStatus">Норма</span>
 184                            <span id="humeValueDisplay" class="humeValue">1.0 Юм</span>
 185                        </div>
 186                    </div>
 187                    <input type="range" id="humeSlider" min="0.5" max="5" step="0.1" value="1.0" style="width: 100%;" oninput="updateHumeFromSlider()">
 188                    <div class="humeScaleBarWrap">
 189                        <div id="humeScaleFillMask" class="humeScaleFillMask" style="width: 88.9%;"></div>
 190                    </div>
 191                    <div class="humeTicks">
 192                        <span>0.5 Юм</span>
 193                        <span>1.0 (норма)</span>
 194                        <span>2.5</span>
 195                        <span>5.0 Юм</span>
 196                    </div>
 197                </div>
 198
 199                <!-- GM Notes Broadcast -->
 200                <div class="notesFieldWrap">
 201                    <label for="gmBroadcastNotes" class="fieldLabel" style="margin-bottom: .3rem;">Заметки мастера (видны игрокам в Player View):</label>
 202                    <textarea id="gmBroadcastNotes" class="gmNotesTextarea" placeholder="Введите текст для игроков — описание локации, статус аномалии, условия сцены..." oninput="updateGMNotesFromInput()"></textarea>
 203                </div>
 204            </section>
 205        </div>
 206
 207    </div>
 208</main>
 209
 210</body>
 211
 212<!-- Import bootstrap javascript -->
 213<script src="./libraries/bootstrap/jquery-3.5.1.slim.min.js"></script>
 214<script src="./libraries/bootstrap/bootstrap.js"></script>
 215<!-- Import compression javascript -->
 216<script src="./libraries/compressor.min.js"></script>
 217<!-- Import simplyRPG JavaScript -->
 218<script src="./libraries/fakeBroadcastPolyfill.js"></script>
 219<script src="./libraries/easeljs.js"></script>
 220<script src="./libraries/canvasModule.js"></script>
 221<script src="./libraries/dynamicDivModule.js"></script>
 222
 223<script>
 224    let stage;
 225
 226    globs.scenes = [];
 227    globs.activeSceneIdx = 0;
 228    globs.gmNotes = "";
 229    globs.humeValue = 1.0;
 230    globs._autosaveReady = false;   // flips to true only after restoreAutosave() finishes
 231
 232    // ---------------------------------------------------------------------------
 233    // IndexedDB autosave: the whole session (all scenes, backgrounds, token
 234    // images, GM notes, Hume level) is written as a single record on every
 235    // state change (debounced), so an accidental F5 / tab close restores it.
 236    // Blobs are stored natively by IndexedDB — no base64 packing involved.
 237    // ---------------------------------------------------------------------------
 238    const AUTOSAVE_DB_NAME = 'simplyRPG';
 239    const AUTOSAVE_STORE = 'autosave';
 240    const AUTOSAVE_KEY = 'current';
 241    const AUTOSAVE_DEBOUNCE_MS = 500;
 242
 243    let autosaveTimer = null;
 244    let autosaveDB = null;
 245    let autosaveInFlight = null;
 246    let autosaveDirty = false;
 247
 248    function openAutosaveDB() {
 249        if (autosaveDB) return Promise.resolve(autosaveDB);
 250        return new Promise((resolve, reject) => {
 251            const req = indexedDB.open(AUTOSAVE_DB_NAME, 1);
 252            req.onupgradeneeded = function () {
 253                if (!req.result.objectStoreNames.contains(AUTOSAVE_STORE)) {
 254                    req.result.createObjectStore(AUTOSAVE_STORE);
 255                }
 256            };
 257            req.onsuccess = function () {
 258                autosaveDB = req.result;
 259                autosaveDB.onversionchange = function () {
 260                    autosaveDB.close();
 261                    autosaveDB = null;
 262                };
 263                resolve(autosaveDB);
 264            };
 265            req.onerror = function () { reject(req.error); };
 266            req.onblocked = function () { reject(new Error('IndexedDB open blocked')); };
 267        });
 268    }
 269
 270    function setAutosaveStatus(label) {
 271        const el = document.getElementById('autosaveStatus');
 272        if (el) el.textContent = label || '';
 273    }
 274
 275    function formatClock(ts) {
 276        const d = new Date(ts);
 277        const pad = function (n) { return String(n).padStart(2, '0'); };
 278        return pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());
 279    }
 280
 281    // Serialise the live board: active scene is captured from the canvas first,
 282    // the other scenes already hold their last captured state.
 283    function buildAutosaveSnapshot() {
 284        captureCurrentScene();
 285        return {
 286            version: 2,
 287            autosave: true,
 288            savedAt: Date.now(),
 289            activeSceneIdx: globs.activeSceneIdx,
 290            gmNotes: globs.gmNotes || "",
 291            humeValue: globs.humeValue !== undefined ? globs.humeValue : 1.0,
 292            scenes: globs.scenes.map(scene => ({
 293                name: scene.name,
 294                backgroundFile: scene.backgroundFile || null,
 295                tokenImages: scene.tokenImages || [],
 296                state: scene.state
 297            }))
 298        };
 299    }
 300
 301    function scheduleAutosave() {
 302        if (!globs._autosaveReady) return;
 303        if (autosaveTimer) clearTimeout(autosaveTimer);
 304        setAutosaveStatus('сохранение…');
 305        autosaveTimer = setTimeout(function () {
 306            autosaveTimer = null;
 307            saveAutosaveNow();
 308        }, AUTOSAVE_DEBOUNCE_MS);
 309    }
 310
 311    function saveAutosaveNow() {
 312        if (!globs._autosaveReady) return Promise.resolve();
 313        if (autosaveTimer) {
 314            clearTimeout(autosaveTimer);
 315            autosaveTimer = null;
 316        }
 317        // A write is already running: remember that state changed again and
 318        // run one more pass once it settles, so the newest state always lands.
 319        if (autosaveInFlight) {
 320            autosaveDirty = true;
 321            return autosaveInFlight;
 322        }
 323
 324        const snapshot = buildAutosaveSnapshot();
 325        autosaveInFlight = openAutosaveDB()
 326            .then(function (db) {
 327                return new Promise(function (resolve, reject) {
 328                    const tx = db.transaction(AUTOSAVE_STORE, 'readwrite');
 329                    tx.objectStore(AUTOSAVE_STORE).put(snapshot, AUTOSAVE_KEY);
 330                    tx.oncomplete = function () { resolve(); };
 331                    tx.onerror = function () { reject(tx.error); };
 332                    tx.onabort = function () { reject(tx.error); };
 333                });
 334            })
 335            .then(function () {
 336                setAutosaveStatus('автосейв ' + formatClock(snapshot.savedAt));
 337            })
 338            .catch(function (err) {
 339                setAutosaveStatus('автосейв недоступен');
 340                console.warn('Autosave failed:', err);
 341            })
 342            .then(function () {
 343                autosaveInFlight = null;
 344                if (autosaveDirty) {
 345                    autosaveDirty = false;
 346                    scheduleAutosave();
 347                }
 348            });
 349        return autosaveInFlight;
 350    }
 351
 352    // Fire any pending debounced write right now (pagehide / tab hidden).
 353    function flushAutosave() {
 354        if (!globs._autosaveReady) return;
 355        if (autosaveTimer) {
 356            clearTimeout(autosaveTimer);
 357            autosaveTimer = null;
 358            saveAutosaveNow();
 359        }
 360    }
 361
 362    function readAutosaveRecord(db) {
 363        return new Promise(function (resolve, reject) {
 364            const req = db.transaction(AUTOSAVE_STORE, 'readonly').objectStore(AUTOSAVE_STORE).get(AUTOSAVE_KEY);
 365            req.onsuccess = function () { resolve(req.result); };
 366            req.onerror = function () { reject(req.error); };
 367        });
 368    }
 369
 370    async function restoreAutosave() {
 371        globs._autosaveReady = false;
 372        try {
 373            const db = await openAutosaveDB();
 374            const snapshot = await readAutosaveRecord(db);
 375            if (snapshot && Array.isArray(snapshot.scenes) && snapshot.scenes.length > 0) {
 376                const scenes = snapshot.scenes.map(function (s, idx) {
 377                    return {
 378                        name: s.name || ("Карта " + (idx + 1)),
 379                        backgroundFile: s.backgroundFile || null,
 380                        tokenImages: Array.isArray(s.tokenImages) ? s.tokenImages : [],
 381                        state: s.state
 382                    };
 383                });
 384                activateSession(scenes, snapshot.activeSceneIdx, snapshot.gmNotes, snapshot.humeValue);
 385                setAutosaveStatus('восстановлено в ' + formatClock(snapshot.savedAt || Date.now()));
 386            } else {
 387                setAutosaveStatus('автосейв включён');
 388            }
 389        } catch (err) {
 390            setAutosaveStatus('автосейв недоступен');
 391            console.warn('Autosave restore failed:', err);
 392        } finally {
 393            globs._autosaveReady = true;
 394        }
 395    }
 396
 397    // Swap the whole session in and render the active scene (shared by the
 398    // .ttrpg loader and the IndexedDB restore).
 399    function activateSession(scenes, activeSceneIdx, gmNotes, humeValue) {
 400        globs.scenes = (scenes && scenes.length) ? scenes : [makeBlankScene("Карта 1")];
 401        globs.activeSceneIdx = Math.min(activeSceneIdx || 0, globs.scenes.length - 1);
 402        globs.gmNotes = gmNotes || "";
 403        const parsedHume = parseFloat(humeValue);
 404        globs.humeValue = isNaN(parsedHume) ? 1.0 : parsedHume;
 405        const notesEl = document.getElementById("gmBroadcastNotes");
 406        if (notesEl) notesEl.value = globs.gmNotes;
 407        renderHumeUI(globs.humeValue);
 408        restoreScene(globs.scenes[globs.activeSceneIdx]);
 409    }
 410
 411    function makeBlankScene(name) {
 412        return {
 413            name: name || ("Карта " + (globs.scenes.length + 1)),
 414            backgroundFile: null,
 415            tokenImages: [],
 416            state: {
 417                backgroundImageBoolean: false,
 418                canvasSize: [globs.canvasX || 640, globs.canvasY || 360],
 419                gridDrawnBoolean: false,
 420                mapScale: 5,
 421                circles: [],
 422                lines: [],
 423                measurer: null
 424            }
 425        };
 426    }
 427
 428    function init() {
 429        globs.windowLocation = "main";
 430        stage = new createjs.Stage("canvas");
 431        createjs.Touch.enable(stage);
 432        stage.mouseMoveOutside = true;
 433
 434        setupCanvas();
 435        circleMoving();
 436        broadcastChannel.bc.onmessage = handleCanvasUpdates;
 437        window.onresize = resizeCanvas;
 438
 439        globs.scenes = [makeBlankScene("Карта 1")];
 440        globs.activeSceneIdx = 0;
 441        renderSceneTabs();
 442        renderHumeUI(globs.humeValue);
 443
 444        // Autosave: flush pending writes when the tab is hidden or going away,
 445        // then pull the last session back from IndexedDB.
 446        window.addEventListener('pagehide', flushAutosave);
 447        document.addEventListener('visibilitychange', function () {
 448            if (document.visibilityState === 'hidden') flushAutosave();
 449        });
 450        restoreAutosave();
 451    }
 452
 453    function handleCanvasUpdates(event) {
 454        let broadcastMetadata = event.data[0];
 455        let broadcastData = event.data[1];
 456
 457        if (broadcastMetadata[2] == 'encounterMap') {
 458            applyBroadcast(broadcastData, broadcastMetadata[0], broadcastMetadata[1]);
 459        }
 460    }
 461
 462    function renderHumeUI(val) {
 463        const meta = formatHumeMeta(val);
 464        const slider = document.getElementById("humeSlider");
 465        if (slider) slider.value = meta.clamped.toFixed(1);
 466        const disp = document.getElementById("humeValueDisplay");
 467        if (disp) disp.textContent = meta.clamped.toFixed(1) + " Юм";
 468        const badge = document.getElementById("humeStatusBadge");
 469        if (badge) {
 470            badge.textContent = meta.label;
 471            badge.style.color = meta.color;
 472            badge.style.backgroundColor = meta.bg;
 473        }
 474        const mask = document.getElementById("humeScaleFillMask");
 475        if (mask) {
 476            mask.style.width = (100 - meta.pct).toFixed(1) + "%";
 477        }
 478    }
 479
 480    function updateHumeFromSlider() {
 481        const val = parseFloat(document.getElementById("humeSlider").value);
 482        globs.humeValue = isNaN(val) ? 1.0 : val;
 483        renderHumeUI(globs.humeValue);
 484        broadcastChannel.postMessage(['setHume', globs.humeValue]);
 485        scheduleAutosave();
 486    }
 487
 488    function updateGMNotesFromInput() {
 489        globs.gmNotes = document.getElementById("gmBroadcastNotes").value;
 490        broadcastChannel.postMessage(['setGMNotes', globs.gmNotes]);
 491        scheduleAutosave();
 492    }
 493
 494    function clearGMNotes() {
 495        const el = document.getElementById("gmBroadcastNotes");
 496        if (el) el.value = "";
 497        updateGMNotesFromInput();
 498    }
 499
 500    function broadcastHUDState() {
 501        broadcastChannel.postMessage(['setGMNotes', globs.gmNotes || ""]);
 502        broadcastChannel.postMessage(['setHume', globs.humeValue !== undefined ? globs.humeValue : 1.0]);
 503    }
 504
 505    function stripExtension(filename) {
 506        if (!filename) return "Карта";
 507        return filename.replace(/\.[^/.]+$/, "");
 508    }
 509
 510    function renderSceneTabs() {
 511        const container = document.getElementById("sceneTabs");
 512        if (!container) return;
 513        container.innerHTML = "";
 514
 515        globs.scenes.forEach((scene, idx) => {
 516            const btn = document.createElement("button");
 517            btn.type = "button";
 518            btn.className = "sceneTab" + (idx === globs.activeSceneIdx ? " active" : "");
 519            btn.dataset.sceneIdx = String(idx);
 520
 521            const nameSpan = document.createElement("span");
 522            nameSpan.textContent = scene.name;
 523            btn.appendChild(nameSpan);
 524
 525            const count = idx === globs.activeSceneIdx
 526                ? globs.circleHandles.filter(Boolean).length
 527                : (scene.state && scene.state.circles ? scene.state.circles.length : 0);
 528            if (count > 0) {
 529                const countSpan = document.createElement("span");
 530                countSpan.className = "sceneTabCount";
 531                countSpan.textContent = "(" + count + ")";
 532                btn.appendChild(countSpan);
 533            }
 534
 535            btn.onclick = function() {
 536                switchScene(idx);
 537            };
 538            container.appendChild(btn);
 539        });
 540
 541        const delBtn = document.getElementById("deleteSceneBtn");
 542        if (delBtn) {
 543            delBtn.disabled = globs.scenes.length <= 1;
 544        }
 545    }
 546
 547    function captureCurrentScene() {
 548        const scene = globs.scenes[globs.activeSceneIdx];
 549        if (!scene) return null;
 550
 551        const saveObject = saveCanvasState();
 552        const tokenImages = [];
 553        for (let i = 0; i < globs.circleHandles.length; i += 1) {
 554            const circleHandle = globs.circleHandles[i];
 555            if (!circleHandle) continue;
 556            const circle = circleHandle.namedSubElements.circle;
 557            if (circle.circleType === 'customCircle' || circle.circleType === 'custom') {
 558                const imgFile = circle.compressedImage || circle.imageFile || null;
 559                if (imgFile) {
 560                    tokenImages.push(imgFile);
 561                }
 562            }
 563        }
 564
 565        const bgFile = globs.imageSrc || scene.backgroundFile || null;
 566        saveObject.backgroundImageBoolean = Boolean(bgFile);
 567        scene.state = saveObject;
 568        scene.backgroundFile = bgFile;
 569        scene.tokenImages = tokenImages;
 570        return scene;
 571    }
 572
 573    function restoreScene(scene) {
 574        if (!scene) return;
 575
 576        _clearCanvas();
 577        broadcastChannel.postMessage(['clearCanvas']);
 578
 579        const prevCompression = globs.imageCompression;
 580        globs.imageCompression = false;
 581        try {
 582            if (scene.backgroundFile) {
 583                loadMapImage(scene.backgroundFile);
 584            }
 585            loadCanvasState(scene.state, scene.tokenImages || [], false);
 586        } finally {
 587            globs.imageCompression = prevCompression;
 588        }
 589
 590        broadcastPageElements();
 591        renderSceneTabs();
 592    }
 593
 594    function switchScene(idx) {
 595        if (idx < 0 || idx >= globs.scenes.length) return;
 596        if (idx === globs.activeSceneIdx) return;
 597
 598        captureCurrentScene();
 599        globs.activeSceneIdx = idx;
 600        restoreScene(globs.scenes[idx]);
 601        scheduleAutosave();
 602    }
 603
 604    function addEmptyScene() {
 605        captureCurrentScene();
 606        const nextScene = makeBlankScene("Карта " + (globs.scenes.length + 1));
 607        globs.scenes.push(nextScene);
 608        globs.activeSceneIdx = globs.scenes.length - 1;
 609        restoreScene(nextScene);
 610        scheduleAutosave();
 611    }
 612
 613    function renameCurrentScene() {
 614        const scene = globs.scenes[globs.activeSceneIdx];
 615        if (!scene) return;
 616        const nextName = window.prompt("Название карты:", scene.name);
 617        if (nextName && nextName.trim()) {
 618            scene.name = nextName.trim();
 619            renderSceneTabs();
 620            scheduleAutosave();
 621        }
 622    }
 623
 624    function deleteCurrentScene() {
 625        if (globs.scenes.length <= 1) return;
 626        const scene = globs.scenes[globs.activeSceneIdx];
 627        if (!window.confirm('Удалить карту "' + scene.name + '" и её токены?')) {
 628            return;
 629        }
 630        globs.scenes.splice(globs.activeSceneIdx, 1);
 631        if (globs.activeSceneIdx >= globs.scenes.length) {
 632            globs.activeSceneIdx = globs.scenes.length - 1;
 633        }
 634        restoreScene(globs.scenes[globs.activeSceneIdx]);
 635        scheduleAutosave();
 636    }
 637
 638    function clearCurrentScene() {
 639        clearCanvas();
 640        const scene = globs.scenes[globs.activeSceneIdx];
 641        if (scene) {
 642            scene.backgroundFile = null;
 643            scene.tokenImages = [];
 644            scene.state.backgroundImageBoolean = false;
 645            scene.state.circles = [];
 646            scene.state.lines = [];
 647            scene.state.measurer = null;
 648        }
 649        document.getElementById('includeGrid').checked = false;
 650        renderSceneTabs();
 651        scheduleAutosave();
 652    }
 653
 654    function loadMapImageFromButton(event) {
 655        const files = Array.from(event.target.files || []);
 656        if (!files.length) return;
 657
 658        files.forEach((file, i) => {
 659            if (i === 0) {
 660                const active = globs.scenes[globs.activeSceneIdx];
 661                if (/^Карта \d+$/.test(active.name)) {
 662                    active.name = stripExtension(file.name);
 663                }
 664                loadMapImage(file);
 665                broadcastChannel.postMessage(['loadMap', file]);
 666            } else {
 667                captureCurrentScene();
 668                const newScene = makeBlankScene(stripExtension(file.name));
 669                newScene.backgroundFile = file;
 670                newScene.state.backgroundImageBoolean = true;
 671                globs.scenes.push(newScene);
 672            }
 673        });
 674
 675        captureCurrentScene();
 676        renderSceneTabs();
 677        scheduleAutosave();
 678        event.target.value = "";
 679    }
 680
 681    function updateGridFromButton() {
 682        const checkboxValue = document.getElementById('includeGrid').checked;
 683        updateGrid(checkboxValue, document.getElementById("canvasScale").value);
 684        broadcastChannel.postMessage(['toggleGrid', checkboxValue, document.getElementById("canvasScale").value]);
 685        scheduleAutosave();
 686    }
 687
 688    function updateCanvasScaleFromSlider() {
 689        let pxPerFoot = document.getElementById("canvasScale").value;
 690        updateCanvasScale(pxPerFoot);
 691        updateCanvasScaleLabel();
 692        broadcastChannel.postMessage(['updateScale', pxPerFoot]);
 693        scheduleAutosave();
 694    }
 695
 696    function drawNewCircleFromButton() {
 697        let circleDiameter = document.getElementById('circleSize').value;
 698        let circleColor = document.getElementById("circleColor").value;
 699        let circleText = document.getElementById("circleText")
 700            ? document.getElementById("circleText").value
 701            : '';
 702        let circleType = document.getElementById("circleShape").value;
 703        let circleTransparency = document.getElementById("circleTransparency").value;
 704
 705        const colorConverter = {
 706            'red': `rgba(255,0,0,${circleTransparency / 100})`,
 707            'green': `rgba(0,128,0,${circleTransparency / 100})`,
 708            'blue': `rgba(0,0,255,${circleTransparency / 100})`,
 709            'black': `rgba(0,0,0,${circleTransparency / 100})`
 710        };
 711
 712        circleColor = colorConverter[circleColor];
 713
 714        drawNewCircle(circleDiameter, circleColor, circleText, 'main', circleType, "", null, true);
 715        broadcastChannel.postMessage(['newCircle', circleDiameter, circleColor, circleText, circleType]);
 716        renderSceneTabs();
 717        scheduleAutosave();
 718    }
 719
 720    function postLabels() {
 721        let message = ['labelUpdate', []];
 722        for (let i = 0; i < globs.circleHandles.length; i += 1) {
 723            let circleHandle = globs.circleHandles[i];
 724            if (circleHandle) {
 725                let label = circleHandle.namedSubElements.labelbox.value;
 726                message[1].push(label);
 727            } else {
 728                message[1].push(null);
 729            }
 730        }
 731        broadcastChannel.postMessage(message);
 732    }
 733
 734    function updateCircleSliderLabel() {
 735        let circleSize = document.getElementById("circleSize").value;
 736        document.getElementById("circleSizeLabel").innerHTML = `Size: ${circleSize}ft`;
 737    }
 738
 739    function updateCircleTransparencyLabel() {
 740        let circleOpacity = document.getElementById("circleTransparency").value;
 741        document.getElementById("circleTransparencyLabel").innerHTML = `Opacity: ${circleOpacity}%`;
 742    }
 743
 744    function updateCanvasScaleLabel() {
 745        let pxPerFoot = document.getElementById("canvasScale").value;
 746        document.getElementById("canvasScaleLabel").innerHTML = `Map Scale: ${pxPerFoot}px/ft`;
 747    }
 748
 749    function createMirrorWindow() {
 750        window.open("./encounterMap.html", "Encounter Map");
 751    }
 752
 753    function saveCanvasState() {
 754        let saveObject = {
 755            backgroundImageBoolean: Boolean(globs.imageSrc || globs.backgroundBitmap),
 756            canvasSize: [globs.canvasX, globs.canvasY],
 757            gridDrawnBoolean: document.getElementById('includeGrid').checked,
 758            mapScale: globs.pxPerFoot,
 759            circles: [],
 760            lines: [],
 761            measurer: null,
 762        };
 763
 764        for (let i = 0; i < globs.circleHandles.length; i += 1) {
 765            let circleHandle = globs.circleHandles[i];
 766            if (circleHandle) {
 767                let circle = circleHandle.namedSubElements.circle;
 768                let circleDiameter = circle.circleRadius * 2;
 769                let circleColor = circle.circleColor;
 770                let circleText = circle.circleText;
 771                let circleNotes = circleHandle.namedSubElements.notesBox.value;
 772                let circleX = circle.dragObject.x;
 773                let circleY = circle.dragObject.y;
 774                let circleType = circle.circleType;
 775                let circleRotation = circle.dragObject.rotation;
 776                let circleVisible = circle.visible !== false;
 777                let hasCustomImage = (circleType === 'customCircle' || circleType === 'custom')
 778                    && Boolean(circle.compressedImage || circle.imageFile);
 779
 780                saveObject.circles.push([
 781                    circleDiameter,
 782                    circleColor,
 783                    circleText,
 784                    circleNotes,
 785                    circleX,
 786                    circleY,
 787                    circleType,
 788                    circleRotation,
 789                    circleVisible,
 790                    hasCustomImage
 791                ]);
 792            }
 793        }
 794
 795        for (let i = 0; i < drawer.lineSegments.length; i += 1) {
 796            let lineSegment = drawer.lineSegments[i];
 797            if (!lineSegment) continue;
 798            saveObject.lines.push([
 799                lineSegment.startX,
 800                lineSegment.endX,
 801                lineSegment.startY,
 802                lineSegment.endY,
 803                lineSegment.width,
 804                lineSegment.color
 805            ]);
 806        }
 807
 808        if (measurer.currentLine) {
 809            saveObject.measurer = [
 810                measurer.currentLine.startX,
 811                measurer.currentLine.endX,
 812                measurer.currentLine.startY,
 813                measurer.currentLine.endY
 814            ];
 815        }
 816        return saveObject;
 817    }
 818
 819    function loadCanvasState(saveObject, tokenImages, syncBroadcast = true) {
 820        const scale = Number(saveObject.mapScale || 5);
 821        document.getElementById("canvasScale").value = scale;
 822        updateCanvasScale(scale);
 823        updateCanvasScaleLabel();
 824        if (syncBroadcast) {
 825            broadcastChannel.postMessage(['updateScale', scale]);
 826        }
 827
 828        document.getElementById('includeGrid').checked = Boolean(saveObject.gridDrawnBoolean);
 829        updateGrid(Boolean(saveObject.gridDrawnBoolean), scale);
 830        if (syncBroadcast) {
 831            broadcastChannel.postMessage(['toggleGrid', Boolean(saveObject.gridDrawnBoolean), scale]);
 832        }
 833
 834        const preSaveY = (saveObject.canvasSize && saveObject.canvasSize[1]) ? saveObject.canvasSize[1] : globs.canvasY;
 835        const loadRescale = globs.canvasY / preSaveY;
 836
 837        let imageIDX = 0;
 838        const circles = saveObject.circles || [];
 839        for (let i = 0; i < circles.length; i += 1) {
 840            const c = circles[i];
 841            const circleDiameter = c[0];
 842            const circleColor = c[1];
 843            const circleText = c[2];
 844            const circleNotes = c[3] || "";
 845            const circleX = c[4] * loadRescale;
 846            const circleY = c[5] * loadRescale;
 847            const circleType = c[6];
 848            const circleRotation = c[7] || 0;
 849            const circleVisible = c.length > 8 ? Boolean(c[8]) : true;
 850            const hasImage = c.length > 9
 851                ? Boolean(c[9])
 852                : (circleType === 'customCircle' || circleType === 'custom');
 853
 854            if (hasImage && tokenImages && tokenImages[imageIDX]) {
 855                const tokenImage = tokenImages[imageIDX];
 856                drawNewCircle(circleDiameter, circleColor, circleText, 'main', circleType, circleNotes, tokenImage, circleVisible);
 857                if (syncBroadcast) {
 858                    broadcastChannel.postMessage(['newCircle', circleDiameter, circleColor, circleText, circleType]);
 859                    broadcastChannel.postMessage(['manuallyAppendImage', i, tokenImage]);
 860                }
 861                imageIDX += 1;
 862            } else {
 863                drawNewCircle(circleDiameter, circleColor, circleText, 'main', circleType, circleNotes, null, circleVisible);
 864                if (syncBroadcast) {
 865                    broadcastChannel.postMessage(['newCircle', circleDiameter, circleColor, circleText, circleType]);
 866                }
 867            }
 868
 869            const circleHandle = globs.circleHandles[i];
 870            circleHandle.updateLocation(circleX, circleY);
 871            circleHandle.updateRotation(circleRotation);
 872            if (!circleVisible) {
 873                circleHandle.setVisibility(false);
 874            }
 875            if (syncBroadcast) {
 876                broadcastChannel.postMessage(['moveCircle', i, circleX, circleY]);
 877                broadcastChannel.postMessage(['newRotation', i, circleRotation]);
 878                broadcastChannel.postMessage(['setCircleVisibility', i, circleVisible]);
 879            }
 880        }
 881
 882        const lines = saveObject.lines || [];
 883        for (let i = 0; i < lines.length; i += 1) {
 884            const lineSegment = lines[i];
 885            const startX = lineSegment[0] * loadRescale;
 886            const endX = lineSegment[1] * loadRescale;
 887            const startY = lineSegment[2] * loadRescale;
 888            const endY = lineSegment[3] * loadRescale;
 889            const width = lineSegment[4];
 890            const color = lineSegment[5];
 891
 892            drawSingleLine(startX, endX, startY, endY, width, color);
 893            if (syncBroadcast) {
 894                broadcastChannel.postMessage(['drawLine', startX, endX, startY, endY, width, color]);
 895            }
 896        }
 897
 898        if (saveObject.measurer) {
 899            const startX = saveObject.measurer[0] * loadRescale;
 900            const endX = saveObject.measurer[1] * loadRescale;
 901            const startY = saveObject.measurer[2] * loadRescale;
 902            const endY = saveObject.measurer[3] * loadRescale;
 903
 904            drawSingleMeasurer(startX, endX, startY, endY);
 905            if (syncBroadcast) {
 906                broadcastChannel.postMessage(['drawMeasurer', startX, endX, startY, endY]);
 907            }
 908        }
 909    }
 910
 911    function saveCanvas() {
 912        captureCurrentScene();
 913
 914        const filesToSave = [];
 915        const fileStartIndexes = [0];
 916        const scenesPayload = globs.scenes.map(scene => {
 917            if (scene.backgroundFile) {
 918                filesToSave.push(scene.backgroundFile);
 919                fileStartIndexes.push(fileStartIndexes[fileStartIndexes.length - 1] + scene.backgroundFile.size);
 920            }
 921            const tokenImages = scene.tokenImages || [];
 922            for (let i = 0; i < tokenImages.length; i += 1) {
 923                const imgFile = tokenImages[i];
 924                if (imgFile) {
 925                    filesToSave.push(imgFile);
 926                    fileStartIndexes.push(fileStartIndexes[fileStartIndexes.length - 1] + imgFile.size);
 927                }
 928            }
 929            return {
 930                name: scene.name,
 931                state: scene.state,
 932                tokenImageCount: tokenImages.length
 933            };
 934        });
 935
 936        const payload = {
 937            version: 2,
 938            activeSceneIdx: globs.activeSceneIdx,
 939            gmNotes: globs.gmNotes || "",
 940            humeLevel: globs.humeValue !== undefined ? globs.humeValue : 1.0,
 941            fileStartIndexes: fileStartIndexes,
 942            scenes: scenesPayload
 943        };
 944
 945        const jsonString = JSON.stringify(payload).replace(/\//g, "\\u002f") + "//";
 946        const headerBytes = new TextEncoder().encode(jsonString);
 947        const parts = [headerBytes].concat(filesToSave);
 948
 949        let filename = document.getElementById("saveName").value.trim();
 950        if (!filename) {
 951            filename = 'session';
 952        }
 953
 954        const toSave = new File(parts, filename);
 955        const toSavePath = URL.createObjectURL(toSave);
 956        download(filename + '.ttrpg', toSavePath);
 957    }
 958
 959    function loadCanvas() {
 960        let element = document.createElement('input');
 961        element.setAttribute('type', 'file');
 962        element.setAttribute('accept', '.ttrpg');
 963        element.style.display = 'none';
 964        element.onchange = handleCanvasLoad;
 965        document.body.appendChild(element);
 966        element.click();
 967        document.body.removeChild(element);
 968    }
 969
 970    async function handleCanvasLoad(event) {
 971        const savedFile = event.target.files[0];
 972        if (!savedFile) return;
 973
 974        const buffer = await savedFile.arrayBuffer();
 975        const bytes = new Uint8Array(buffer);
 976        let borderIdx = -1;
 977        for (let i = 0; i < bytes.length - 1; i += 1) {
 978            if (bytes[i] === 0x2f && bytes[i + 1] === 0x2f) {
 979                borderIdx = i;
 980                break;
 981            }
 982        }
 983        if (borderIdx === -1) {
 984            alert("Некорректный формат файла .ttrpg");
 985            return;
 986        }
 987
 988        const jsonStr = new TextDecoder("utf-8").decode(bytes.subarray(0, borderIdx));
 989        const jsonContents = JSON.parse(jsonStr);
 990        const imageContents = savedFile.slice(borderIdx + 2, savedFile.size);
 991
 992        const savedImages = [];
 993        const starts = jsonContents.fileStartIndexes || [0];
 994        for (let i = 0; i < starts.length - 1; i += 1) {
 995            savedImages.push(imageContents.slice(starts[i], starts[i + 1]));
 996        }
 997        if (jsonContents.version !== 2 && starts.length > 0) {
 998            const lastStart = starts[starts.length - 1];
 999            if (lastStart < imageContents.size) {
1000                savedImages.push(imageContents.slice(lastStart, imageContents.size));
1001            }
1002        }
1003
1004        if (jsonContents.version === 2 && Array.isArray(jsonContents.scenes) && jsonContents.scenes.length > 0) {
1005            let offset = 0;
1006            const scenes = jsonContents.scenes.map((s, idx) => {
1007                let bg = null;
1008                if (s.state && s.state.backgroundImageBoolean && offset < savedImages.length) {
1009                    bg = savedImages[offset++];
1010                }
1011                const imgCount = s.tokenImageCount || 0;
1012                const tImgs = savedImages.slice(offset, offset + imgCount);
1013                offset += imgCount;
1014                return {
1015                    name: s.name || ("Карта " + (idx + 1)),
1016                    backgroundFile: bg,
1017                    tokenImages: tImgs,
1018                    state: s.state
1019                };
1020            });
1021            activateSession(scenes, jsonContents.activeSceneIdx, jsonContents.gmNotes, jsonContents.humeLevel);
1022        } else {
1023            let bg = null;
1024            let imgs = savedImages;
1025            if (jsonContents.backgroundImageBoolean && imgs.length > 0) {
1026                bg = imgs[0];
1027                imgs = imgs.slice(1);
1028            }
1029            const scenes = [{
1030                name: stripExtension(savedFile.name) || "Карта 1",
1031                backgroundFile: bg,
1032                tokenImages: imgs,
1033                state: jsonContents
1034            }];
1035            activateSession(scenes, 0, "", globs.humeValue);
1036        }
1037        scheduleAutosave();
1038    }
1039
1040    function download(filename, path) {
1041        var element = document.createElement('a');
1042        element.setAttribute('href', path);
1043        element.setAttribute('download', filename);
1044        element.style.display = 'none';
1045        document.body.appendChild(element);
1046        element.click();
1047        document.body.removeChild(element);
1048    }
1049</script>
1050
1051</html>