| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415 |
- /* app.js — логика интерактивной модели
- * "Приборы ночного видения и тепловизоры"
- * Загружается из index.html: <script src="app.js" defer></script>
- * Все ID элементов совпадают с разметкой index.html.
- */
- "use strict";
- (() => {
- /* ---------- Константы и DOM ---------- */
- const NV_W = 720;
- const NV_H = 405;
- const nvCanvas = document.getElementById("nvCanvas");
- const thermalCanvas = document.getElementById("thermalCanvas");
- if (!nvCanvas || !thermalCanvas) return;
- const nvCtx = nvCanvas.getContext("2d");
- const thermalCtx = thermalCanvas.getContext("2d");
- const gainInput = document.getElementById("gain");
- const gainOut = document.getElementById("gainOut");
- const luxInput = document.getElementById("lux");
- const luxOut = document.getElementById("luxOut");
- const irInput = document.getElementById("ir");
- const paletteInput = document.getElementById("palette");
- const spanInput = document.getElementById("span");
- const spanOut = document.getElementById("spanOut");
- const ambientInput = document.getElementById("ambient");
- const ambientOut = document.getElementById("ambientOut");
- const nvReadout = document.getElementById("nvReadout");
- const thermalReadout = document.getElementById("thermalReadout");
- const nvFoot = document.getElementById("nvFoot");
- const thermalFoot = document.getElementById("thermalFoot");
- const sceneHint = document.getElementById("sceneHint");
- const sceneSwitch = document.getElementById("sceneSwitch");
- /* ---------- Данные сцен ---------- */
- /* Каждый элемент: {type, x, y, w, h, temp(K), em(ε), refl, bg?} */
- const scenes = {
- forest: {
- title: "Ночной лес",
- hint: "Ночной лес: слабая освещённость, тёплые биологические объекты и источник с высокой температурой.",
- elements: [
- { type: "rect", x: 0.00, y: 0.00, w: 1.00, h: 0.42, temp: 255, em: 0.95, refl: 0.01, bg: true },
- { type: "rect", x: 0.00, y: 0.42, w: 1.00, h: 0.58, temp: 284, em: 0.96, refl: 0.12 },
- { type: "rect", x: 0.10, y: 0.24, w: 0.055, h: 0.76, temp: 279, em: 0.90, refl: 0.18 },
- { type: "ellipse", x: 0.035, y: 0.10, w: 0.20, h: 0.24, temp: 285, em: 0.94, refl: 0.08 },
- { type: "rect", x: 0.27, y: 0.30, w: 0.045, h: 0.70, temp: 279, em: 0.90, refl: 0.18 },
- { type: "ellipse", x: 0.21, y: 0.16, w: 0.17, h: 0.22, temp: 285, em: 0.94, refl: 0.08 },
- { type: "rect", x: 0.84, y: 0.22, w: 0.060, h: 0.78, temp: 279, em: 0.90, refl: 0.18 },
- { type: "ellipse", x: 0.77, y: 0.09, w: 0.20, h: 0.24, temp: 285, em: 0.94, refl: 0.08 },
- { type: "ellipse", x: 0.66, y: 0.54, w: 0.065, h: 0.065, temp: 310, em: 0.98, refl: 0.35 },
- { type: "rect", x: 0.665, y: 0.595, w: 0.055, h: 0.24, temp: 309, em: 0.98, refl: 0.34 },
- { type: "ellipse", x: 0.75, y: 0.64, w: 0.10, h: 0.11, temp: 305, em: 0.97, refl: 0.30 },
- { type: "ellipse", x: 0.43, y: 0.70, w: 0.06, h: 0.08, temp: 900, em: 0.90, refl: 0.05 },
- { type: "ellipse", x: 0.48, y: 0.74, w: 0.04, h: 0.05, temp: 780, em: 0.88, refl: 0.05 }
- ]
- },
- city: {
- title: "Город ночью",
- hint: "Город ночью: холодное небо, нагретые здания и дороги, горячий двигатель автомобиля и человек.",
- elements: [
- { type: "rect", x: 0.00, y: 0.00, w: 1.00, h: 0.38, temp: 258, em: 0.95, refl: 0.01, bg: true },
- { type: "rect", x: 0.00, y: 0.38, w: 1.00, h: 0.62, temp: 290, em: 0.96, refl: 0.10 },
- { type: "rect", x: 0.04, y: 0.16, w: 0.20, h: 0.52, temp: 285, em: 0.92, refl: 0.20 },
- { type: "rect", x: 0.29, y: 0.08, w: 0.18, h: 0.62, temp: 286, em: 0.92, refl: 0.20 },
- { type: "rect", x: 0.52, y: 0.20, w: 0.15, h: 0.48, temp: 284, em: 0.92, refl: 0.20 },
- { type: "rect", x: 0.73, y: 0.12, w: 0.23, h: 0.56, temp: 287, em: 0.92, refl: 0.20 },
- { type: "rect", x: 0.075, y: 0.25, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.155, y: 0.25, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.075, y: 0.39, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.155, y: 0.39, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.31, y: 0.23, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.39, y: 0.23, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.31, y: 0.41, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.39, y: 0.41, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.15, y: 0.78, w: 0.30, h: 0.09, temp: 300, em: 0.86, refl: 0.22 },
- { type: "rect", x: 0.19, y: 0.72, w: 0.18, h: 0.08, temp: 305, em: 0.88, refl: 0.24 },
- { type: "ellipse", x: 0.20, y: 0.70, w: 0.05, h: 0.04, temp: 360, em: 0.80, refl: 0.15 },
- { type: "ellipse", x: 0.79, y: 0.55, w: 0.06, h: 0.06, temp: 310, em: 0.98, refl: 0.35 },
- { type: "rect", x: 0.795, y: 0.59, w: 0.05, h: 0.24, temp: 309, em: 0.98, refl: 0.34 }
- ]
- },
- lab: {
- title: "Лаборатория",
- hint: "Лаборатория: ровный фон, горячая чашка, холодный лёд, электроника и человек.",
- elements: [
- { type: "rect", x: 0.00, y: 0.00, w: 1.00, h: 0.55, temp: 293, em: 0.94, refl: 0.35, bg: true },
- { type: "rect", x: 0.00, y: 0.55, w: 1.00, h: 0.45, temp: 295, em: 0.92, refl: 0.30 },
- { type: "rect", x: 0.08, y: 0.62, w: 0.84, h: 0.06, temp: 295, em: 0.90, refl: 0.30 },
- { type: "ellipse", x: 0.16, y: 0.51, w: 0.08, h: 0.10, temp: 350, em: 0.85, refl: 0.20 },
- { type: "rect", x: 0.17, y: 0.56, w: 0.06, h: 0.07, temp: 345, em: 0.84, refl: 0.20 },
- { type: "ellipse", x: 0.32, y: 0.57, w: 0.08, h: 0.05, temp: 273, em: 0.96, refl: 0.45 },
- { type: "rect", x: 0.55, y: 0.43, w: 0.18, h: 0.13, temp: 330, em: 0.86, refl: 0.18 },
- { type: "rect", x: 0.57, y: 0.45, w: 0.14, h: 0.09, temp: 335, em: 0.86, refl: 0.18 },
- { type: "ellipse", x: 0.78, y: 0.48, w: 0.06, h: 0.06, temp: 310, em: 0.98, refl: 0.35 },
- { type: "rect", x: 0.79, y: 0.53, w: 0.05, h: 0.22, temp: 309, em: 0.98, refl: 0.34 },
- { type: "rect", x: 0.90, y: 0.60, w: 0.06, h: 0.08, temp: 320, em: 0.88, refl: 0.20 }
- ]
- }
- };
- let activeScene = "forest";
- let rafId = null;
- /* ---------- Утилиты ---------- */
- const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
- function drawShape(ctx, el, color) {
- const x = el.x * NV_W;
- const y = el.y * NV_H;
- const w = el.w * NV_W;
- const h = el.h * NV_H;
- ctx.fillStyle = color;
- if (el.type === "rect") {
- ctx.fillRect(x, y, w, h);
- } else if (el.type === "ellipse") {
- ctx.beginPath();
- ctx.ellipse(x + w / 2, y + h / 2, Math.max(0.1, w / 2), Math.max(0.1, h / 2), 0, 0, Math.PI * 2);
- ctx.fill();
- }
- }
- /* ---------- ЭОП ---------- */
- function nvBrightness(el) {
- const gain = parseFloat(gainInput.value);
- const lux = parseFloat(luxInput.value);
- const irOn = irInput.checked ? 1 : 0;
- // Фотонный поток: внешняя освещённость + опциональная ИК-подсветка.
- // Отражение объекта refl играет роль albedo по отношению к падающему потоку.
- const photonFactor = lux * 200 + irOn * 2.0;
- let v = 0.045 + photonFactor * el.refl * gain;
- v = Math.pow(clamp(v, 0, 1), 0.72); // гамма-коррекция свечения экрана ЭОП
- return Math.round(v * 255);
- }
- function drawNV() {
- const scene = scenes[activeScene];
- nvCtx.fillStyle = "#010806";
- nvCtx.fillRect(0, 0, NV_W, NV_H);
- for (const el of scene.elements) {
- const g = nvBrightness(el);
- const r = Math.round(g * 0.22);
- const gg = Math.round(g);
- const b = Math.round(g * 0.42);
- drawShape(nvCtx, el, `rgb(${r},${gg},${b})`);
- }
- // Шум фотокатода / МКП (примерный визуальный эффект)
- nvCtx.save();
- nvCtx.globalCompositeOperation = "lighter";
- for (let i = 0; i < 2600; i++) {
- const x = Math.random() * NV_W;
- const y = Math.random() * NV_H;
- const a = Math.random() * 0.06;
- nvCtx.fillStyle = `rgba(120,255,180,${a})`;
- nvCtx.fillRect(x, y, 1, 1);
- }
- nvCtx.restore();
- // Строки развёртки (характерный вид ЭОП-изображения)
- nvCtx.save();
- nvCtx.globalAlpha = 0.08;
- nvCtx.strokeStyle = "#7dffb2";
- nvCtx.lineWidth = 1;
- for (let y = 0; y < NV_H; y += 4) {
- nvCtx.beginPath();
- nvCtx.moveTo(0, y + 0.5);
- nvCtx.lineTo(NV_W, y + 0.5);
- nvCtx.stroke();
- }
- nvCtx.restore();
- const gain = parseFloat(gainInput.value);
- const lux = parseFloat(luxInput.value);
- nvReadout.textContent =
- `E=${lux.toExponential(2)} лк · G=${gain.toFixed(2)}× · ИК=${irInput.checked ? "вкл" : "выкл"}`;
- nvFoot.textContent = irInput.checked
- ? "ИК-подсветка 850 нм добавляет фотоны ближнего ИК-диапазона; сильнее проявляются объекты с высоким отражением."
- : "Без ИК-подсветки яркость зависит от внешней освещённости и отражения объектов; в полной темноте сигнала нет.";
- }
- /* ---------- Тепловизор ---------- */
- function lerpStops(stops, t) {
- t = clamp(t, 0, 1);
- const n = stops.length - 1;
- const p = t * n;
- const i = Math.floor(p);
- const f = p - i;
- const a = stops[i];
- const b = stops[Math.min(n, i + 1)];
- return [
- Math.round(a[0] + (b[0] - a[0]) * f),
- Math.round(a[1] + (b[1] - a[1]) * f),
- Math.round(a[2] + (b[2] - a[2]) * f)
- ];
- }
- function paletteColor(name, t) {
- t = clamp(t, 0, 1);
- if (name === "whiteHot") {
- const v = Math.round(255 * t);
- return `rgb(${v},${v},${v})`;
- }
- if (name === "blackHot") {
- const v = Math.round(255 * (1 - t));
- return `rgb(${v},${v},${v})`;
- }
- let stops;
- if (name === "ironbow") {
- stops = [
- [0, 0, 0],
- [40, 0, 70],
- [140, 30, 20],
- [230, 120, 0],
- [255, 210, 40],
- [255, 255, 255]
- ];
- } else if (name === "rainbow") {
- stops = [
- [0, 0, 70],
- [0, 160, 255],
- [0, 220, 120],
- [255, 230, 0],
- [255, 80, 0],
- [255, 255, 255]
- ];
- } else {
- stops = [
- [20, 0, 30],
- [120, 0, 90],
- [220, 40, 20],
- [255, 160, 0],
- [255, 255, 180]
- ];
- }
- const [r, g, b] = lerpStops(stops, t);
- return `rgb(${r},${g},${b})`;
- }
- // Наблюдаемая ("радиационная") температура серого тела:
- // T_app = [ ε·T_obj⁴ + (1−ε)·T_amb⁴ ]^(1/4)
- function apparentTemperature(el, ambient) {
- const eps = clamp(el.em, 0.01, 1);
- const t4 = eps * Math.pow(el.temp, 4) + (1 - eps) * Math.pow(ambient, 4);
- return Math.pow(t4, 0.25);
- }
- function drawThermal() {
- const scene = scenes[activeScene];
- const ambient = parseFloat(ambientInput.value);
- const span = parseFloat(spanInput.value);
- const paletteName = paletteInput.value;
- thermalCtx.fillStyle = "#000";
- thermalCtx.fillRect(0, 0, NV_W, NV_H);
- const center = ambient + 10;
- const minT = center - span / 2;
- const maxT = center + span / 2;
- for (const el of scene.elements) {
- const baseTemp = el.bg ? ambient : el.temp;
- const elCalc = el.bg ? { ...el, temp: baseTemp } : el;
- const tApp = apparentTemperature(elCalc, ambient);
- const t = (tApp - minT) / Math.max(0.001, maxT - minT);
- drawShape(thermalCtx, el, paletteColor(paletteName, t));
- }
- // Сенсорный шум микроболометра
- thermalCtx.save();
- for (let i = 0; i < 3600; i++) {
- const x = Math.random() * NV_W;
- const y = Math.random() * NV_H;
- const a = Math.random() * 0.045;
- thermalCtx.fillStyle = `rgba(255,255,255,${a})`;
- thermalCtx.fillRect(x, y, 1, 1);
- }
- thermalCtx.restore();
- thermalReadout.textContent = `T_фона=${ambient} K · ΔT=${span} K · ${paletteName}`;
- thermalFoot.textContent =
- `Окно отображения: ${Math.round(minT)}–${Math.round(maxT)} K. Цвет зависит от ε, температуры объекта и фона.`;
- }
- /* ---------- Рендер ---------- */
- function render() {
- drawNV();
- drawThermal();
- }
- function scheduleRender() {
- if (rafId !== null) cancelAnimationFrame(rafId);
- rafId = requestAnimationFrame(() => {
- rafId = null;
- render();
- });
- }
- function updateOutputs() {
- gainOut.textContent = `${parseFloat(gainInput.value).toFixed(2)}×`;
- luxOut.textContent = `${parseFloat(luxInput.value).toFixed(4)} лк`;
- spanOut.textContent = `${spanInput.value} K`;
- ambientOut.textContent = `${ambientInput.value} K`;
- }
- function onControlsChange() {
- updateOutputs();
- scheduleRender();
- }
- /* ---------- Подписки ---------- */
- gainInput.addEventListener("input", onControlsChange);
- luxInput.addEventListener("input", onControlsChange);
- irInput.addEventListener("change", onControlsChange);
- paletteInput.addEventListener("change", onControlsChange);
- spanInput.addEventListener("input", onControlsChange);
- ambientInput.addEventListener("input", onControlsChange);
- if (sceneSwitch) {
- sceneSwitch.addEventListener("click", (event) => {
- const btn = event.target.closest("button[data-scene]");
- if (!btn) return;
- activeScene = btn.dataset.scene;
- for (const b of sceneSwitch.querySelectorAll("button")) {
- b.classList.toggle("active", b === btn);
- }
- if (sceneHint) sceneHint.textContent = scenes[activeScene].hint;
- scheduleRender();
- });
- }
- /* ---------- Квиз ---------- */
- const answers = {
- q1: "b",
- q2: "a",
- q3: "b"
- };
- const checkBtn = document.getElementById("checkQuiz");
- const resetBtn = document.getElementById("resetQuiz");
- const quizResult = document.getElementById("quizResult");
- if (checkBtn) {
- checkBtn.addEventListener("click", () => {
- let correct = 0;
- let answered = 0;
- for (const key of Object.keys(answers)) {
- const selected = document.querySelector(`input[name="${key}"]:checked`);
- if (selected) {
- answered++;
- if (selected.value === answers[key]) correct++;
- }
- }
- if (!quizResult) return;
- if (answered < 3) {
- quizResult.innerHTML = `Ответьте на все вопросы. Сейчас выбрано <strong>${answered}</strong> из 3.`;
- return;
- }
- if (correct === 3) {
- quizResult.innerHTML = "Верно: <strong>3/3</strong>. Вы корректно различаете принципы ЭОП и тепловизора.";
- } else if (correct === 2) {
- quizResult.innerHTML = "Результат: <strong>2/3</strong>. Один принцип стоит повторить: различие отражённого и собственного ИК-излучения.";
- } else if (correct === 1) {
- quizResult.innerHTML = "Результат: <strong>1/3</strong>. Вернитесь к блоку «Научная основа модели» и сравните ЭОП с тепловизором.";
- } else {
- quizResult.innerHTML = "Результат: <strong>0/3</strong>. Начните с ключевой идеи: ЭОП усиливает свет, тепловизор регистрирует тепловое ИК-излучение.";
- }
- });
- }
- if (resetBtn) {
- resetBtn.addEventListener("click", () => {
- for (const radio of document.querySelectorAll('#quiz input[type="radio"]')) {
- radio.checked = false;
- }
- if (quizResult) quizResult.textContent = "Выберите ответы и нажмите «Проверить».";
- });
- }
- /* ---------- Запуск ---------- */
- updateOutputs();
- render();
- // Плавный "живой" шум сенсоров
- setInterval(render, 140);
- /* ---------- PWA: регистрация service worker (если файл рядом) ---------- */
- if ("serviceWorker" in navigator) {
- window.addEventListener("load", () => {
- navigator.serviceWorker
- .register("sw.js")
- .catch(() => { /* тихо игнорируем отсутствие sw.js */ });
- });
- }
- })();
|