File size: 37,457 Bytes
40d1bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3895b83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40d1bea
3895b83
40d1bea
 
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
<!DOCTYPE html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="description" content="Универсальная программа для открытия параметрических файлов Roblox UGC"><title>RUGC Studio — универсальный 3D-просмотрщик</title>
<script src="https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js"></script>
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js","three/addons/":"https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"}}</script>
<style>
:root{color-scheme:dark;font-family:Inter,ui-sans-serif,system-ui,Segoe UI,Arial,sans-serif;background:#080d18;color:#eaf1ff}*{box-sizing:border-box}body{margin:0;min-height:100vh}button,input,select{font:inherit}button{cursor:pointer;border:1px solid #34435d;background:#17263e;color:#eaf1ff;padding:10px 15px;border-radius:10px;font-weight:650;transition:background .2s,border-color .2s}button:hover:not(:disabled){background:#234065;border-color:#6483b1}button:disabled{opacity:.4;cursor:not-allowed}button.primary{background:#3885ea;border:1px solid #4c9dff;color:#fff}button.primary:hover{background:#1772ec}.topbar{display:flex;align-items:center;gap:16px;justify-content:space-between;padding:13px 20px;border-bottom:1px solid #24334a;background:#0b1324}.logo{display:flex;align-items:center;gap:11px}.brand-mark{display:grid;place-items:center;border-radius:11px;background:linear-gradient(135deg,#298afc,#7658ec);width:42px;height:42px;font-size:23px;font-weight:900}.brand-name{font-size:17px;font-weight:800;letter-spacing:.2px}.brand-sub{font-size:12px;color:#8599b9;margin-top:1px}.top-actions{display:flex;gap:9px;flex-wrap:wrap}.layout{display:grid;grid-template-columns:330px minmax(0,1fr) 282px;min-height:calc(100vh - 80px)}.panel{background:#0e1728;padding:18px;border-color:#25334a;overflow:auto}.left{border-right:1px solid #25334a}.right{border-left:1px solid #25334a}.panel h2{font-size:12px;letter-spacing:1.3px;text-transform:uppercase;color:#92a7c6;margin:0 0 14px}.panel h3{font-size:13px;font-weight:750;color:#d7e5fb;margin:0 0 15px}.control-section{padding:16px 0;border-top:1px solid #28344a}.control-section:first-child{border-top:0;padding-top:0}.control{margin:0 0 17px}.control-label{display:flex;align-items:center;justify-content:space-between;font-size:12px;color:#a8bad3;margin-bottom:9px}.control-value{font-size:11px;color:#d0e5ff}.control select,.hf-fields input{background:#121e32;border:1px solid #32425c;color:#eaf1ff;padding:10px;border-radius:9px;width:100%;outline:none}.control select:focus,.hf-fields input:focus{border-color:#579ce8}.control input[type=range]{width:100%;accent-color:#59a0ff}.control input[type=color]{appearance:none;background:transparent;border:none;padding:0;width:100%;height:35px;cursor:pointer}.control input[type=color]::-webkit-color-swatch{border-radius:8px;border:1px solid #56677b}.toggle-control .control-label{margin:0}.toggle-control input{width:18px;height:18px;accent-color:#4894f3}.viewwrap{min-width:0;display:flex;flex-direction:column;background:radial-gradient(ellipse at 47% 10%,#1a2c45,#070c16 68%);position:relative}.viewer-title{padding:20px 24px 13px;display:flex;align-items:flex-start;justify-content:space-between;gap:15px;z-index:1;pointer-events:none}.viewer-title h1{font-size:22px;margin:0 0 6px;letter-spacing:-.4px}.viewer-title p{color:#90a4bf;font-size:13px;margin:0}.tag{font-size:11px;background:#122a43;color:#8bc6ff;border:1px solid #2e5278;padding:6px 9px;border-radius:8px;white-space:nowrap}.viewport{position:relative;flex:1;min-height:450px;overflow:hidden}.viewport canvas{display:block;width:100%;height:100%}.empty{position:absolute;pointer-events:none;top:47%;left:50%;transform:translate(-50%,-50%);max-width:320px;text-align:center;background:#0a1422dc;padding:24px;border-radius:14px;border:1px dashed #426387;color:#b9cee8;font-size:13px;line-height:1.7}.empty .glyph{font-size:40px;margin-bottom:8px}.view-bottom{padding:10px 17px;display:flex;align-items:center;gap:16px;border-top:1px solid #233148;background:#0d1727cc;flex-wrap:wrap}.view-bottom label{display:flex;align-items:center;gap:7px;color:#a8b6c9;font-size:12px}.view-bottom input{accent-color:#59a0ff}.tiny-btn{font-size:12px;padding:6px 11px}.status{padding:12px 20px;font-size:12px;background:#101c2c;color:#a9c5e7;border-top:1px solid #203248;white-space:normal}.status[data-type=bad]{color:#ffadad;background:#321c25}.status[data-type=good]{color:#8fddba;background:#0c2924}.stats{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:0 0 19px}.stat{background:#121e31;border:1px solid #283953;padding:12px;border-radius:10px}.stat span{display:block;color:#93a8c2;font-size:11px;margin-bottom:7px}.stat strong{display:block;font-size:21px;font-weight:800}.stat strong.good{color:#91e4b6}.stat strong.bad{color:#ff9d97}.stat small{font-size:11px;color:#8ca0b7}.detail-box{background:#101d31;border:1px solid #29394f;border-radius:11px;padding:13px;margin:0 0 13px}.detail-box h4{margin:0 0 9px;font-size:12px;color:#c6d8f1}.detail-box p{font-size:12px;color:#91a7c2;line-height:1.55;margin:5px 0}.detail-box strong{color:#dce9fd;font-weight:600}.validation{font-size:12px;line-height:1.6;color:#a0b6d1}.validation[data-type=good]{color:#82d6ab}.validation[data-type=bad]{color:#ff9e9e}.note{font-size:11px;color:#7689a4;line-height:1.6}.hf-fields{display:flex;flex-direction:column;gap:8px}.hf-fields input{font-size:12px}.hf-fields button{font-size:12px}.error-detail{font-size:11px;color:#f9b5ac;white-space:pre-wrap;overflow-wrap:anywhere;background:#291c26;padding:12px;margin-top:12px;max-height:160px;overflow:auto}.muted{font-size:12px;color:#7e91ad;line-height:1.5}footer{font-size:11px;color:#7386a0;padding:12px 20px;background:#0b1423;border-top:1px solid #23334a}.file-chip{padding:5px 9px;border-radius:9px;border:1px solid #2c3f58;color:#99c0e9;font-size:11px;max-width:230px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}@media(max-width:1120px){.layout{grid-template-columns:275px minmax(0,1fr)}.right{grid-column:1/3;border-top:1px solid #23334a;border-left:none;display:grid;grid-template-columns:repeat(2,1fr);gap:14px}.right h2{grid-column:1/3}.right .stats{grid-column:1/3}}@media(max-width:670px){.topbar{flex-wrap:wrap}.top-actions{width:100%}.layout{display:flex;flex-direction:column}.left{order:2;border-right:0;border-top:1px solid #24354b}.viewwrap{order:1;min-height:460px}.right{order:3;display:block}.viewport{min-height:330px}.viewer-title{padding:14px}.viewer-title h1{font-size:18px}}@media(prefers-reduced-motion:reduce){*{transition:none!important}}
</style></head><body>
<header class="topbar"><div class="logo"><div class="brand-mark">R</div><div><div class="brand-name">RUGC Studio <span style="font-size:10px;color:#83b9fd">V1</span></div><div class="brand-sub">Универсальный редактор пакетов 3D-аксессуаров</div></div></div><div class="top-actions"><div class="file-chip" id="fileName">Файл не открыт</div><button class="primary" id="pickBtn">▣ Открыть .rugc</button><input type="file" hidden id="filePicker" accept=".rugc,.zip,application/zip"><button id="exportBtn" disabled>⇩ Экспорт ZIP</button></div></header>
<div class="layout"><aside class="panel left"><h2>Настройки аксессуара</h2><div id="controls"><div class="muted">Загрузи .rugc, чтобы появились настройки, созданные автором этого файла.<p>Разные файлы могут содержать разные детали, цвета, материалы и уровни качества.</p></div></div></aside>
<main class="viewwrap"><div class="viewer-title"><div><h1 id="assetTitle">Универсальный 3D-просмотрщик</h1><p id="assetSub">Формат RUGC · 3D-модели, текстуры и настройки в одном файле</p></div><div class="tag">3D VIEWPORT</div></div><div class="viewport" id="viewport"><div class="empty" id="emptyHint"><div class="glyph">⬡</div><strong>Перетащи сюда файл .rugc</strong><p>Или нажми «Открыть .rugc». Программа автоматически создаст элементы управления из файла.</p></div></div><div class="view-bottom"><label><input type="checkbox" checked id="gridToggle"> Сетка</label><label><input type="checkbox" id="axisToggle"> Оси XYZ</label><button class="tiny-btn" id="resetCamera">Центрировать</button><button class="tiny-btn" id="previewBtn" disabled>PNG-превью</button></div><div class="status" id="status">Готов к открытию файлов .rugc</div></main>
<aside class="panel right"><h2>Информация и проверки</h2><div class="stats"><div class="stat"><span>Треугольники</span><strong id="triCount">—</strong><small>лимит: <span id="triLimit">—</span></small></div><div class="stat"><span>Детали</span><strong id="partCount">—</strong><small>реальные 3D-меши</small></div></div><div class="detail-box"><h4>Габариты XYZ</h4><p id="sizeStats">—</p><h4>Геометрия</h4><div class="validation" id="validation">Нет модели</div><p id="validationNote" class="note"></p></div><div id="assetDetails" hidden class="detail-box"><h4>Информация о файле</h4><p id="description"></p><p>Attachment: <strong id="attachment"></strong></p></div><div class="detail-box"><h4>Открыть из Hugging Face Dataset</h4><p>Только публичный Dataset; может потребоваться открыть файл локально из-за CORS.</p><div class="hf-fields"><input id="hfRepo" placeholder="автор/имя-датасета" aria-label="Hugging Face Dataset ID"><input id="hfPath" placeholder="examples/example.rugc" aria-label="Путь к файлу внутри датасета"><button id="hfLoad">Загрузить из Dataset</button></div></div><div class="note">Файл .rugc — архив ZIP с описанием параметров, моделями и текстурами. Код из загруженного файла не запускается.</div><pre id="errorDetail" class="error-detail" hidden></pre></aside></div>
<footer>RUGC v1 · Произвольные 3D-аксессуары · Несколько уровней качества · Программная проверка ≠ модерация Roblox</footer>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { OBJLoader } from 'three/addons/loaders/OBJLoader.js';
import { OBJExporter } from 'three/addons/exporters/OBJExporter.js';

const $ = (id) => document.getElementById(id);
const addText = (el,text,cls) => { const n=document.createElement('div'); n.textContent=text; if(cls)n.className=cls; el.append(n); return n; };
const state = {zip:null,manifest:null,packageName:'', parts:new Map(), textureURLs:new Map(), textures:new Map(), controls:{},quality:null,buildToken:0, activeFile:'', errors:[]};
const MAX_ARCHIVE = 100 * 1024 * 1024;
const MAX_FILE = 35 * 1024 * 1024;
const MAX_PARTS = 80;
const MAX_CONTROLS = 120;
const loader = new OBJLoader();
const exporter = new OBJExporter();
let scene,renderer,camera,orbit,assembly,grid,axes;

function setStatus(msg,type='info') {$('status').textContent=msg;$('status').dataset.type=type;}
function safeId(s) {return typeof s==='string' && /^[a-zA-Z0-9][a-zA-Z0-9_\-]{0,63}$/.test(s);}
function safePath(s) {return typeof s==='string' && s.length<210 && !s.startsWith('/') && !s.includes('\\') && !s.split('/').some(x=>x==='..'||x==='') && /\.(obj|png|jpg|jpeg|webp)$/i.test(s);}
function bounded(v,min,max,def) {let n=Number(v);return Number.isFinite(n)?Math.min(max,Math.max(min,n)):def;}
function showValue(v,type) {return type==='range'? Number(v).toFixed(2).replace(/\.00$/,''):String(v);}
function isObjPath(path) {return safePath(path)&&path.toLowerCase().endsWith('.obj');}

function init3D() {
 scene=new THREE.Scene();scene.background=new THREE.Color('#0b111e');
 camera=new THREE.PerspectiveCamera(38, 1,.025,150);camera.position.set(3.5,2.3,4.6);
 renderer=new THREE.WebGLRenderer({antialias:true,preserveDrawingBuffer:true}); renderer.setPixelRatio(Math.min(devicePixelRatio||1,2));renderer.setSize(480,420);renderer.outputColorSpace=THREE.SRGBColorSpace;renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.55;
 $('viewport').appendChild(renderer.domElement);
 orbit=new OrbitControls(camera,renderer.domElement);orbit.enableDamping=true;orbit.dampingFactor=.065;orbit.target.set(0,.1,0);
 const hemi=new THREE.HemisphereLight(0xdce9ff,0x192636,2.25);scene.add(hemi);
 const k=new THREE.DirectionalLight(0xffffff,3.4);k.position.set(-2,5,4);scene.add(k);
 const fill=new THREE.DirectionalLight(0xa9cfff,2.2);fill.position.set(4,1,-3);scene.add(fill);
 grid=new THREE.GridHelper(12,28,0x283b55,0x172337);grid.position.y=-1.45;scene.add(grid);
 axes=new THREE.AxesHelper(1.5);axes.visible=false;scene.add(axes);
 assembly=new THREE.Group();assembly.name='RUGC_asset';scene.add(assembly);
 new ResizeObserver(()=>{const r=$('viewport').getBoundingClientRect();if(r.width<1||r.height<1)return;camera.aspect=r.width/r.height;camera.updateProjectionMatrix();renderer.setSize(r.width,r.height,false);}).observe($('viewport'));
 const animate=()=>{requestAnimationFrame(animate);orbit.update();renderer.render(scene,camera);};animate();
}

function validateManifest(m,zip) {
 if(!m||m.format!=='RUGC'||m.formatVersion!==1)throw Error('Неверный формат: требуется RUGC v1');
 if(typeof m.name!=='string'||!m.name.trim()||m.name.length>150)throw Error('В манифесте отсутствует name');
 if(!Array.isArray(m.qualities)||m.qualities.length<1||m.qualities.length>8)throw Error('Нужны qualities (1–8 уровней)');
 if(!Array.isArray(m.parts)||m.parts.length<1||m.parts.length>MAX_PARTS)throw Error('Нужны parts (1–80 деталей)');
 if(!Array.isArray(m.controls)||m.controls.length>MAX_CONTROLS)throw Error('Некорректные controls');
 const qIds=new Set();for(const q of m.qualities){if(!safeId(q.id)||qIds.has(q.id))throw Error('Повтор или неверный ID качества');qIds.add(q.id);}
 const pIds=new Set();for(const p of m.parts){
  if(!safeId(p.id)||pIds.has(p.id))throw Error('Повтор или неверный ID детали');pIds.add(p.id);
  if(!p.meshes || typeof p.meshes!=='object') throw Error('Нет meshes у '+p.id);
  for(const q of m.qualities){const path=p.meshes[q.id];if(!isObjPath(path)||!zip.file(path))throw Error(`Файл сетки не найден: ${p.id} / ${q.id} (${path||'нет'})`);}
  for(const variant of Object.values(p.meshVariants||{})){for(const q of m.qualities){const path=variant[q.id];if(!isObjPath(path)||!zip.file(path))throw Error('Отсутствует mesh variant: '+path);}}
  for(const mat of [p.material,...Object.values(p.materialPresets||{})])if(mat)for(const key of ['colorMap','normalMap','roughnessMap','metalnessMap'])if(mat[key]&&(!safePath(mat[key])||!zip.file(mat[key])))throw Error('Текстура отсутствует: '+mat[key]);
 }
 const validTargets=new Set(['visibility','color','roughness','metalness','opacity','normalStrength','materialPreset','meshChoice','position.x','position.y','position.z','rotation.x','rotation.y','rotation.z','scale.x','scale.y','scale.z','scale.all']);
 const ctlIds=new Set();for(const c of m.controls){
  if(!safeId(c.id)||ctlIds.has(c.id))throw Error('Неверный ID настройки');ctlIds.add(c.id);
  if(!['range','toggle','select','color'].includes(c.type)||!validTargets.has(c.target))throw Error('Неизвестный тип настройки: '+c.id);
  if(c.parts && (!Array.isArray(c.parts)||c.parts.some(id=>!pIds.has(id))))throw Error('Неизвестные детали у '+c.id);
  if(c.type==='select'&&(!Array.isArray(c.options)||!c.options.length||c.options.length>60))throw Error('Пустой список у '+c.id);
 }
 return m;
}

function resetPackage(){state.buildToken++;for(const p of state.parts.values()){p.root.traverse(n=>{if(n.isMesh){n.geometry?.dispose();n.material?.dispose();}});assembly.remove(p.root);}state.parts.clear();for(const tex of state.textures.values())tex.dispose();state.textures.clear();for(const u of state.textureURLs.values())URL.revokeObjectURL(u);state.textureURLs.clear();state.zip=null;state.manifest=null;state.controls={};state.quality=null;}
async function readPack(data,name){
 try {
  setStatus('Читаю пакет и проверяю структуру…');if(data.byteLength>MAX_ARCHIVE)throw Error('Файл больше 100 МБ');
  if(!window.JSZip)throw Error('Не загрузилась библиотека JSZip (проверь интернет)');
  const zip=await window.JSZip.loadAsync(data,{checkCRC32:true});const item=zip.file('manifest.json');if(!item)throw Error('В файле нет manifest.json');
  let uncompressed=0,fileCount=0;for(const [path,f] of Object.entries(zip.files)){if(f.dir)continue;fileCount++;if(fileCount>700)throw Error('Слишком много файлов в архиве');if(path.includes('..')||path.startsWith('/'))throw Error('Недопустимый путь файла');const n=f._data?.uncompressedSize||0;uncompressed+=n;if(n>MAX_FILE)throw Error('Слишком большой файл внутри: '+path);if(uncompressed>180*1024*1024)throw Error('Слишком большой распакованный объём');}
  if((item._data?.uncompressedSize||0)>1024*1024)throw Error('manifest.json слишком большой');
  const m=validateManifest(JSON.parse(await item.async('string')),zip);
  resetPackage();state.zip=zip;state.manifest=m;state.activeFile=name;
  state.quality=(m.defaultQuality && m.qualities.some(q=>q.id===m.defaultQuality))?m.defaultQuality:m.qualities[0].id;
  state.controls=Object.fromEntries(m.controls.map(c=>[c.id,c.default??(c.type==='toggle'?true:c.type==='range'?c.min||0:c.type==='color'?'#ffffff':c.options?.[0]?.value)]));
  $('assetTitle').textContent=m.name;$('assetSub').textContent=[m.category||'3D-аксессуар',m.author||'автор неизвестен'].join(' · ');
  $('fileName').textContent=name;$('emptyHint').hidden=true;$('assetDetails').hidden=false;$('exportBtn').disabled=false;$('previewBtn').disabled=false;
  $('description').textContent=m.description||'Описания нет';$('attachment').textContent=m.attachment||'Не задан';
  renderControls();await changeQuality(state.quality);
  setStatus(`Открыт ${name} · ${m.parts.length} деталей · ${m.controls.length} настроек`,'good');
 } catch(err) {console.error(err);setStatus('Ошибка: '+err.message,'bad');$('errorDetail').textContent=err.stack||String(err);$('errorDetail').hidden=false;}
}
async function texture(path,color=false){
 if(!path)return null;
 if(state.textures.has(path))return state.textures.get(path);
 const file=state.zip.file(path);if(!file)return null;
 const bytes=await file.async('blob');const url=URL.createObjectURL(bytes);state.textureURLs.set(path,url);
 const t=await new Promise((resolve,reject)=>new THREE.TextureLoader().load(url,resolve,undefined,reject));
 if(color)t.colorSpace=THREE.SRGBColorSpace;
 t.flipY=true;t.wrapS=t.wrapT=THREE.RepeatWrapping;
 state.textures.set(path,t);return t;
}
async function createMaterial(part,preset){
 const opt={...(part.material||{}),...(preset&&part.materialPresets?.[preset]||{})};
 const props={color:opt.color||'#ffffff',roughness:bounded(opt.roughness,0,1,.78),metalness:bounded(opt.metalness,0,1,0),side:THREE.DoubleSide};
 const names={colorMap:'map',normalMap:'normalMap',roughnessMap:'roughnessMap',metalnessMap:'metalnessMap'};
 for(const [k,dest] of Object.entries(names))if(opt[k])props[dest]=await texture(opt[k],k==='colorMap');
 const mat=new THREE.MeshStandardMaterial(props);mat.name='material_'+part.id;
 mat.userData.sourceMaterial=opt;mat.userData.partId=part.id;return mat;
}
function resolveParts(control){const ids=control.parts?.length?control.parts:state.manifest.parts.map(p=>p.id);return ids.map(id=>state.parts.get(id)).filter(Boolean);}
function applyControls(){
 if(!state.manifest)return;
 for(const item of state.parts.values()){
  item.root.visible=true;item.root.position.set(...(item.spec.position||[0,0,0]));item.root.rotation.set(...(item.spec.rotation||[0,0,0]).map(v=>v*Math.PI/180));item.root.scale.set(...(item.spec.scale||[1,1,1]));
  item.material.color.set(item.material.userData.sourceMaterial.color||'#ffffff');
  item.material.roughness=bounded(item.material.userData.sourceMaterial.roughness,0,1,.78);
  item.material.metalness=bounded(item.material.userData.sourceMaterial.metalness,0,1,0);
  item.material.opacity=bounded(item.material.userData.sourceMaterial.opacity,0.05,1,1);item.material.transparent=item.material.opacity<1;item.material.normalScale.set(1,1);
 }
 for(const c of state.manifest.controls){
  const v=state.controls[c.id];
  for(const p of resolveParts(c)){
   switch(c.target){
    case 'visibility':p.root.visible=!!v;break;
    case 'color':p.material.color.set(v);break;
    case 'roughness':p.material.roughness=bounded(v,0,1,.78);break;
    case 'metalness':p.material.metalness=bounded(v,0,1,0);break;
    case 'opacity':p.material.opacity=bounded(v,.05,1,1);p.material.transparent=p.material.opacity<1;break;
    case 'normalStrength':p.material.normalScale.set(bounded(v,0,5,1),bounded(v,0,5,1));break;
    case 'position.x':p.root.position.x+=Number(v)||0;break;
    case 'position.y':p.root.position.y+=Number(v)||0;break;
    case 'position.z':p.root.position.z+=Number(v)||0;break;
    case 'rotation.x':p.root.rotation.x+=(Number(v)||0)*Math.PI/180;break;
    case 'rotation.y':p.root.rotation.y+=(Number(v)||0)*Math.PI/180;break;
    case 'rotation.z':p.root.rotation.z+=(Number(v)||0)*Math.PI/180;break;
    case 'scale.all':p.root.scale.multiplyScalar(bounded(v,.05,10,1));break;
    case 'scale.x':p.root.scale.x*=bounded(v,.05,10,1);break;
    case 'scale.y':p.root.scale.y*=bounded(v,.05,10,1);break;
    case 'scale.z':p.root.scale.z*=bounded(v,.05,10,1);break;
   }
  }
 }
 updateStats();
}
function applyMaterialPreset(){
 for(const c of state.manifest.controls.filter(c=>c.target==='materialPreset')){
  for(const p of resolveParts(c)){
   const key=String(state.controls[c.id]);const mp=p.spec.materialPresets?.[key];if(!mp)continue;
   const base=p.spec.material||{};const opt={...base,...mp};const mat=p.material;
   mat.color.set(opt.color||'#ffffff');mat.roughness=bounded(opt.roughness,0,1,.78);mat.metalness=bounded(opt.metalness,0,1,0);mat.opacity=bounded(opt.opacity,.05,1,1);mat.transparent=mat.opacity<1;
   for(const [a,b] of Object.entries({colorMap:'map',normalMap:'normalMap',roughnessMap:'roughnessMap',metalnessMap:'metalnessMap'}))mat[b]=opt[a]?state.textures.get(opt[a])||null:null;
   mat.userData.sourceMaterial=opt;mat.needsUpdate=true;
  }
 }
}
async function changeQuality(q){
 if(!state.zip || !state.manifest)return;
 const token=++state.buildToken;state.quality=q;const oldRoots=new Map(state.parts);
 const next=[];setStatus('Загружаю геометрию: '+q+'…');
 try {
  for(const spec of state.manifest.parts){
   const meshControl=state.manifest.controls.find(c=>c.target==='meshChoice' && (!c.parts || c.parts.includes(spec.id)));
   const chosen=meshControl?String(state.controls[meshControl.id]):null;
   const meshPath=chosen && spec.meshVariants?.[chosen]?.[q] || spec.meshes[q];
   const file=state.zip.file(meshPath);if(!file)throw Error('Не найдена сетка '+meshPath);
   const txt=await file.async('string');if(txt.length>MAX_FILE)throw Error('Слишком большой OBJ');
   const geom=loader.parse(txt);if(token!==state.buildToken)return;
   const material=await createMaterial(spec,null);if(token!==state.buildToken){material.dispose();return;}
   geom.traverse(n=>{if(n.isMesh){n.material=material;n.castShadow=false;}});
   geom.name=spec.id;const root=new THREE.Group();root.name=spec.id;root.add(geom);
   next.push({root,spec,material});
  }
  if(token!==state.buildToken)return;
  for(const old of oldRoots.values()){assembly.remove(old.root);old.root.traverse(n=>{if(n.isMesh)n.geometry?.dispose();});old.material.dispose();}
  state.parts.clear();for(const p of next){state.parts.set(p.spec.id,p);assembly.add(p.root);}
  applyMaterialPreset();applyControls();
  const box=new THREE.Box3().setFromObject(assembly);if(!box.isEmpty()){
   const c=box.getCenter(new THREE.Vector3()),size=box.getSize(new THREE.Vector3()),max=Math.max(size.x,size.y,size.z,.5);orbit.target.copy(c);camera.position.copy(c).add(new THREE.Vector3(max*1.65,max*1.1,max*1.8));camera.near=Math.max(.01,max/300);camera.far=Math.max(100,max*100);camera.updateProjectionMatrix();orbit.update();
  }
  setStatus(`Загружено качество «${state.manifest.qualities.find(x=>x.id===q)?.label||q}»`,'good');
 }catch(err){console.error(err);setStatus('Ошибка при переключении качества: '+err.message,'bad');}
}
function showControl(c,container){
 const line=document.createElement('div');line.className='control';const head=document.createElement('div');head.className='control-label';
 const label=document.createElement('span');label.textContent=c.label||c.id;head.append(label);
 const info=document.createElement('span');info.className='control-value';head.append(info);
 const update=async(v)=>{state.controls[c.id]=v;info.textContent=showValue(v,c.type);if(c.target==='materialPreset'){applyMaterialPreset();applyControls();}else if(c.target==='meshChoice'){await changeQuality(state.quality);}else applyControls();};
 let input;
 if(c.type==='toggle'){input=document.createElement('input');input.type='checkbox';input.checked=!!state.controls[c.id];input.addEventListener('change',()=>update(input.checked));line.classList.add('toggle-control');}
 else if(c.type==='select'){input=document.createElement('select');for(const op of c.options){let o=document.createElement('option');o.value=String(op.value);o.textContent=op.label||op.value;input.append(o);}input.value=String(state.controls[c.id]);input.addEventListener('change',()=>update(input.value));}
 else if(c.type==='range'){input=document.createElement('input');input.type='range';input.min=String(c.min??0);input.max=String(c.max??1);input.step=String(c.step??.01);input.value=String(state.controls[c.id]);input.addEventListener('input',()=>update(Number(input.value)));}
 else if(c.type==='color'){input=document.createElement('input');input.type='color';input.value=/^#[0-9a-fA-F]{6}$/.test(state.controls[c.id])?state.controls[c.id]:'#ffffff';input.addEventListener('input',()=>update(input.value));}
 info.textContent=c.type==='toggle'?'':c.type==='select'?'':showValue(state.controls[c.id],c.type);
 if(c.type==='toggle'){head.append(input);line.append(head);}else {line.append(head,input);}container.append(line);
}
function renderControls(){
 const m=state.manifest;const host=$('controls');host.replaceChildren();
 const qsec=document.createElement('section');qsec.className='control-section';const ht=document.createElement('h3');ht.textContent='Детализация';qsec.append(ht);
 const ql=document.createElement('div');ql.className='control';const sel=document.createElement('select');for(const q of m.qualities){const o=document.createElement('option');o.value=q.id;o.textContent=q.label||q.id;sel.append(o);}sel.value=state.quality;sel.onchange=()=>changeQuality(sel.value);ql.append(sel);qsec.append(ql);host.append(qsec);
 const groups=new Map();for(const c of m.controls){const g=c.group||'Основные настройки';if(!groups.has(g))groups.set(g,[]);groups.get(g).push(c);}
 for(const [group,controls] of groups){const sec=document.createElement('section');sec.className='control-section';const h=document.createElement('h3');h.textContent=group;sec.append(h);for(const c of controls)showControl(c,sec);host.append(sec);}
 if(!m.controls.length)addText(host,'Создатель файла не добавил дополнительных настроек.','muted');
}
function geometryInfo(){
 const bounding=new THREE.Box3();let triangles=0,degenerate=0,meshCount=0;
 assembly.updateMatrixWorld(true);
 assembly.traverse(n=>{
  if(!n.isMesh||!n.visible||!n.parent?.visible)return;
  let p=n;while(p!==assembly){if(p.visible===false)return;p=p.parent;}
  const geo=n.geometry;meshCount++;const pos=geo.getAttribute('position');if(!pos)return;
  const index=geo.getIndex();const f=index?index.count/3:pos.count/3;triangles+=f;
  const b=new THREE.Box3().setFromObject(n);bounding.union(b);
  const a=new THREE.Vector3(),bb=new THREE.Vector3(),c=new THREE.Vector3(),v1=new THREE.Vector3(),v2=new THREE.Vector3();
  for(let i=0;i<f;i++){
   const j=i*3,ix=index?index.getX(j):j,iy=index?index.getX(j+1):j+1,iz=index?index.getX(j+2):j+2;
   a.fromBufferAttribute(pos,ix);bb.fromBufferAttribute(pos,iy);c.fromBufferAttribute(pos,iz);
   if(v1.subVectors(bb,a).cross(v2.subVectors(c,a)).lengthSq()<1e-18)degenerate++;
  }
 });
 return {triangles,degenerate,meshCount,bounds:bounding.isEmpty()?new THREE.Vector3(0,0,0):bounding.getSize(new THREE.Vector3())};
}
function updateStats(){if(!state.manifest)return;const v=geometryInfo(), max=Number(state.manifest?.limits?.maxTriangles)||4000;
 $('triCount').textContent=v.triangles.toLocaleString('ru-RU');$('triCount').className=v.triangles>max?'bad':'good';
 $('triLimit').textContent=max.toLocaleString('ru-RU');$('partCount').textContent=state.parts.size; $('sizeStats').textContent=[v.bounds.x,v.bounds.y,v.bounds.z].map(x=>x.toFixed(2)).join(' × ');
 const e=[];if(v.triangles>max)e.push('Превышен лимит треугольников');if(v.degenerate)e.push('Вырожденные треугольники: '+v.degenerate);
 const maxSize=state.manifest.limits?.maxSize;if(Array.isArray(maxSize)&&maxSize.length===3){for(let i=0;i<3;i++)if(v.bounds.getComponent(i)>Number(maxSize[i])+.0001)e.push('Превышен габарит по '+['X','Y','Z'][i]);}
 $('validation').textContent=e.length?'⚠ '+e.join(' · '):'✓ Базовые проверки сетки пройдены';$('validation').dataset.type=e.length?'bad':'good';
 $('validationNote').textContent='Это только локальная проверка. Посадка на аватар и одобрение Roblox Studio не подтверждены.';
}
async function saveFile(blob,name){const url=URL.createObjectURL(blob);const a=document.createElement('a');a.href=url;a.download=name;document.body.append(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),3000);}
async function exportCurrent(){
 if(!state.manifest)return;
 try {
  setStatus('Собираю OBJ + MTL + текстуры…');const zip=new window.JSZip();let temp=new THREE.Group();
  assembly.updateMatrixWorld(true);
  const exported=[];
  for(const item of state.parts.values()){
   if(!item.root.visible)continue;
   item.root.traverse(n=>{if(!n.isMesh||!n.visible)return;const m=n.clone();m.geometry=n.geometry;m.material=n.material;m.name=item.spec.id+'_'+n.name.replace(/\s+/g,'_');m.matrixAutoUpdate=false;m.matrix.copy(n.matrixWorld);temp.add(m);exported.push({mesh:m,item});});
  }
  if(!exported.length)throw Error('Нет видимых деталей для экспорта');
  temp.updateMatrixWorld(true);let obj=exporter.parse(temp);const mtl=[];const paths=new Set();
  for(const {item} of exported){const mat=item.material,spec=mat.userData.sourceMaterial||item.spec.material||{};const n=mat.name;
   const color=mat.color;mtl.push(`newmtl ${n}`,`Kd ${color.r.toFixed(5)} ${color.g.toFixed(5)} ${color.b.toFixed(5)}`,'Ka 1.00000 1.00000 1.00000',`d ${mat.opacity.toFixed(4)}`,'illum 2',`# roughness ${mat.roughness.toFixed(4)}`,`# metalness ${mat.metalness.toFixed(4)}`);
   const mapNames={colorMap:'map_Kd',normalMap:'norm',roughnessMap:'map_Pr',metalnessMap:'map_Pm'};
   for(const [k,mTag] of Object.entries(mapNames))if(spec[k]){mtl.push(`${mTag} ${spec[k]}`);paths.add(spec[k]);}mtl.push('');
  }
  if(!obj.includes('usemtl ')){obj=obj.replace(/^o /m,'usemtl material_default\no ');}
  zip.file('model.obj','mtllib model.mtl\n'+obj);zip.file('model.mtl',mtl.join('\n'));
  for(const path of paths){const file=state.zip.file(path);if(file)zip.file(path,await file.async('uint8array'));}
  zip.file('configuration.json',JSON.stringify({format:'RUGC export config',source:state.manifest.name,quality:state.quality,controls:state.controls},null,2));
  zip.file('README_RU.txt','Экспорт из RUGC Studio. В ZIP есть OBJ, MTL, доступные PBR-карты и конфигурация. Цвет материала/параметры roughness и metalness в предпросмотре не гарантированно переносятся в Roblox автоматически. После импорта OBJ создайте SurfaceAppearance и назначьте карты вручную. Затем настройте attachment через Accessory Fitting Tool и проверьте лимиты и посадку в Roblox Studio.');
  await saveFile(await zip.generateAsync({type:'blob',compression:'DEFLATE',compressionOptions:{level:5}}), (state.manifest.name.replace(/[^a-z0-9_-]+/gi,'_')||'accessory')+'_'+state.quality+'_export.zip');
  setStatus('ZIP с текущей конфигурацией экспортирован','good');
 }catch(e){console.error(e);setStatus('Ошибка экспорта: '+e.message,'bad');}
}
function screenshot(){const a=document.createElement('a');a.href=renderer.domElement.toDataURL('image/png');a.download='ugc_preview.png';a.click();}
async function openFromDataset(){
 const repo=$('hfRepo').value.trim(),path=$('hfPath').value.trim();if(!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repo)||!safePath(path)||!path.toLowerCase().endsWith('.rugc')){
 // .rugc deliberately excluded from paths of mesh/assets, so validate separately
 if(!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repo)||!/^([a-zA-Z0-9_.-]+\/)*[a-zA-Z0-9_.-]+\.rugc$/i.test(path)){setStatus('Укажи владельца/имя Dataset и путь .rugc','bad');return;}
 }
 const url=`https://huggingface.co/datasets/${repo}/resolve/main/${path.split('/').map(encodeURIComponent).join('/')}`;
 try{setStatus('Скачиваю из Hugging Face Dataset…');const r=await fetch(url,{mode:'cors'});if(!r.ok)throw Error('HTTP '+r.status);await readPack(await r.arrayBuffer(),path);}catch(e){setStatus('Не удалось загрузить через браузер: '+e.message+'. Скачай файл с Dataset и открой локально.','bad');}
}
$('pickBtn').onclick=()=>$('filePicker').click();$('filePicker').addEventListener('change',async e=>{const f=e.target.files?.[0];if(f)await readPack(await f.arrayBuffer(),f.name);e.target.value='';});
$('exportBtn').onclick=exportCurrent;$('previewBtn').onclick=screenshot;$('hfLoad').onclick=openFromDataset;
$('resetCamera').onclick=()=>{if(!state.manifest)return;const b=new THREE.Box3().setFromObject(assembly);if(!b.isEmpty()){const c=b.getCenter(new THREE.Vector3()),s=b.getSize(new THREE.Vector3()),r=Math.max(s.x,s.y,s.z,.5);orbit.target.copy(c);camera.position.copy(c).add(new THREE.Vector3(1.7*r,1.1*r,1.8*r));}};
$('gridToggle').addEventListener('change',e=>{grid.visible=e.target.checked;});
$('axisToggle').addEventListener('change',e=>{axes.visible=e.target.checked;});
window.addEventListener('dragover',e=>e.preventDefault());window.addEventListener('drop',async e=>{e.preventDefault();let f=e.dataTransfer.files?.[0];if(f)await readPack(await f.arrayBuffer(),f.name);});
$('errorDetail').hidden=true;
/** Agent preview mode: same RUGC Studio, optional local .rugc auto-loading.
 *  Disabled in normal use. The local preview server serves a single selected file.
 */
async function loadLocalAgentPreview(){
 const params=new URLSearchParams(location.search);
 if(params.get('rugcPreview')!=='1')return;
 document.documentElement.dataset.rugcPreview='loading';
 try{
  if(location.protocol!=='http:' && location.protocol!=='https:')throw Error('Локальный предпросмотр требует HTTP-сервера');
  const r=await fetch('/__rugc_preview__.rugc',{cache:'no-store'});
  if(!r.ok)throw Error('HTTP '+r.status+' при загрузке .rugc');
  const data=await r.arrayBuffer();
  await readPack(data,'agent-preview.rugc');
  if(!state.manifest || state.parts.size!==state.manifest.parts.length || $('status').dataset.type!=='good'){
   throw Error('RUGC Studio не смогла полностью открыть пакет: '+$('status').textContent);
  }
  document.documentElement.dataset.rugcPreview='ready';
 }catch(e){
  document.documentElement.dataset.rugcPreview='error';
  setStatus('Ошибка агентского предпросмотра: '+e.message,'bad');
  $('errorDetail').textContent=e.stack||String(e);$('errorDetail').hidden=false;
 }
}
init3D();
void loadLocalAgentPreview();

</script></body></html>