-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2217 lines (1873 loc) · 86 KB
/
Copy pathscript.js
File metadata and controls
2217 lines (1873 loc) · 86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as THREE from 'three';
import { STLLoader } from 'three/addons/loaders/STLLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// ============================================
// ГЛОБАЛЬНЫЕ ПЕРЕМЕННЫЕ
// ============================================
let editor;
let pyodide;
let pyodideReady = false;
let openscadInstance = null;
let openjscadReady = false;
let stlData = null;
let lastScadCode = null;
let scene, camera, renderer, controls, currentMesh = null;
let renderEngine = 'auto'; // 'auto', 'openscad', 'openjscad', 'parser'
let printModifiers = {
wallThickness: 2,
infillPercent: 20,
infillPattern: 'grid',
addSupports: false,
supportAngle: 45,
addBrim: false,
layerHeight: 0.2
};
const OPENROUTER_API_KEY = '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';
// Список моделей для попытки (в порядке приоритета, от лучших к быстрым/бесплатным)
const AI_MODELS = [
'google/gemini-3-pro-preview', // Флагман Google
'anthropic/claude-opus-4.5', // Мощный Claude
'openai/gpt-5.1-codex', // Специализированный кодер
'openai/gpt-5.1', // Общий GPT-5.1
'x-ai/grok-4.1-fast:free', // Быстрый и бесплатный
'kwaipilot/kat-coder-pro:free' // Специализированный бесплатный кодер
];
let currentAIModel = AI_MODELS[0];
const OPENROUTER_API_URL = 'https://openrouter.ai/api/v1/chat/completions';
// ============================================
// ИНИЦИАЛИЗАЦИЯ ПРИ ЗАГРУЗКЕ
// ============================================
document.addEventListener('DOMContentLoaded', () => {
console.log("🚀 DOM загружен. Инициализация приложения...");
console.log("✅ JSCAD НЕ ИСПОЛЬЗУЕТСЯ - только OpenSCAD WASM и простой парсер");
console.log("✅ Версия: 11.0 - OpenRouter Integration");
// Проверяем что JSCAD не загружен
if (typeof window.Modeling !== 'undefined' || typeof window.jscad !== 'undefined') {
console.warn("⚠ ВНИМАНИЕ: Обнаружены остатки JSCAD в window, но они НЕ используются!");
}
initNavigation();
initCodeEditor();
init3DViewer();
initPyodide();
initRenderEngineSelector();
initPrintModifiers();
initPresets(); // Добавлено
initUIImprovements(); // Добавлено
initEventListeners();
initOpenJSCAD();
updateStatus("ИНИЦИАЛИЗАЦИЯ...");
});
// ============================================
// НАВИГАЦИЯ
// ============================================
function initNavigation() {
const navItems = document.querySelectorAll('.nav-item');
const pages = document.querySelectorAll('.page');
navItems.forEach(item => {
item.addEventListener('click', (e) => {
e.preventDefault();
navItems.forEach(nav => nav.classList.remove('active'));
item.classList.add('active');
const targetId = item.getAttribute('data-target');
pages.forEach(page => page.classList.remove('active'));
const targetPage = document.getElementById(targetId);
if (targetPage) {
targetPage.classList.add('active');
if (targetId === 'generator' && editor) {
setTimeout(() => editor.refresh(), 10);
}
}
});
});
}
// ============================================
// РЕДАКТОР КОДА (CodeMirror)
// ============================================
function initCodeEditor() {
const editorElement = document.getElementById('code-editor');
if (editorElement) {
editor = CodeMirror.fromTextArea(editorElement, {
mode: 'python',
theme: 'neo',
lineNumbers: true,
indentUnit: 4,
lineWrapping: true
});
console.log("✓ CodeMirror инициализирован");
}
}
// ============================================
// 3D ПРОСМОТРЩИК (Three.js)
// ============================================
function init3DViewer() {
const container = document.getElementById('viewer-container');
if (!container) return;
// Очищаем контейнер
container.innerHTML = '';
// Создаем сцену
scene = new THREE.Scene();
scene.background = new THREE.Color(0xf0f0f0);
// Камера
// Увеличиваем Far plane до 10000, чтобы большие модели не обрезались
camera = new THREE.PerspectiveCamera(75, container.clientWidth / container.clientHeight, 0.1, 10000);
camera.position.set(50, 50, 50);
camera.lookAt(0, 0, 0);
// Рендерер
// logarithmicDepthBuffer помогает избежать мерцания на больших дистанциях
renderer = new THREE.WebGLRenderer({ antialias: true, logarithmicDepthBuffer: true });
renderer.setSize(container.clientWidth, container.clientHeight);
container.appendChild(renderer.domElement);
// Освещение
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(50, 50, 50);
scene.add(directionalLight);
// Управление камерой
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.screenSpacePanning = true;
controls.minDistance = 1;
controls.maxDistance = 5000;
controls.zoomSpeed = 0.8;
controls.rotateSpeed = 0.8;
controls.panSpeed = 0.8;
controls.enableDamping = true;
controls.dampingFactor = 0.1;
// Исправление скролла: предотвращаем прокрутку страницы при зуме
renderer.domElement.addEventListener('wheel', (e) => {
e.preventDefault();
}, { passive: false });
// Анимация
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
animate();
// Обработка изменения размера
const resizeObserver = new ResizeObserver(() => {
if (container && container.clientWidth > 0 && container.clientHeight > 0) {
camera.aspect = container.clientWidth / container.clientHeight;
camera.updateProjectionMatrix();
renderer.setSize(container.clientWidth, container.clientHeight);
}
});
resizeObserver.observe(container);
console.log("✓ 3D просмотрщик инициализирован");
}
// ============================================
// ОБНОВЛЕНИЕ МОДЕЛИ В 3D ПРОСМОТРЩИКЕ
// ============================================
function updateModel(stlBuffer) {
if (!scene || !renderer) {
console.error("3D просмотрщик не инициализирован");
return;
}
try {
// Проверяем валидность буфера
if (!stlBuffer || stlBuffer.byteLength < 84) {
throw new Error("Неверный формат STL файла");
}
// Удаляем старую модель
if (currentMesh) {
scene.remove(currentMesh);
if (currentMesh.geometry) currentMesh.geometry.dispose();
if (currentMesh.material) currentMesh.material.dispose();
currentMesh = null;
}
// Загружаем новую модель
const loader = new STLLoader();
const geometry = loader.parse(stlBuffer);
// Вычисляем нормали для лучшего отображения
geometry.computeVertexNormals();
// Вычисляем центр для центрирования модели
geometry.computeBoundingBox();
const center = new THREE.Vector3();
geometry.boundingBox.getCenter(center);
geometry.translate(-center.x, -center.y, -center.z);
// Создаем улучшенный материал
const material = new THREE.MeshPhongMaterial({
color: 0x0033ff,
specular: 0x222222,
shininess: 100,
flatShading: false,
side: THREE.DoubleSide
});
// Создаем mesh
currentMesh = new THREE.Mesh(geometry, material);
// ВАЖНО: Отключаем отсечение, чтобы модель не исчезала при вращении
currentMesh.frustumCulled = false;
scene.add(currentMesh);
// Добавляем сетку для лучшей ориентации
if (!scene.getObjectByName('gridHelper')) {
const gridHelper = new THREE.GridHelper(200, 20, 0x888888, 0xcccccc);
gridHelper.name = 'gridHelper';
scene.add(gridHelper);
}
// Автоматически настраиваем камеру
// BoundingBox уже вычислен выше
const box = geometry.boundingBox;
const size = new THREE.Vector3();
box.getSize(size);
const maxDim = Math.max(size.x, size.y, size.z);
const fov = camera.fov * (Math.PI / 180);
let cameraZ = Math.abs(maxDim / 2 / Math.tan(fov / 2));
// Добавляем запас
cameraZ *= 2.0;
// Ставим камеру под углом
const newPos = new THREE.Vector3(cameraZ, cameraZ, cameraZ);
camera.position.copy(newPos);
// Сбрасываем контролы и направляем на центр
controls.target.set(0, 0, 0);
controls.update();
camera.lookAt(0, 0, 0);
// Скрываем placeholder
const placeholder = document.getElementById('viewer-placeholder');
if (placeholder) placeholder.style.display = 'none';
console.log("✓ Модель загружена в 3D просмотрщик");
} catch (error) {
console.error("❌ Ошибка загрузки модели:", error);
const outputLog = document.getElementById('output-log');
if (outputLog) {
outputLog.innerText += "\n❌ Ошибка отображения модели: " + error.message;
}
const placeholder = document.getElementById('viewer-placeholder');
if (placeholder) {
placeholder.style.display = 'block';
placeholder.innerHTML = `<p>❌ Ошибка загрузки модели</p><p style="font-size: 0.7rem;">${error.message}</p>`;
}
}
}
// ============================================
// PYODIDE ИНИЦИАЛИЗАЦИЯ
// ============================================
async function initPyodide() {
const outputLog = document.getElementById('output-log');
if (!outputLog) return;
outputLog.innerText = "⚡ Инициализация Pyodide (Python в браузере)...";
console.log("=== Инициализация Pyodide ===");
try {
if (typeof loadPyodide === 'undefined') {
throw new Error("Pyodide не загружен");
}
pyodide = await loadPyodide();
console.log("✓ Pyodide загружен");
outputLog.innerText = "📦 Установка SolidPython2...";
await pyodide.loadPackage("micropip");
const micropip = pyodide.pyimport("micropip");
await micropip.install('solidpython2');
console.log("✓ SolidPython2 установлен");
// Проверяем импорт и настраиваем окружение для сложного кода
await pyodide.runPythonAsync(`
import solid2
import sys
import gc
# Увеличиваем лимиты для сложных моделей
sys.setrecursionlimit(5000) # Увеличиваем лимит рекурсии
# Настраиваем сборку мусора для больших моделей
gc.set_threshold(700, 10, 10)
print("SolidPython2 успешно загружен!")
print("Окружение настроено для сложных моделей")
`);
pyodideReady = true;
outputLog.innerText = "✅ Pyodide готов!\n✅ SolidPython2 загружен\n✅ Окружение настроено для сложных моделей\n⏳ Загрузка OpenSCAD WASM...";
console.log("✅ Pyodide готов и настроен для сложного кода");
// Инициализируем OpenSCAD WASM
setTimeout(() => initOpenSCAD(), 2000);
updateCompileButton();
} catch (err) {
console.error("❌ Ошибка инициализации Pyodide:", err);
outputLog.innerText = "❌ Ошибка: " + err.message + "\n\nОбновите страницу (Ctrl+Shift+R)";
updateStatus("ОШИБКА");
}
}
// ============================================
// OPENJSCAD ИНИЦИАЛИЗАЦИЯ
// ============================================
async function initOpenJSCAD() {
console.log("=== Инициализация OpenJSCAD ===");
try {
// Пытаемся загрузить OpenJSCAD модули
if (!window.jscadModeling) {
const modeling = await import('https://cdn.jsdelivr.net/npm/@jscad/modeling@2.11.0/+esm');
window.jscadModeling = modeling;
}
openjscadReady = true;
console.log("✓ OpenJSCAD готов к использованию");
updateStatus("OpenJSCAD готов");
} catch (err) {
console.warn("⚠ OpenJSCAD не загрузился:", err);
openjscadReady = false;
}
}
// ============================================
// OPENSCAD MANAGER (RESILIENT)
// ============================================
class OpenSCADManager {
constructor() {
this.worker = null;
this.isReady = false;
this.initPromise = null;
}
async init() {
if (this.initPromise) return this.initPromise;
this.initPromise = new Promise((resolve, reject) => {
const outputLog = document.getElementById('output-log');
try {
if (outputLog) outputLog.innerText += "\n⚙️ Запуск Worker ядра...";
console.log("Creating new OpenSCAD Worker...");
this.worker = new Worker('worker.js');
this.worker.onerror = (err) => {
console.error("❌ Worker Error:", err);
if (outputLog) outputLog.innerText += `\n❌ Worker Error: ${err.message}`;
this.isReady = false;
reject(err);
};
this.worker.onmessage = (e) => {
const { type, message } = e.data;
if (type === 'ready') {
console.log("✅ Worker ready");
this.isReady = true;
if (outputLog) outputLog.innerText += "\n✅ OpenSCAD готов!";
updateStatus("ГОТОВ");
updateCompileButton();
resolve();
} else if (type === 'log') {
// console.log("[Worker]", message);
}
};
} catch (err) {
reject(err);
}
});
return this.initPromise;
}
terminate() {
if (this.worker) {
this.worker.terminate();
this.worker = null;
this.isReady = false;
this.initPromise = null;
console.log("Worker terminated");
}
}
async render(scadCode) {
// Всегда перезапускаем воркер для чистоты памяти при сложных рендерах
// Или если он упал
if (!this.worker || !this.isReady) {
this.terminate();
await this.init();
}
return new Promise((resolve, reject) => {
if (!this.worker) return reject(new Error("Worker not initialized"));
const outputLog = document.getElementById('output-log');
this.worker.onmessage = (e) => {
const { type, blob, message } = e.data;
if (type === 'stl') {
resolve(blob);
} else if (type === 'error') {
// Если ошибка критическая - убиваем воркер
if (message.includes('CRITICAL') || message.includes('Worker Error')) {
this.terminate();
}
reject(new Error(message));
} else if (type === 'log') {
if (outputLog && message.startsWith('⚠')) {
outputLog.innerText += `\n${message}`;
}
// console.log("[Render]", message);
}
};
this.worker.onerror = (err) => {
this.terminate();
reject(new Error(`Worker crash: ${err.message}`));
};
this.worker.postMessage({ command: 'render', code: scadCode });
});
}
}
const scadManager = new OpenSCADManager();
async function initOpenSCAD() {
await scadManager.init();
}
// ============================================
// ============================================
// УЛУЧШЕННЫЙ КОМПИЛЯТОР: PYTHON → SCAD → STL
// Поддержка сложного и длинного кода
// ============================================
// Очистка состояния Pyodide перед компиляцией
function resetPyodideState() {
try {
pyodide.runPython(`
# Очистка пользовательских переменных
import sys
import gc
from io import StringIO
# Очищаем stdout/stderr
sys.stdout = StringIO()
sys.stderr = StringIO()
# Принудительная сборка мусора
gc.collect()
`);
console.log("✓ Состояние Pyodide очищено");
} catch (e) {
console.warn("⚠ Не удалось очистить состояние:", e);
}
}
// Выполнение Python кода с улучшенной обработкой ошибок
async function executePythonCode(code) {
const startTime = Date.now();
try {
// 1. Очищаем состояние перед выполнением
resetPyodideState();
// 2. Настраиваем перехват вывода
pyodide.runPython(`
import sys
from io import StringIO
import traceback
# Перехватываем stdout и stderr
_stdout_buffer = StringIO()
_stderr_buffer = StringIO()
sys.stdout = _stdout_buffer
sys.stderr = _stderr_buffer
# Функции для получения вывода
def get_stdout():
return _stdout_buffer.getvalue()
def get_stderr():
return _stderr_buffer.getvalue()
`);
// 3. Выполняем код
await pyodide.runPythonAsync(code);
// 4. Получаем результат
const stdout = pyodide.runPython("get_stdout()");
const stderr = pyodide.runPython("get_stderr()");
const executionTime = ((Date.now() - startTime) / 1000).toFixed(2);
console.log(`✓ Код выполнен за ${executionTime}с`);
if (stderr && stderr.trim()) {
console.warn("⚠ Предупреждения Python:", stderr);
}
return {
stdout: stdout || "",
stderr: stderr || "",
executionTime: executionTime
};
} catch (err) {
const executionTime = ((Date.now() - startTime) / 1000).toFixed(2);
console.error(`❌ Ошибка выполнения (${executionTime}с):`, err);
// Пытаемся получить stderr
let stderr = "";
try {
stderr = pyodide.runPython("get_stderr() if 'get_stderr' in dir() else ''");
} catch (e) {
console.warn("Не удалось получить stderr:", e);
}
throw {
message: err.message || "Неизвестная ошибка",
stderr: stderr,
executionTime: executionTime
};
}
}
async function runCompilation() {
const outputLog = document.getElementById('output-log');
const runBtn = document.getElementById('run-btn');
const downloadBtn = document.getElementById('download-stl-btn');
// Если OpenSCAD не готов, попробуем подождать (Auto-wait)
if (!pyodide || !pyodideReady) {
if (outputLog) {
outputLog.innerText = "⏳ Ожидание загрузки Pyodide...";
}
// Ждем Pyodide
for (let i = 0; i < 20; i++) {
if (pyodideReady) break;
await new Promise(r => setTimeout(r, 500));
}
}
// OpenSCAD Manager инициализируется лениво или при загрузке.
// Если он еще не готов, scadManager.render() сам его инициализирует.
if (!scadManager.isReady) {
console.log("ℹ OpenSCAD Manager инициализируется по требованию...");
}
const code = editor ? editor.getValue() : "";
if (!code || !code.trim()) {
if (outputLog) {
outputLog.innerText = "❌ Код пуст. Напишите Python код.";
}
return;
}
// Блокируем кнопки
if (runBtn) {
runBtn.disabled = true;
runBtn.innerText = "⚡ КОМПИЛЯЦИЯ...";
}
if (downloadBtn) downloadBtn.disabled = true;
showLoadingOverlay('⚡ Компиляция...'); // Показываем спиннер
const compilationStartTime = Date.now();
console.log("=== Начало компиляции ===");
console.log("Длина кода:", code.length, "символов");
console.log("Строк кода:", code.split('\n').length);
if (outputLog) {
outputLog.innerText = "⚡ Компиляция Python → SCAD...\n📊 Анализ кода...";
}
try {
// Предварительная валидация синтаксиса
if (outputLog) {
outputLog.innerText = "🔍 Предварительная проверка синтаксиса...";
}
const syntaxCheck = await validatePythonSyntax(code);
if (!syntaxCheck.valid) {
throw new Error(`Синтаксическая ошибка в строке ${syntaxCheck.line}:\n${syntaxCheck.error}\n\nИсправьте код и попробуйте снова.`);
}
console.log("✅ Предварительная валидация пройдена");
if (outputLog) {
outputLog.innerText = "✅ Синтаксис проверен\n⚡ Выполнение Python кода...";
}
// 1. Python → SCAD (улучшенная версия)
const result = await executePythonCode(code);
const scadCode = result.stdout.trim();
lastScadCode = scadCode;
if (!scadCode) {
// Проверяем, может быть код не выводит результат
let errorInfo = "";
if (result.stderr) {
errorInfo = `\n\n🐍 Python предупреждения:\n${result.stderr}`;
}
// Пытаемся найти объект в глобальной области видимости
try {
const hasModel = pyodide.runPython(`
# Проверяем наличие переменных с объектами
import sys
vars_with_objects = [name for name, obj in globals().items()
if hasattr(obj, '__class__') and not name.startswith('_')]
vars_with_objects
`);
if (hasModel && hasModel.length > 0) {
errorInfo += `\n\n💡 Обнаружены переменные: ${hasModel.join(', ')}`;
errorInfo += `\n💡 Добавьте в конец кода: print(scad_render(${hasModel[0]}))`;
}
} catch (e) {
console.log("Не удалось проверить переменные:", e);
}
throw new Error("Нет SCAD кода в выводе. Убедитесь что используете: print(scad_render(my_object))" + errorInfo);
}
console.log("✓ SCAD код сгенерирован");
console.log(" Длина SCAD:", scadCode.length, "символов");
console.log(" Строк SCAD:", scadCode.split('\n').length);
console.log(" Время выполнения Python:", result.executionTime, "с");
if (outputLog) {
outputLog.innerText = `✅ SCAD код сгенерирован!\n`;
outputLog.innerText += `📊 Строк SCAD: ${scadCode.split('\n').length}\n`;
outputLog.innerText += `⏱ Время Python: ${result.executionTime}с\n`;
if (result.stderr) {
outputLog.innerText += `⚠ Предупреждения: ${result.stderr.substring(0, 100)}...\n`;
}
outputLog.innerText += `\n⚡ Рендеринг SCAD → STL...`;
}
// 2. SCAD → STL
const stlStartTime = Date.now();
const stlOutput = await scadToStl(scadCode);
const stlTime = ((Date.now() - stlStartTime) / 1000).toFixed(2);
if (!stlOutput || stlOutput.length === 0) {
throw new Error("Не удалось сгенерировать STL из SCAD кода");
}
stlData = stlOutput instanceof Uint8Array ? stlOutput : new Uint8Array(stlOutput);
console.log("✓ STL сгенерирован");
console.log(" Размер STL:", stlData.length, "байт");
console.log(" Время рендеринга:", stlTime, "с");
// 3. Отображаем модель
if (outputLog) {
outputLog.innerText += `\n⚡ Загрузка в 3D просмотрщик...`;
}
updateModel(stlData.buffer);
// Скрываем placeholder
const placeholder = document.getElementById('viewer-placeholder');
if (placeholder) placeholder.style.display = 'none';
const totalTime = ((Date.now() - compilationStartTime) / 1000).toFixed(2);
if (outputLog) {
outputLog.innerText = `\n\n✅ УСПЕХ! Модель сгенерирована и отображена!\n`;
outputLog.innerText += `📊 Размер STL: ${(stlData.length / 1024).toFixed(2)} KB\n`;
outputLog.innerText += `🎯 Движок: ${getRenderEngineName(renderEngine)}\n`;
outputLog.innerText += `⏱ Общее время: ${totalTime}с (Python: ${result.executionTime}с, STL: ${stlTime}с)\n`;
outputLog.innerText += `💾 Нажмите 'СКАЧАТЬ STL' для сохранения`;
}
if (downloadBtn) downloadBtn.disabled = false;
const downloadScadBtn = document.getElementById('download-scad-btn');
if (downloadScadBtn) downloadScadBtn.disabled = false;
} catch (err) {
console.error("❌ Ошибка компиляции:", err);
const totalTime = ((Date.now() - compilationStartTime) / 1000).toFixed(2);
let errorMessage = err.message || "Неизвестная ошибка";
let pythonErrors = "";
// Добавляем информацию об ошибках Python
if (err.stderr) {
pythonErrors = `\n\n🐍 Python ошибки:\n${err.stderr}`;
} else {
// Пытаемся получить stderr из Pyodide
try {
const stderr = pyodide.runPython("get_stderr() if 'get_stderr' in dir() else ''");
if (stderr && stderr.trim()) {
pythonErrors = `\n\n🐍 Python ошибки:\n${stderr}`;
}
} catch (e) {
console.log("Не удалось получить stderr:", e);
}
}
if (outputLog) {
outputLog.innerText = `❌ Ошибка компиляции (${totalTime}с): ${errorMessage}${pythonErrors}\n\n`;
outputLog.innerText += `💡 ПОДСКАЗКИ:\n`;
outputLog.innerText += `- Используйте print(scad_render(my_object)) в конце кода\n`;
outputLog.innerText += `- Проверьте синтаксис Python\n`;
outputLog.innerText += `- Убедитесь что импортировали: from solid2 import *\n`;
outputLog.innerText += `- Для сложных моделей используйте функции и классы\n`;
outputLog.innerText += `- Проверьте что все переменные определены`;
}
} finally {
hideLoadingOverlay(); // Скрываем спиннер
if (runBtn) {
runBtn.disabled = false;
runBtn.innerText = "СКОМПИЛИРОВАТЬ()";
}
updateCompileButton();
}
}
// ============================================
// ВЫБОР ДВИЖКА РЕНДЕРИНГА
// ============================================
function initRenderEngineSelector() {
const selector = document.getElementById('render-engine-select');
if (!selector) return;
// Загружаем сохраненный выбор
const saved = localStorage.getItem('renderEngine');
const validEngines = ['auto', 'openscad', 'openscad-cloud', 'openjscad', 'cadhub', 'smart-scad', 'parser'];
if (saved && validEngines.includes(saved)) {
renderEngine = saved;
selector.value = saved;
}
// Обновляем при изменении
selector.addEventListener('change', (e) => {
renderEngine = e.target.value;
localStorage.setItem('renderEngine', renderEngine);
console.log(`🎯 Движок рендеринга изменен на: ${renderEngine}`);
updateStatus(`Движок: ${getRenderEngineName(renderEngine)}`);
});
console.log(`🎯 Движок рендеринга: ${getRenderEngineName(renderEngine)}`);
}
function getRenderEngineName(engine) {
const names = {
'auto': 'АВТО',
'openscad': 'OpenSCAD WASM',
'parser': 'ПРОСТОЙ ПАРСЕР'
};
return names[engine] || 'АВТО';
}
// ============================================
// SCAD → STL (МНОЖЕСТВЕННЫЕ МЕТОДЫ)
// ============================================
async function scadToStl(scadCode) {
console.log("=== SCAD → STL ===");
console.log(`🎯 Выбранный движок: ${getRenderEngineName(renderEngine)}`);
// Проверяем внешние компиляторы
const externalCompilers = ['openscad-cloud', 'cadhub', 'smart-scad'];
if (externalCompilers.includes(renderEngine)) {
console.log(`🌐 Открытие внешнего компилятора: ${getRenderEngineName(renderEngine)}`);
openExternalCompiler(scadCode, renderEngine);
// Показываем сообщение пользователю
const outputLog = document.getElementById('output-log');
if (outputLog) {
outputLog.innerText += `\n\n🌐 Внешний компилятор открыт в новой вкладке.\n📋 SCAD код сохранен в буфер обмена.\nВставьте код в редактор компилятора.`;
}
// Копируем SCAD код в буфер обмена
if (navigator.clipboard) {
navigator.clipboard.writeText(scadCode).then(() => {
console.log("✓ SCAD код скопирован в буфер обмена");
});
}
throw new Error("Внешний компилятор открыт. Используйте его для рендеринга.");
}
// OpenJSCAD обработка
if (renderEngine === 'openjscad') {
try {
console.log("🔄 Используем OpenJSCAD...");
return await scadToStlViaOpenJSCAD(scadCode);
} catch (err) {
console.error("❌ OpenJSCAD не сработал:", err);
throw new Error("OpenJSCAD ошибка: " + err.message);
}
}
// Основной режим: OpenSCAD WASM (через Manager)
// Используем его для 'openscad' и 'auto'
if (renderEngine === 'openscad' || renderEngine === 'auto') {
try {
console.log("🔄 Используем OpenSCAD WASM Manager...");
// Всегда используем менеджер, он сам разберется с инициализацией и перезапуском
const stlBlob = await scadManager.render(scadCode);
return stlBlob;
} catch (err) {
console.error("❌ OpenSCAD Manager Error:", err);
// Если выбран строго OpenSCAD - падаем
if (renderEngine === 'openscad') {
throw new Error("OpenSCAD рендеринг не удался: " + err.message);
}
// Если AUTO, идем к фоллбеку
console.warn("⚠ Переход на запасной парсер...");
}
}
// Fallback: Простой парсер
if (renderEngine === 'parser' || renderEngine === 'auto') {
console.log("⚠ Используем простой парсер (Fallback)...");
try {
return await scadToStlViaSimpleParser(scadCode);
} catch (err) {
console.error("❌ Простой парсер не сработал:", err);
throw new Error("Не удалось отрендерить модель ни одним способом.");
}
}
throw new Error(`Неизвестный движок рендеринга: ${renderEngine}`);
}
// OpenJSCAD метод
async function scadToStlViaOpenJSCAD(scadCode) {
console.log("=== OpenJSCAD рендеринг ===");
// Проверяем доступность OpenJSCAD
if (!window.jscadModeling) {
// Пытаемся загрузить
try {
const modeling = await import('https://cdn.jsdelivr.net/npm/@jscad/modeling@2.11.0/+esm');
window.jscadModeling = modeling;
openjscadReady = true;
} catch (err) {
throw new Error("OpenJSCAD не загружен. Проверьте интернет соединение.");
}
}
const { primitives, booleans, transforms, extrusions } = window.jscadModeling;
const { cube, sphere, cylinder } = primitives;
const { union, subtract, intersect } = booleans;
const { translate, rotate, scale } = transforms;
const { extrudeLinear, extrudeRotate } = extrusions;
try {
// Конвертируем SCAD код в OpenJSCAD JavaScript
// Это упрощенный парсер - работает только с базовыми примитивами
const jsCode = convertScadToOpenJSCAD(scadCode);
// Выполняем код
const mainFunction = new Function('cube', 'sphere', 'cylinder', 'union', 'subtract', 'intersect',
'translate', 'rotate', 'scale', 'extrudeLinear', 'extrudeRotate',
`return ${jsCode}`);
const geometry = mainFunction(cube, sphere, cylinder, union, subtract, intersect,
translate, rotate, scale, extrudeLinear, extrudeRotate);
if (!geometry) {
throw new Error("OpenJSCAD не вернул геометрию");
}
// Конвертируем геометрию в STL
const { serialize } = await import('https://cdn.jsdelivr.net/npm/@jscad/io@2.11.0/+esm');
const stlData = serialize({ binary: true }, geometry);
return new Uint8Array(stlData);
} catch (err) {
console.error("OpenJSCAD ошибка:", err);
throw new Error("OpenJSCAD не смог обработать SCAD код: " + err.message);
}
}
// Простая конвертация SCAD в OpenJSCAD JavaScript
function convertScadToOpenJSCAD(scadCode) {
// Упрощенный парсер - работает только с базовыми примитивами
let jsCode = scadCode;
// Заменяем cube() на cube()
jsCode = jsCode.replace(/cube\(\[([^\]]+)\]\)/g, (match, params) => {
const [x, y, z] = params.split(',').map(p => p.trim());
return `cube({ size: [${x}, ${y}, ${z}] })`;
});
// Заменяем sphere() на sphere()
jsCode = jsCode.replace(/sphere\(r=([^)]+)\)/g, (match, r) => {
return `sphere({ radius: ${r} })`;
});
// Заменяем cylinder() на cylinder()
jsCode = jsCode.replace(/cylinder\(r=([^,]+),\s*h=([^)]+)\)/g, (match, r, h) => {
return `cylinder({ radius: ${r}, height: ${h} })`;
});
// Заменяем union() на union()
jsCode = jsCode.replace(/union\(\)/g, 'union');
// Заменяем difference() на subtract()
jsCode = jsCode.replace(/difference\(\)/g, 'subtract');
// Заменяем translate() на translate()
jsCode = jsCode.replace(/translate\(\[([^\]]+)\]\)/g, (match, params) => {
const [x, y, z] = params.split(',').map(p => p.trim());
return `translate([${x}, ${y}, ${z}], `;
});
// Простая обертка
return `function main() { return ${jsCode}; } main()`;
}
// Простой парсер SCAD (fallback)
async function scadToStlViaSimpleParser(scadCode) {
console.log("Парсинг SCAD кода...");
// Парсим union() с несколькими цилиндрами (для вазы)
const unionMatch = scadCode.match(/union\s*\(\s*\)\s*\{([^}]+)\}/i);
if (unionMatch) {
const unionContent = unionMatch[1];
const cylinders = unionContent.match(/cylinder\s*\([^)]+\)/gi) || [];
if (cylinders.length > 0) {
console.log(`Найдено ${cylinders.length} цилиндров в union, генерируем вазу...`);
// Для вазы: base (r=15, h=5), body (r1=15, r2=20, h=30), rim (r=20, h=2)
// Генерируем комбинированную модель вазы
return generateVaseSTL();
}
}
// Ищем примитивы: cube, sphere, cylinder
const cubeMatch = scadCode.match(/cube\s*\(\s*(\[?\s*[\d.]+\s*(?:,\s*[\d.]+)?\s*(?:,\s*[\d.]+)?\s*\]?)\s*\)/i);
const sphereMatch = scadCode.match(/sphere\s*\(\s*r\s*=\s*([\d.]+)\s*\)/i);
const cylinderMatch = scadCode.match(/cylinder\s*\(\s*(?:r\s*=\s*)?([\d.]+)\s*(?:,\s*h\s*=\s*([\d.]+))?/i);
if (cubeMatch) {
const size = cubeMatch[1].replace(/[\[\]]/g, '').split(',').map(s => parseFloat(s.trim()) || 10);
const s = size.length === 1 ? [size[0], size[0], size[0]] : [size[0] || 10, size[1] || 10, size[2] || 10];
console.log("Генерируем куб:", s);
return generateCubeSTL(s[0], s[1], s[2]);
} else if (sphereMatch) {
const r = parseFloat(sphereMatch[1]) || 10;
console.log("Генерируем сферу, радиус:", r);
return generateSphereSTL(r);
} else if (cylinderMatch) {
const r = parseFloat(cylinderMatch[1]) || 10;
const h = cylinderMatch[2] ? parseFloat(cylinderMatch[2]) : 20;
console.log("Генерируем цилиндр, r:", r, "h:", h);
return generateCylinderSTL(r, h);
} else {
// Fallback: простой куб 10x10x10
console.log("Не найдено примитивов, генерируем куб по умолчанию");
return generateCubeSTL(10, 10, 10);