app.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /* app.js — логика интерактивной модели
  2. * "Приборы ночного видения и тепловизоры"
  3. * Загружается из index.html: <script src="app.js" defer></script>
  4. * Все ID элементов совпадают с разметкой index.html.
  5. */
  6. "use strict";
  7. (() => {
  8. /* ---------- Константы и DOM ---------- */
  9. const NV_W = 720;
  10. const NV_H = 405;
  11. const nvCanvas = document.getElementById("nvCanvas");
  12. const thermalCanvas = document.getElementById("thermalCanvas");
  13. if (!nvCanvas || !thermalCanvas) return;
  14. const nvCtx = nvCanvas.getContext("2d");
  15. const thermalCtx = thermalCanvas.getContext("2d");
  16. const gainInput = document.getElementById("gain");
  17. const gainOut = document.getElementById("gainOut");
  18. const luxInput = document.getElementById("lux");
  19. const luxOut = document.getElementById("luxOut");
  20. const irInput = document.getElementById("ir");
  21. const paletteInput = document.getElementById("palette");
  22. const spanInput = document.getElementById("span");
  23. const spanOut = document.getElementById("spanOut");
  24. const ambientInput = document.getElementById("ambient");
  25. const ambientOut = document.getElementById("ambientOut");
  26. const nvReadout = document.getElementById("nvReadout");
  27. const thermalReadout = document.getElementById("thermalReadout");
  28. const nvFoot = document.getElementById("nvFoot");
  29. const thermalFoot = document.getElementById("thermalFoot");
  30. const sceneHint = document.getElementById("sceneHint");
  31. const sceneSwitch = document.getElementById("sceneSwitch");
  32. /* ---------- Данные сцен ---------- */
  33. /* Каждый элемент: {type, x, y, w, h, temp(K), em(ε), refl, bg?} */
  34. const scenes = {
  35. forest: {
  36. title: "Ночной лес",
  37. hint: "Ночной лес: слабая освещённость, тёплые биологические объекты и источник с высокой температурой.",
  38. elements: [
  39. { type: "rect", x: 0.00, y: 0.00, w: 1.00, h: 0.42, temp: 255, em: 0.95, refl: 0.01, bg: true },
  40. { type: "rect", x: 0.00, y: 0.42, w: 1.00, h: 0.58, temp: 284, em: 0.96, refl: 0.12 },
  41. { type: "rect", x: 0.10, y: 0.24, w: 0.055, h: 0.76, temp: 279, em: 0.90, refl: 0.18 },
  42. { type: "ellipse", x: 0.035, y: 0.10, w: 0.20, h: 0.24, temp: 285, em: 0.94, refl: 0.08 },
  43. { type: "rect", x: 0.27, y: 0.30, w: 0.045, h: 0.70, temp: 279, em: 0.90, refl: 0.18 },
  44. { type: "ellipse", x: 0.21, y: 0.16, w: 0.17, h: 0.22, temp: 285, em: 0.94, refl: 0.08 },
  45. { type: "rect", x: 0.84, y: 0.22, w: 0.060, h: 0.78, temp: 279, em: 0.90, refl: 0.18 },
  46. { type: "ellipse", x: 0.77, y: 0.09, w: 0.20, h: 0.24, temp: 285, em: 0.94, refl: 0.08 },
  47. { type: "ellipse", x: 0.66, y: 0.54, w: 0.065, h: 0.065, temp: 310, em: 0.98, refl: 0.35 },
  48. { type: "rect", x: 0.665, y: 0.595, w: 0.055, h: 0.24, temp: 309, em: 0.98, refl: 0.34 },
  49. { type: "ellipse", x: 0.75, y: 0.64, w: 0.10, h: 0.11, temp: 305, em: 0.97, refl: 0.30 },
  50. { type: "ellipse", x: 0.43, y: 0.70, w: 0.06, h: 0.08, temp: 900, em: 0.90, refl: 0.05 },
  51. { type: "ellipse", x: 0.48, y: 0.74, w: 0.04, h: 0.05, temp: 780, em: 0.88, refl: 0.05 }
  52. ]
  53. },
  54. city: {
  55. title: "Город ночью",
  56. hint: "Город ночью: холодное небо, нагретые здания и дороги, горячий двигатель автомобиля и человек.",
  57. elements: [
  58. { type: "rect", x: 0.00, y: 0.00, w: 1.00, h: 0.38, temp: 258, em: 0.95, refl: 0.01, bg: true },
  59. { type: "rect", x: 0.00, y: 0.38, w: 1.00, h: 0.62, temp: 290, em: 0.96, refl: 0.10 },
  60. { type: "rect", x: 0.04, y: 0.16, w: 0.20, h: 0.52, temp: 285, em: 0.92, refl: 0.20 },
  61. { type: "rect", x: 0.29, y: 0.08, w: 0.18, h: 0.62, temp: 286, em: 0.92, refl: 0.20 },
  62. { type: "rect", x: 0.52, y: 0.20, w: 0.15, h: 0.48, temp: 284, em: 0.92, refl: 0.20 },
  63. { type: "rect", x: 0.73, y: 0.12, w: 0.23, h: 0.56, temp: 287, em: 0.92, refl: 0.20 },
  64. { type: "rect", x: 0.075, y: 0.25, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
  65. { type: "rect", x: 0.155, y: 0.25, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
  66. { type: "rect", x: 0.075, y: 0.39, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
  67. { type: "rect", x: 0.155, y: 0.39, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
  68. { type: "rect", x: 0.31, y: 0.23, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
  69. { type: "rect", x: 0.39, y: 0.23, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
  70. { type: "rect", x: 0.31, y: 0.41, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
  71. { type: "rect", x: 0.39, y: 0.41, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
  72. { type: "rect", x: 0.15, y: 0.78, w: 0.30, h: 0.09, temp: 300, em: 0.86, refl: 0.22 },
  73. { type: "rect", x: 0.19, y: 0.72, w: 0.18, h: 0.08, temp: 305, em: 0.88, refl: 0.24 },
  74. { type: "ellipse", x: 0.20, y: 0.70, w: 0.05, h: 0.04, temp: 360, em: 0.80, refl: 0.15 },
  75. { type: "ellipse", x: 0.79, y: 0.55, w: 0.06, h: 0.06, temp: 310, em: 0.98, refl: 0.35 },
  76. { type: "rect", x: 0.795, y: 0.59, w: 0.05, h: 0.24, temp: 309, em: 0.98, refl: 0.34 }
  77. ]
  78. },
  79. lab: {
  80. title: "Лаборатория",
  81. hint: "Лаборатория: ровный фон, горячая чашка, холодный лёд, электроника и человек.",
  82. elements: [
  83. { type: "rect", x: 0.00, y: 0.00, w: 1.00, h: 0.55, temp: 293, em: 0.94, refl: 0.35, bg: true },
  84. { type: "rect", x: 0.00, y: 0.55, w: 1.00, h: 0.45, temp: 295, em: 0.92, refl: 0.30 },
  85. { type: "rect", x: 0.08, y: 0.62, w: 0.84, h: 0.06, temp: 295, em: 0.90, refl: 0.30 },
  86. { type: "ellipse", x: 0.16, y: 0.51, w: 0.08, h: 0.10, temp: 350, em: 0.85, refl: 0.20 },
  87. { type: "rect", x: 0.17, y: 0.56, w: 0.06, h: 0.07, temp: 345, em: 0.84, refl: 0.20 },
  88. { type: "ellipse", x: 0.32, y: 0.57, w: 0.08, h: 0.05, temp: 273, em: 0.96, refl: 0.45 },
  89. { type: "rect", x: 0.55, y: 0.43, w: 0.18, h: 0.13, temp: 330, em: 0.86, refl: 0.18 },
  90. { type: "rect", x: 0.57, y: 0.45, w: 0.14, h: 0.09, temp: 335, em: 0.86, refl: 0.18 },
  91. { type: "ellipse", x: 0.78, y: 0.48, w: 0.06, h: 0.06, temp: 310, em: 0.98, refl: 0.35 },
  92. { type: "rect", x: 0.79, y: 0.53, w: 0.05, h: 0.22, temp: 309, em: 0.98, refl: 0.34 },
  93. { type: "rect", x: 0.90, y: 0.60, w: 0.06, h: 0.08, temp: 320, em: 0.88, refl: 0.20 }
  94. ]
  95. }
  96. };
  97. let activeScene = "forest";
  98. let rafId = null;
  99. /* ---------- Утилиты ---------- */
  100. const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
  101. function drawShape(ctx, el, color) {
  102. const x = el.x * NV_W;
  103. const y = el.y * NV_H;
  104. const w = el.w * NV_W;
  105. const h = el.h * NV_H;
  106. ctx.fillStyle = color;
  107. if (el.type === "rect") {
  108. ctx.fillRect(x, y, w, h);
  109. } else if (el.type === "ellipse") {
  110. ctx.beginPath();
  111. 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);
  112. ctx.fill();
  113. }
  114. }
  115. /* ---------- ЭОП ---------- */
  116. function nvBrightness(el) {
  117. const gain = parseFloat(gainInput.value);
  118. const lux = parseFloat(luxInput.value);
  119. const irOn = irInput.checked ? 1 : 0;
  120. // Фотонный поток: внешняя освещённость + опциональная ИК-подсветка.
  121. // Отражение объекта refl играет роль albedo по отношению к падающему потоку.
  122. const photonFactor = lux * 200 + irOn * 2.0;
  123. let v = 0.045 + photonFactor * el.refl * gain;
  124. v = Math.pow(clamp(v, 0, 1), 0.72); // гамма-коррекция свечения экрана ЭОП
  125. return Math.round(v * 255);
  126. }
  127. function drawNV() {
  128. const scene = scenes[activeScene];
  129. nvCtx.fillStyle = "#010806";
  130. nvCtx.fillRect(0, 0, NV_W, NV_H);
  131. for (const el of scene.elements) {
  132. const g = nvBrightness(el);
  133. const r = Math.round(g * 0.22);
  134. const gg = Math.round(g);
  135. const b = Math.round(g * 0.42);
  136. drawShape(nvCtx, el, `rgb(${r},${gg},${b})`);
  137. }
  138. // Шум фотокатода / МКП (примерный визуальный эффект)
  139. nvCtx.save();
  140. nvCtx.globalCompositeOperation = "lighter";
  141. for (let i = 0; i < 2600; i++) {
  142. const x = Math.random() * NV_W;
  143. const y = Math.random() * NV_H;
  144. const a = Math.random() * 0.06;
  145. nvCtx.fillStyle = `rgba(120,255,180,${a})`;
  146. nvCtx.fillRect(x, y, 1, 1);
  147. }
  148. nvCtx.restore();
  149. // Строки развёртки (характерный вид ЭОП-изображения)
  150. nvCtx.save();
  151. nvCtx.globalAlpha = 0.08;
  152. nvCtx.strokeStyle = "#7dffb2";
  153. nvCtx.lineWidth = 1;
  154. for (let y = 0; y < NV_H; y += 4) {
  155. nvCtx.beginPath();
  156. nvCtx.moveTo(0, y + 0.5);
  157. nvCtx.lineTo(NV_W, y + 0.5);
  158. nvCtx.stroke();
  159. }
  160. nvCtx.restore();
  161. const gain = parseFloat(gainInput.value);
  162. const lux = parseFloat(luxInput.value);
  163. nvReadout.textContent =
  164. `E=${lux.toExponential(2)} лк · G=${gain.toFixed(2)}× · ИК=${irInput.checked ? "вкл" : "выкл"}`;
  165. nvFoot.textContent = irInput.checked
  166. ? "ИК-подсветка 850 нм добавляет фотоны ближнего ИК-диапазона; сильнее проявляются объекты с высоким отражением."
  167. : "Без ИК-подсветки яркость зависит от внешней освещённости и отражения объектов; в полной темноте сигнала нет.";
  168. }
  169. /* ---------- Тепловизор ---------- */
  170. function lerpStops(stops, t) {
  171. t = clamp(t, 0, 1);
  172. const n = stops.length - 1;
  173. const p = t * n;
  174. const i = Math.floor(p);
  175. const f = p - i;
  176. const a = stops[i];
  177. const b = stops[Math.min(n, i + 1)];
  178. return [
  179. Math.round(a[0] + (b[0] - a[0]) * f),
  180. Math.round(a[1] + (b[1] - a[1]) * f),
  181. Math.round(a[2] + (b[2] - a[2]) * f)
  182. ];
  183. }
  184. function paletteColor(name, t) {
  185. t = clamp(t, 0, 1);
  186. if (name === "whiteHot") {
  187. const v = Math.round(255 * t);
  188. return `rgb(${v},${v},${v})`;
  189. }
  190. if (name === "blackHot") {
  191. const v = Math.round(255 * (1 - t));
  192. return `rgb(${v},${v},${v})`;
  193. }
  194. let stops;
  195. if (name === "ironbow") {
  196. stops = [
  197. [0, 0, 0],
  198. [40, 0, 70],
  199. [140, 30, 20],
  200. [230, 120, 0],
  201. [255, 210, 40],
  202. [255, 255, 255]
  203. ];
  204. } else if (name === "rainbow") {
  205. stops = [
  206. [0, 0, 70],
  207. [0, 160, 255],
  208. [0, 220, 120],
  209. [255, 230, 0],
  210. [255, 80, 0],
  211. [255, 255, 255]
  212. ];
  213. } else {
  214. stops = [
  215. [20, 0, 30],
  216. [120, 0, 90],
  217. [220, 40, 20],
  218. [255, 160, 0],
  219. [255, 255, 180]
  220. ];
  221. }
  222. const [r, g, b] = lerpStops(stops, t);
  223. return `rgb(${r},${g},${b})`;
  224. }
  225. // Наблюдаемая ("радиационная") температура серого тела:
  226. // T_app = [ ε·T_obj⁴ + (1−ε)·T_amb⁴ ]^(1/4)
  227. function apparentTemperature(el, ambient) {
  228. const eps = clamp(el.em, 0.01, 1);
  229. const t4 = eps * Math.pow(el.temp, 4) + (1 - eps) * Math.pow(ambient, 4);
  230. return Math.pow(t4, 0.25);
  231. }
  232. function drawThermal() {
  233. const scene = scenes[activeScene];
  234. const ambient = parseFloat(ambientInput.value);
  235. const span = parseFloat(spanInput.value);
  236. const paletteName = paletteInput.value;
  237. thermalCtx.fillStyle = "#000";
  238. thermalCtx.fillRect(0, 0, NV_W, NV_H);
  239. const center = ambient + 10;
  240. const minT = center - span / 2;
  241. const maxT = center + span / 2;
  242. for (const el of scene.elements) {
  243. const baseTemp = el.bg ? ambient : el.temp;
  244. const elCalc = el.bg ? { ...el, temp: baseTemp } : el;
  245. const tApp = apparentTemperature(elCalc, ambient);
  246. const t = (tApp - minT) / Math.max(0.001, maxT - minT);
  247. drawShape(thermalCtx, el, paletteColor(paletteName, t));
  248. }
  249. // Сенсорный шум микроболометра
  250. thermalCtx.save();
  251. for (let i = 0; i < 3600; i++) {
  252. const x = Math.random() * NV_W;
  253. const y = Math.random() * NV_H;
  254. const a = Math.random() * 0.045;
  255. thermalCtx.fillStyle = `rgba(255,255,255,${a})`;
  256. thermalCtx.fillRect(x, y, 1, 1);
  257. }
  258. thermalCtx.restore();
  259. thermalReadout.textContent = `T_фона=${ambient} K · ΔT=${span} K · ${paletteName}`;
  260. thermalFoot.textContent =
  261. `Окно отображения: ${Math.round(minT)}–${Math.round(maxT)} K. Цвет зависит от ε, температуры объекта и фона.`;
  262. }
  263. /* ---------- Рендер ---------- */
  264. function render() {
  265. drawNV();
  266. drawThermal();
  267. }
  268. function scheduleRender() {
  269. if (rafId !== null) cancelAnimationFrame(rafId);
  270. rafId = requestAnimationFrame(() => {
  271. rafId = null;
  272. render();
  273. });
  274. }
  275. function updateOutputs() {
  276. gainOut.textContent = `${parseFloat(gainInput.value).toFixed(2)}×`;
  277. luxOut.textContent = `${parseFloat(luxInput.value).toFixed(4)} лк`;
  278. spanOut.textContent = `${spanInput.value} K`;
  279. ambientOut.textContent = `${ambientInput.value} K`;
  280. }
  281. function onControlsChange() {
  282. updateOutputs();
  283. scheduleRender();
  284. }
  285. /* ---------- Подписки ---------- */
  286. gainInput.addEventListener("input", onControlsChange);
  287. luxInput.addEventListener("input", onControlsChange);
  288. irInput.addEventListener("change", onControlsChange);
  289. paletteInput.addEventListener("change", onControlsChange);
  290. spanInput.addEventListener("input", onControlsChange);
  291. ambientInput.addEventListener("input", onControlsChange);
  292. if (sceneSwitch) {
  293. sceneSwitch.addEventListener("click", (event) => {
  294. const btn = event.target.closest("button[data-scene]");
  295. if (!btn) return;
  296. activeScene = btn.dataset.scene;
  297. for (const b of sceneSwitch.querySelectorAll("button")) {
  298. b.classList.toggle("active", b === btn);
  299. }
  300. if (sceneHint) sceneHint.textContent = scenes[activeScene].hint;
  301. scheduleRender();
  302. });
  303. }
  304. /* ---------- Квиз ---------- */
  305. const answers = {
  306. q1: "b",
  307. q2: "a",
  308. q3: "b"
  309. };
  310. const checkBtn = document.getElementById("checkQuiz");
  311. const resetBtn = document.getElementById("resetQuiz");
  312. const quizResult = document.getElementById("quizResult");
  313. if (checkBtn) {
  314. checkBtn.addEventListener("click", () => {
  315. let correct = 0;
  316. let answered = 0;
  317. for (const key of Object.keys(answers)) {
  318. const selected = document.querySelector(`input[name="${key}"]:checked`);
  319. if (selected) {
  320. answered++;
  321. if (selected.value === answers[key]) correct++;
  322. }
  323. }
  324. if (!quizResult) return;
  325. if (answered < 3) {
  326. quizResult.innerHTML = `Ответьте на все вопросы. Сейчас выбрано <strong>${answered}</strong> из 3.`;
  327. return;
  328. }
  329. if (correct === 3) {
  330. quizResult.innerHTML = "Верно: <strong>3/3</strong>. Вы корректно различаете принципы ЭОП и тепловизора.";
  331. } else if (correct === 2) {
  332. quizResult.innerHTML = "Результат: <strong>2/3</strong>. Один принцип стоит повторить: различие отражённого и собственного ИК-излучения.";
  333. } else if (correct === 1) {
  334. quizResult.innerHTML = "Результат: <strong>1/3</strong>. Вернитесь к блоку «Научная основа модели» и сравните ЭОП с тепловизором.";
  335. } else {
  336. quizResult.innerHTML = "Результат: <strong>0/3</strong>. Начните с ключевой идеи: ЭОП усиливает свет, тепловизор регистрирует тепловое ИК-излучение.";
  337. }
  338. });
  339. }
  340. if (resetBtn) {
  341. resetBtn.addEventListener("click", () => {
  342. for (const radio of document.querySelectorAll('#quiz input[type="radio"]')) {
  343. radio.checked = false;
  344. }
  345. if (quizResult) quizResult.textContent = "Выберите ответы и нажмите «Проверить».";
  346. });
  347. }
  348. /* ---------- Запуск ---------- */
  349. updateOutputs();
  350. render();
  351. // Плавный "живой" шум сенсоров
  352. setInterval(render, 140);
  353. /* ---------- PWA: регистрация service worker (если файл рядом) ---------- */
  354. if ("serviceWorker" in navigator) {
  355. window.addEventListener("load", () => {
  356. navigator.serviceWorker
  357. .register("sw.js")
  358. .catch(() => { /* тихо игнорируем отсутствие sw.js */ });
  359. });
  360. }
  361. })();