File size: 39,771 Bytes
1efc858
 
 
 
25f2b49
1efc858
3aa9907
0154c3a
1efc858
 
0154c3a
8af251a
7bbe85d
1efc858
7bbe85d
 
a78ebd7
 
7bbe85d
a78ebd7
1efc858
 
8af251a
1efc858
7bbe85d
 
3aa9907
1efc858
8af251a
7bbe85d
3aa9907
 
1efc858
7bbe85d
8af251a
0154c3a
8af251a
 
f5297c8
0154c3a
7bbe85d
0154c3a
7bbe85d
 
7877e69
7bbe85d
a78ebd7
7bbe85d
 
1efc858
7877e69
 
 
3aa9907
7877e69
 
3aa9907
7bbe85d
7877e69
7bbe85d
 
 
 
 
1efc858
 
 
 
 
 
7877e69
1efc858
 
 
 
 
 
6a5bf2b
3aa9907
 
7877e69
7bbe85d
6a5bf2b
3aa9907
1ab9987
6a5bf2b
 
 
1efc858
 
 
 
 
25f2b49
3aa9907
 
 
 
 
1efc858
 
 
 
7bbe85d
3aa9907
1efc858
 
7bbe85d
1efc858
7bbe85d
7877e69
3aa9907
0154c3a
1efc858
7bbe85d
3aa9907
 
 
 
 
 
7bbe85d
 
3aa9907
 
 
 
7877e69
 
 
 
 
 
 
 
 
0154c3a
3aa9907
1efc858
0154c3a
7877e69
 
0154c3a
1efc858
 
 
a78ebd7
 
 
 
 
1efc858
 
 
 
 
 
 
 
 
7877e69
 
 
 
 
 
 
 
 
 
3aa9907
7877e69
 
 
 
 
 
 
 
 
 
8af251a
 
 
3aa9907
 
 
 
0154c3a
a78ebd7
7bbe85d
0154c3a
1efc858
 
 
 
 
3aa9907
1efc858
7bbe85d
 
 
 
 
 
 
 
 
 
 
8af251a
 
1efc858
 
 
7bbe85d
7877e69
6a5bf2b
1efc858
7877e69
1efc858
3aa9907
7877e69
 
1efc858
 
0154c3a
1efc858
 
 
 
 
 
 
a78ebd7
 
1efc858
 
 
7877e69
1efc858
7877e69
0154c3a
1efc858
 
 
3aa9907
 
 
 
 
 
 
 
 
 
 
 
 
7877e69
3aa9907
 
 
 
 
 
 
 
 
7877e69
 
3aa9907
 
 
 
 
 
8af251a
3aa9907
7877e69
3aa9907
 
 
 
 
 
7877e69
3aa9907
 
 
 
 
 
7877e69
3aa9907
 
 
f5297c8
 
3aa9907
 
 
 
 
 
 
 
8af251a
3aa9907
 
8af251a
 
 
 
3aa9907
8af251a
3aa9907
8af251a
 
 
 
3aa9907
8af251a
 
 
 
 
 
 
 
 
 
 
 
 
7877e69
8af251a
 
 
 
 
 
 
 
 
 
7877e69
 
 
 
8d30518
 
 
f5297c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d30518
a78ebd7
25f2b49
8d30518
7bbe85d
6a5bf2b
8d30518
3aa9907
7877e69
25f2b49
7877e69
 
 
3aa9907
 
 
 
7877e69
 
 
 
3aa9907
7877e69
3aa9907
7877e69
f5297c8
7877e69
 
 
 
 
 
 
 
 
 
f5297c8
3aa9907
 
 
7877e69
3aa9907
7877e69
 
 
3aa9907
7877e69
 
3aa9907
 
 
7877e69
 
1ab9987
 
7877e69
 
1ab9987
7877e69
3aa9907
 
7877e69
3aa9907
8d30518
3aa9907
 
 
 
 
 
 
 
 
 
 
 
7877e69
 
 
 
 
 
3aa9907
 
 
 
 
8d30518
3aa9907
 
 
 
8d30518
 
a78ebd7
8d30518
 
6a5bf2b
8d30518
 
 
a78ebd7
7bbe85d
 
a78ebd7
8d30518
a78ebd7
7bbe85d
 
8d30518
 
7bbe85d
 
a78ebd7
8d30518
a78ebd7
8d30518
7bbe85d
a78ebd7
7bbe85d
8d30518
 
 
1ab9987
3aa9907
7877e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f2b49
 
 
7877e69
 
 
 
 
 
 
 
25f2b49
 
 
 
 
 
 
7877e69
 
 
 
 
 
 
 
6a5bf2b
7877e69
3aa9907
7877e69
7bbe85d
25f2b49
 
 
 
3aa9907
 
6a5bf2b
8d30518
7877e69
25f2b49
 
 
 
 
 
3aa9907
8d30518
3aa9907
7877e69
8d30518
1ab9987
f5297c8
3aa9907
1ab9987
 
 
 
 
8d30518
3aa9907
 
1ab9987
8d30518
1ab9987
f5297c8
1ab9987
f5297c8
1ab9987
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5297c8
 
 
8d30518
1ab9987
7877e69
3aa9907
 
f5297c8
7877e69
1ab9987
7877e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ab9987
 
 
25f2b49
1ab9987
8d30518
 
 
 
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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>BeadMaster Pro v10.3 - 完美修正版</title>
    <style>
        :root { --bg: #18181b; --panel: #27272a; --accent: #8b5cf6; --success: #10b981; --warn: #f59e0b; --text: #f4f4f5; --border: #3f3f46; --ruler-bg: #202022; }
        body { margin: 0; overflow: hidden; background: var(--bg); color: var(--text); font-family: 'Segoe UI', Roboto, sans-serif; user-select: none; }
        
        #app { display: flex; width: 100vw; height: 100vh; }
        .sidebar { width: 64px; background: var(--panel); border-right: 1px solid var(--border); display: flex; flex-direction: column; align-items: center; padding-top: 15px; gap: 10px; z-index: 50; }
        .panels { width: 320px; background: var(--panel); border-left: 1px solid var(--border); display: flex; flex-direction: column; z-index: 50; }
        #canvas-wrapper { flex: 1; position: relative; overflow: hidden; background: #09090b; display: flex; flex-direction: column; }
        
        #ruler-top-bar { height: 32px; background: var(--ruler-bg); border-bottom: 1px solid var(--border); display: flex; z-index: 40; }
        #corner-box { width: 32px; height: 32px; background: var(--ruler-bg); border-right: 1px solid var(--border); color: #888; font-size: 10px; display: flex; justify-content: center; align-items: center; flex-shrink: 0; }
        #ruler-top { flex: 1; position: relative; overflow: hidden; }
        #main-area { flex: 1; display: flex; position: relative; overflow: hidden; }
        #ruler-left { width: 32px; background: var(--ruler-bg); border-right: 1px solid var(--border); position: relative; overflow: hidden; z-index: 40; flex-shrink: 0; }
        #viewport { flex: 1; position: relative; overflow: hidden; cursor: crosshair; z-index: 10; }
        canvas { display: block; }

        .topbar { height: 56px; background: var(--panel); border-bottom: 1px solid var(--border); display: flex; align-items: center; padding: 0 15px; gap: 12px; z-index: 45; }

        .tool-btn { width: 42px; height: 42px; border-radius: 8px; border: none; background: transparent; color: #a1a1aa; cursor: pointer; font-size: 22px; transition: 0.2s; display:flex; justify-content:center; align-items:center; }
        .tool-btn:hover { background: #3f3f46; color: white; }
        .tool-btn.active { background: var(--accent); color: white; box-shadow: 0 0 10px rgba(139, 92, 246, 0.3); }
        
        .action-btn { padding: 8px 12px; background: #3f3f46; border: 1px solid var(--border); color: white; border-radius: 6px; cursor: pointer; font-size: 13px; display: flex; align-items: center; gap: 6px; white-space: nowrap; font-weight: 500; }
        .action-btn:hover { background: #52525b; }
        .btn-green { background: var(--success); border-color: var(--success); } .btn-green:hover { background: #059669; }
        .btn-purple { background: var(--accent); border-color: var(--accent); } .btn-purple:hover { background: #7c3aed; }
        
        .control-group { display: flex; flex-direction: column; gap: 2px; }
        .control-label { font-size: 10px; color: #a1a1aa; text-transform: uppercase; letter-spacing: 0.5px; font-weight: bold; }
        
        input[type="number"] { background: #18181b; border: 1px solid #52525b; color: white; width: 60px; padding: 4px; border-radius: 4px; text-align: center; font-size: 14px; font-weight: bold; height: 20px; }
        select { background: #18181b; border: 1px solid #52525b; color: white; padding: 4px; border-radius: 4px; outline: none; font-size: 12px; height: 30px; }
        input[type=range] { width: 100%; accent-color: var(--accent); cursor: pointer; }

        .panel-header { padding: 15px; border-bottom: 1px solid var(--border); font-weight: bold; font-size: 14px; display: flex; justify-content: space-between; align-items: center; background: #202022; }
        #material-list { flex: 1; overflow-y: auto; padding: 5px 0; }
        .material-item { display: flex; align-items: center; padding: 8px 15px; gap: 10px; border-bottom: 1px solid #333; font-size: 13px; cursor: pointer; transition: 0.2s; }
        .material-item:hover { background: #3f3f46; }
        .material-item.active { background: #312e81; border-left: 3px solid var(--accent); }
        .list-swatch { width: 22px; height: 22px; border-radius: 4px; border: 1px solid rgba(255,255,255,0.2); flex-shrink: 0; }
        .list-info { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .list-count { font-family: monospace; font-weight: bold; color: var(--accent); font-size: 14px; }
        #total-stats { padding: 15px; border-top: 1px solid var(--border); background: #202022; font-size: 13px; display: flex; justify-content: space-between; font-weight: bold; color: var(--success); }

        .mode-switch { display: flex; background: #18181b; padding: 4px; border-radius: 6px; border: 1px solid var(--border); width: 140px; }
        .mode-btn { flex: 1; padding: 6px; text-align: center; font-size: 12px; cursor: pointer; border-radius: 4px; color: #888; transition: 0.2s; }
        .mode-btn.active { background: var(--accent); color: white; font-weight: bold; box-shadow: 0 2px 5px rgba(0,0,0,0.3); }
        
        .slider-row { margin-bottom: 15px; }
        .slider-header { display: flex; justify-content: space-between; font-size: 12px; margin-bottom: 5px; color: #ccc; }
        
        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); z-index: 100; display: none; justify-content: center; align-items: center; backdrop-filter: blur(5px); }
        .modal-content { background: var(--panel); padding: 20px; border-radius: 12px; width: 80vw; height: 85vh; display: flex; flex-direction: column; gap: 15px; border: 1px solid var(--border); box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5); }
        #crop-container { flex: 1; background: #000; position: relative; overflow: hidden; display: flex; justify-content: center; align-items: center; border: 1px solid #3f3f46; border-radius: 4px; }
        #crop-img { max-width: 100%; max-height: 100%; display: block; }
        #crop-box { position: absolute; border: 2px dashed #fff; box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.6); cursor: move; display: none; }
        .resize-handle { position: absolute; right: -8px; bottom: -8px; width: 16px; height: 16px; background: var(--accent); cursor: nwse-resize; border: 2px solid white; border-radius: 50%; }
        .modal-footer { display:flex; justify-content:space-between; align-items: center; background: #202022; padding: 15px; border-radius: 8px; border: 1px solid var(--border); }
    </style>
</head>
<body>

<div class="modal-overlay" id="cropModal">
    <div class="modal-content">
        <h3 style="margin:0; color: white;">✂️ 图片导入向导</h3>
        <div id="crop-container" onmousedown="startCropDrag(event)">
            <img id="crop-img">
            <div id="crop-box">
                <div class="resize-handle" onmousedown="startCropResize(event)"></div>
            </div>
        </div>
        <div class="modal-footer">
            <div style="display: flex; gap: 20px; align-items: center;">
                <label style="display: flex; align-items: center; gap: 8px; font-size: 13px; cursor: pointer;">
                    <input type="checkbox" id="ditherCheck" checked> <span>色彩融合 (Dithering)</span>
                </label>
            </div>
            <div style="display: flex; gap: 10px;">
                <button class="action-btn btn-green" id="btn-confirm-import" onclick="confirmCrop()">✅ 确认导入</button>
                <button class="action-btn" onclick="closeModal()">取消</button>
            </div>
        </div>
    </div>
</div>

<div id="app">
    <div class="sidebar">
        <div style="height: 56px; display: flex; align-items: center; font-weight: 900; color: var(--accent); font-size: 14px;">v10.3</div>
        <button class="tool-btn active" id="t-pencil" onclick="setTool('pencil')" title="画笔">✏️</button>
        <button class="tool-btn" id="t-eraser" onclick="setTool('eraser')" title="橡皮">🧼</button>
        <button class="tool-btn" id="t-bucket" onclick="setTool('bucket')" title="油漆桶">🪣</button>
        <button class="tool-btn" id="t-picker" onclick="setTool('picker')" title="吸管">🧪</button>
        <button class="tool-btn" id="t-move" onclick="setTool('move')" title="抓手">✋</button>
    </div>

    <div style="flex:1; display: flex; flex-direction: column;">
        <div class="topbar">
            <label class="action-btn btn-green">
                <b>📁 导入</b>
                <input type="file" id="fileInput" accept="image/*" style="display:none" onchange="handleFile(this)">
            </label>
            <div style="width:1px; height:24px; background:var(--border);"></div>
            
            <div class="control-group">
                <div class="control-label" style="color: var(--success);">🎯 精度</div>
                <input type="number" id="targetRes" value="60" min="10" max="300" onchange="reprocessCurrentImg()" onkeydown="if(event.key==='Enter') reprocessCurrentImg()">
            </div>

            <div class="control-group">
                <div class="control-label">画布格数</div>
                <div style="display:flex; align-items:center; gap:4px;">
                    <input type="number" id="gridW" value="60" onchange="resizeGrid()">
                    <span style="color:#666">x</span>
                    <input type="number" id="gridH" value="60" onchange="resizeGrid()">
                </div>
            </div>

            <div style="width:1px; height:24px; background:var(--border);"></div>

            <div class="mode-switch">
                <div class="mode-btn active" id="mode-2d" onclick="setMode('2d')">2D 平面</div>
                <div class="mode-btn" id="mode-3d" onclick="setMode('3d')">3D 爆炸</div>
            </div>

            <div class="control-group">
                <div class="control-label">形状</div>
                <select id="shapeSelect" onchange="draw()">
                    <option value="circle">🔵 圆形</option>
                    <option value="square">⬛ 方块</option>
                </select>
            </div>

            <div style="flex:1;"></div>
            
            <button class="action-btn btn-purple" id="btn-export-2d" onclick="exportImageWithRuler()">💾 导出平面</button>
            <button class="action-btn btn-purple" id="btn-export-3d" onclick="exportSlices()" style="display:none;">📑 导出分层</button>
            <button class="action-btn" onclick="clearCanvas()">🗑️</button>
        </div>

        <div id="canvas-wrapper">
            <div id="ruler-top-bar">
                <div id="corner-box">px</div>
                <div id="ruler-top"><canvas id="rulerTopCanvas"></canvas></div>
            </div>
            <div id="main-area">
                <div id="ruler-left"><canvas id="rulerLeftCanvas"></canvas></div>
                <div id="viewport">
                    <canvas id="mainCanvas"></canvas>
                </div>
            </div>
        </div>
    </div>

    <div class="panels">
        <div id="panel-3d-controls" style="padding: 15px; background: #202022; border-bottom: 1px solid var(--border); display: none;">
            <button class="action-btn btn-green" style="width:100%; margin-bottom:15px;" onclick="autoGenerate3D()">
                🧊 一键生成立体层级
            </button>
            <div class="slider-row">
                <div class="slider-header">
                    <span>💥 爆炸/间距 (Explode)</span>
                    <span id="explode-val">0%</span>
                </div>
                <input type="range" id="explodeSlider" min="0" max="100" value="0" oninput="updateExplode(this.value)">
            </div>
            <div class="slider-row">
                <div class="slider-header">
                    <span>🍰 显示层级 (Layers)</span>
                    <span id="layer-display">1 / 1</span>
                </div>
                <input type="range" id="layerSlider" min="1" max="1" value="1" oninput="updateLayerView(this.value)">
                <label style="display:flex; align-items:center; gap:8px; margin-top:8px; font-size:12px; color:#aaa; cursor:pointer;">
                    <input type="checkbox" id="singleLayerCheck" onchange="draw()">
                    👁️ 仅看当前层 (专注模式)
                </label>
            </div>
        </div>

        <div class="panel-header">
            <span>📦 材料清单</span>
             <button class="action-btn" style="padding: 2px 8px; font-size: 11px;" onclick="mergeSimilarColors()">📉 合并颜色</button>
        </div>
        <div id="material-list"></div>
        <div id="total-stats">
            <span>总颗粒:</span>
            <span id="total-beads-count">0</span>
        </div>
    </div>
</div>

<script>
// --- 数据 ---
const PALETTE = [
    {id:'A01', hex:'#0f0f12', name:'夜黑'}, {id:'A02', hex:'#FFFFFF', name:'纯白'}, 
    {id:'B01', hex:'#e11d48', name:'正红'}, {id:'B02', hex:'#fb7185', name:'西瓜红'},
    {id:'C01', hex:'#16a34a', name:'鲜绿'}, {id:'C02', hex:'#4ade80', name:'草绿'},
    {id:'D01', hex:'#1d4ed8', name:'深蓝'}, {id:'D02', hex:'#38bdf8', name:'天蓝'},
    {id:'E01', hex:'#facc15', name:'柠檬黄'}, {id:'E02', hex:'#fbbf24', name:'金黄'},
    {id:'F01', hex:'#f97316', name:'亮橙'}, {id:'F02', hex:'#c2410c', name:'焦糖'},
    {id:'G01', hex:'#9333ea', name:'紫罗兰'}, {id:'G02', hex:'#7e22ce', name:'深紫'},
    {id:'H01', hex:'#f472b6', name:'浅粉'}, {id:'H02', hex:'#db2777', name:'热粉'},
    {id:'J01', hex:'#9ca3af', name:'水泥灰'}, {id:'J02', hex:'#4b5563', name:'深灰'},
    {id:'K01', hex:'#7f1d1d', name:'红棕'}, {id:'K02', hex:'#ea580c', name:'南瓜'},
    {id:'L01', hex:'#fde047', name:'卡其'}, {id:'L02', hex:'#c084fc', name:'薰衣草'},
    {id:'M01', hex:'#2dd4bf', name:'绿松石'},{id:'M02', hex:'#f59e0b', name:'金色'},
    {id:'N01', hex:'#fecaca', name:'肉色'}, {id:'N02', hex:'#881337', name:'酒红'}
];

const state = {
    gridW: 60, gridH: 60,
    pixels: {}, heightMap: {},
    scale: 25, 
    offsetX: 50, offsetY: 50,
    tool: 'pencil', curColorIdx: 2,
    isDrag: false, lastX: 0, lastY: 0,
    sourceImgData: null, sourceW: 0, sourceH: 0,
    mode: '2d',
    maxLayers: 1, viewLayer: 1, explodeVal: 0
};

// DOM
const viewport = document.getElementById('viewport');
const cvs = document.getElementById('mainCanvas');
const ctx = cvs.getContext('2d');
const rulerTop = document.getElementById('rulerTopCanvas');
const ctxRTop = rulerTop.getContext('2d');
const rulerLeft = document.getElementById('rulerLeftCanvas');
const ctxRLeft = rulerLeft.getContext('2d');
const materialListEl = document.getElementById('material-list');
const totalBeadsEl = document.getElementById('total-beads-count');

function init() {
    window.addEventListener('resize', resizeAll);
    resizeAll(); updateMaterialList(); draw();
    viewport.addEventListener('wheel', e => {
        e.preventDefault(); const delta = e.deltaY > 0 ? 0.9 : 1.1;
        applyZoom(state.scale * delta, e.clientX, e.clientY);
    }, {passive:false});
}

function setMode(mode) {
    state.mode = mode;
    document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active'));
    document.getElementById(`mode-${mode}`).classList.add('active');
    
    const controls3d = document.getElementById('panel-3d-controls');
    const btnExp2d = document.getElementById('btn-export-2d');
    const btnExp3d = document.getElementById('btn-export-3d');
    
    if(mode === '3d') {
        controls3d.style.display = 'block';
        btnExp2d.style.display = 'none';
        btnExp3d.style.display = 'flex';
        if(state.maxLayers === 1) autoGenerate3D(true);
    } else {
        controls3d.style.display = 'none';
        btnExp2d.style.display = 'flex';
        btnExp3d.style.display = 'none';
    }
    draw();
}

function autoGenerate3D(silent = false) {
    if(!state.sourceImgData) { if(!silent) alert("请先导入图片!"); return; }
    const targetW = state.gridW; const targetH = state.gridH;
    const tmpCv = document.createElement('canvas'); tmpCv.width = targetW; tmpCv.height = targetH;
    const tmpCtx = tmpCv.getContext('2d');
    const srcCv = document.createElement('canvas'); srcCv.width = state.sourceW; srcCv.height = state.sourceH;
    srcCv.getContext('2d').putImageData(state.sourceImgData, 0, 0);
    tmpCtx.drawImage(srcCv, 0, 0, targetW, targetH);
    const data = tmpCtx.getImageData(0, 0, targetW, targetH).data;
    
    state.heightMap = {};
    const layers = 6; state.maxLayers = layers;
    for(let y=0; y<targetH; y++) {
        for(let x=0; x<targetW; x++) {
            const idx = (y*targetW + x)*4;
            const r = data[idx], g = data[idx+1], b = data[idx+2], a = data[idx+3];
            if(a < 128) continue;
            const luma = 0.299*r + 0.587*g + 0.114*b;
            let h = Math.ceil((luma / 255) * layers); if(h < 1) h = 1;
            state.heightMap[`${x},${y}`] = h;
        }
    }
    document.getElementById('layerSlider').max = layers;
    document.getElementById('layerSlider').value = layers;
    state.viewLayer = layers;
    document.getElementById('layer-display').innerText = `${layers} / ${layers}`;
    if(!silent) draw();
}

function updateLayerView(val) { state.viewLayer = parseInt(val); document.getElementById('layer-display').innerText = `${val} / ${state.maxLayers}`; draw(); }
function updateExplode(val) { state.explodeVal = parseInt(val); document.getElementById('explode-val').innerText = `${val}%`; draw(); }

function reprocessCurrentImg() {
    if (!state.sourceImgData) { alert("请先导入图片!"); return; }
    const newWidth = parseInt(document.getElementById('targetRes').value) || 60;
    const aspect = state.sourceH / state.sourceW;
    const newHeight = Math.floor(newWidth * aspect);
    state.gridW = newWidth; state.gridH = newHeight;
    processPixelation(state.sourceImgData, state.sourceW, state.sourceH, newWidth, newHeight);
    resizeAll();
    state.offsetX = (viewport.clientWidth - newWidth*state.scale)/2; state.offsetY = (viewport.clientHeight - newHeight*state.scale)/2;
    if(state.mode === '3d') autoGenerate3D(true);
    draw();
}

function processPixelation(srcData, srcW, srcH, targetW, targetH) {
    const tmpCv = document.createElement('canvas'); tmpCv.width = targetW; tmpCv.height = targetH;
    const tmpCtx = tmpCv.getContext('2d');
    const srcCv = document.createElement('canvas'); srcCv.width = srcW; srcCv.height = srcH;
    srcCv.getContext('2d').putImageData(srcData, 0, 0);
    tmpCtx.drawImage(srcCv, 0, 0, targetW, targetH);
    const data = tmpCtx.getImageData(0, 0, targetW, targetH).data;
    const paletteRGB = PALETTE.map(p => { const v = parseInt(p.hex.slice(1), 16); return [(v>>16)&0xff, (v>>8)&0xff, v&0xff]; });
    state.pixels = {}; state.heightMap = {};
    const useDither = document.getElementById('ditherCheck').checked;

    for(let y=0; y<targetH; y++) {
        for(let x=0; x<targetW; x++) {
            const idx = (y*targetW + x)*4;
            const oldR = data[idx], oldG = data[idx+1], oldB = data[idx+2];
            let bestDist = Infinity, bestP = 0;
            for(let i=0; i<paletteRGB.length; i++) {
                const [pr, pg, pb] = paletteRGB[i];
                const dist = (oldR-pr)**2 + (oldG-pg)**2 + (oldB-pb)**2;
                if(dist < bestDist) { bestDist=dist; bestP=i; }
            }
            state.pixels[`${x},${y}`] = bestP;
            state.heightMap[`${x},${y}`] = 1; 
            if(useDither) {
                const [nr, ng, nb] = paletteRGB[bestP];
                const er = oldR - nr, eg = oldG - ng, eb = oldB - nb;
                function addErr(dx, dy, f) { if(x+dx>=0 && x+dx<targetW && y+dy<targetH) { const nIdx = ((y+dy)*targetW + (x+dx))*4; data[nIdx] += er * f; data[nIdx+1] += eg * f; data[nIdx+2] += eb * f; } }
                addErr(1, 0, 7/16); addErr(-1, 1, 3/16); addErr(0, 1, 5/16); addErr(1, 1, 1/16);
            }
        }
    }
}

function applyZoom(newScale, cx, cy) {
    const oldScale = state.scale; state.scale = Math.max(5, Math.min(150, newScale));
    const rect = viewport.getBoundingClientRect(); const mx = cx - rect.left; const my = cy - rect.top;
    state.offsetX = mx - (mx - state.offsetX) * (state.scale / oldScale); state.offsetY = my - (my - state.offsetY) * (state.scale / oldScale);
    draw();
}

function updateMaterialList() {
    const counts = {};
    let total = 0;
    for(let key in state.pixels) {
        const idx = state.pixels[key];
        counts[idx] = (counts[idx] || 0) + 1;
        total++;
    }
    materialListEl.innerHTML = '';
    totalBeadsEl.innerText = `${total} 颗`;
    PALETTE.forEach((p, idx) => {
        const count = counts[idx] || 0;
        if(count > 0 || idx === state.curColorIdx) {
            const item = document.createElement('div');
            item.className = `material-item ${idx === state.curColorIdx ? 'active' : ''}`;
            item.onclick = () => selectColor(idx);
            item.innerHTML = `
                <div class="list-swatch" style="background-color: ${p.hex}"></div>
                <div class="list-info"><b>${p.id}</b> ${p.name}</div>
                <div class="list-count">${count}</div>
            `;
            materialListEl.appendChild(item);
        }
    });
}

function selectColor(idx) { state.curColorIdx = idx; updateMaterialList(); setTool('pencil'); }
function copyList() {
    let text = "--- 拼豆材料清单 ---\n";
    const counts = {};
    for(let key in state.pixels) counts[state.pixels[key]] = (counts[state.pixels[key]] || 0) + 1;
    PALETTE.forEach((p, idx) => { if(counts[idx]) text += `[${p.id}] ${p.name}: ${counts[idx]}颗\n`; });
    text += `总计: ${Object.values(counts).reduce((a,b)=>a+b, 0)} 颗`;
    navigator.clipboard.writeText(text).then(() => alert('已复制!'));
}

function draw() {
    const s = state.scale; const ox = state.offsetX; const oy = state.offsetY;
    const shape = document.getElementById('shapeSelect').value; // 实时获取形状
    
    ctx.fillStyle = '#09090b'; ctx.fillRect(0, 0, cvs.width, cvs.height);
    ctx.save(); ctx.translate(ox, oy);

    if (state.mode === '3d') {
        const offsetPerLayer = s * 0.15; 
        const explodeY = state.explodeVal * (s * 0.05); 
        const singleMode = document.getElementById('singleLayerCheck').checked;

        ctx.strokeStyle = '#333'; ctx.lineWidth = 1; ctx.beginPath();
        for(let i=0; i<=state.gridW; i++) { ctx.moveTo(i*s, 0); ctx.lineTo(i*s, state.gridH*s); }
        for(let i=0; i<=state.gridH; i++) { ctx.moveTo(0, i*s); ctx.lineTo(state.gridW*s, i*s); }
        ctx.stroke();

        const startL = singleMode ? state.viewLayer : 1;
        const endL = state.viewLayer;

        for(let l=startL; l<=endL; l++) {
            const layerOffsetX = -offsetPerLayer * (l-1);
            const layerOffsetY = -offsetPerLayer * (l-1) - (explodeY * (l-1));
            
            if(!singleMode && state.explodeVal > 5 && l > 1) {
                ctx.save(); ctx.translate(layerOffsetX, layerOffsetY + explodeY * 0.5); ctx.fillStyle = 'rgba(0,0,0,0.3)';
                for(let key in state.pixels) {
                    if ((state.heightMap[key] || 1) >= l) {
                        const [x, y] = key.split(',').map(Number);
                        if(shape==='circle') { ctx.beginPath(); ctx.arc(x*s+s/2, y*s+s/2, s/2, 0, Math.PI*2); ctx.fill(); }
                        else { ctx.fillRect(x*s, y*s, s, s); }
                    }
                }
                ctx.restore();
            }

            ctx.save(); ctx.translate(layerOffsetX, layerOffsetY);
            for(let key in state.pixels) {
                const h = state.heightMap[key] || 1;
                if (h >= l) {
                    const [x, y] = key.split(',').map(Number);
                    const p = PALETTE[state.pixels[key]];
                    const drawX = x*s; const drawY = y*s;

                    if(l < h && !singleMode && state.explodeVal < 10) {
                         ctx.fillStyle = '#000'; 
                         if(shape==='circle') { ctx.beginPath(); ctx.arc(drawX + s/2 + 2, drawY + s/2 + 2, s/2, 0, Math.PI*2); ctx.fill(); }
                         else { ctx.fillRect(drawX+2, drawY+2, s, s); }
                    }

                    ctx.fillStyle = p.hex;
                    if(shape === 'circle') {
                        ctx.beginPath(); ctx.arc(drawX + s/2, drawY + s/2, s/2 - 1, 0, Math.PI*2); ctx.fill();
                        ctx.fillStyle = 'rgba(255,255,255,0.15)'; ctx.beginPath(); ctx.arc(drawX + s/2 - s/6, drawY + s/2 - s/6, s/6, 0, Math.PI*2); ctx.fill();
                        ctx.fillStyle = 'rgba(0,0,0,0.2)'; ctx.beginPath(); ctx.arc(drawX + s/2, drawY + s/2, s/8, 0, Math.PI*2); ctx.fill();
                    } else {
                        ctx.fillRect(drawX + 0.5, drawY + 0.5, s - 1, s - 1);
                        ctx.fillStyle = 'rgba(255,255,255,0.1)'; ctx.fillRect(drawX, drawY, s, s/3);
                    }
                }
            }
            ctx.restore();
        }

    } else {
        ctx.beginPath(); ctx.lineWidth = 1; ctx.strokeStyle = '#27272a';
        for(let i=0; i<=state.gridW; i++) { ctx.moveTo(i*s, 0); ctx.lineTo(i*s, state.gridH*s); }
        for(let i=0; i<=state.gridH; i++) { ctx.moveTo(0, i*s); ctx.lineTo(state.gridW*s, i*s); }
        ctx.stroke();

        const showId = s > 22; 
        for(let key in state.pixels) {
            const [x, y] = key.split(',').map(Number);
            const p = PALETTE[state.pixels[key]];
            if(!p) continue;
            ctx.fillStyle = p.hex;
            if(shape === 'circle') {
                ctx.beginPath(); ctx.arc(x*s + s/2, y*s + s/2, s/2 - s*0.05, 0, Math.PI*2); ctx.fill();
                if(showId) { ctx.fillStyle = 'rgba(255,255,255,0.3)'; ctx.beginPath(); ctx.arc(x*s + s/2, y*s + s/2, s/6, 0, Math.PI*2); ctx.fill(); }
            } else {
                ctx.fillRect(x*s + 0.5, y*s + 0.5, s - 1, s - 1);
            }
            if(showId) {
                ctx.fillStyle = getContrastColor(p.hex) === '#fff' ? '#fff' : '#000';
                ctx.font = `bold ${Math.floor(s*0.35)}px Arial`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
                ctx.fillText(p.id, x*s + s/2, y*s + s/2);
            }
        }
        ctx.beginPath(); ctx.lineWidth = 2; ctx.strokeStyle = '#52525b';
        for(let i=0; i<=state.gridW; i+=10) { ctx.moveTo(i*s, 0); ctx.lineTo(i*s, state.gridH*s); }
        for(let i=0; i<=state.gridH; i+=10) { ctx.moveTo(0, i*s); ctx.lineTo(state.gridW*s, i*s); }
        ctx.stroke();
    }

    ctx.strokeStyle = '#6366f1'; ctx.lineWidth = 2;
    ctx.strokeRect(0, 0, state.gridW*s, state.gridH*s);
    ctx.restore();
    drawRulers(); updateMaterialList();
}

function drawRulers() {
    const s = state.scale; const ox = state.offsetX; const oy = state.offsetY;
    const ctxT = ctxRTop; ctxT.clearRect(0,0,rulerTop.width,32);
    ctxT.fillStyle = '#a1a1aa'; ctxT.font = '11px Arial'; ctxT.textAlign = 'center'; ctxT.beginPath(); ctxT.strokeStyle = '#52525b';
    const startX = Math.max(0, Math.floor(-ox / s)); const endX = Math.min(state.gridW, Math.ceil((cvs.width - ox) / s));
    for(let i=startX; i<=endX; i++) {
        const sx = ox + i * s;
        if(i % 10 === 0) { ctxT.moveTo(sx, 16); ctxT.lineTo(sx, 32); ctxT.fillText(i, sx, 12); }
        else if (i % 5 === 0 && s>10) { ctxT.moveTo(sx, 24); ctxT.lineTo(sx, 32); }
    }
    ctxT.stroke();
    const ctxL = ctxRLeft; ctxL.clearRect(0,0,32,rulerLeft.height);
    ctxL.fillStyle = '#a1a1aa'; ctxL.font = '11px Arial'; ctxL.textAlign = 'center'; ctxL.textBaseline = 'middle'; ctxL.beginPath(); ctxL.strokeStyle = '#52525b';
    const startY = Math.max(0, Math.floor(-oy / s)); const endY = Math.min(state.gridH, Math.ceil((cvs.height - oy) / s));
    for(let i=startY; i<=endY; i++) {
        const sy = oy + i * s;
        if(i % 10 === 0) {
            ctxL.moveTo(16, sy); ctxL.lineTo(32, sy);
            ctxL.save(); ctxL.translate(12, sy); ctxL.rotate(-Math.PI/2); ctxL.fillText(i, 0, 0); ctxL.restore();
        } else if (i % 5 === 0 && s>10) { ctxL.moveTo(24, sy); ctxL.lineTo(32, sy); }
    }
    ctxL.stroke();
}

function getContrastColor(hex) { const r = parseInt(hex.substr(1,2),16), g = parseInt(hex.substr(3,2),16), b = parseInt(hex.substr(5,2),16); return (r*0.299 + g*0.587 + b*0.114) > 128 ? '#000' : '#fff'; }
function resizeAll() { const vw = viewport.clientWidth; const vh = viewport.clientHeight; cvs.width = vw; cvs.height = vh; rulerTop.width = vw; rulerTop.height = 32; rulerLeft.width = 32; rulerLeft.height = vh; draw(); }
function mergeSimilarColors() {
    const used = new Set(); for(let k in state.pixels) used.add(state.pixels[k]);
    const usedArr = Array.from(used);
    if(usedArr.length < 2) { alert("颜色太少无法合并"); return; }
    let minDiff = Infinity, mergePair = [-1, -1];
    const rgbs = {}; usedArr.forEach(idx => { const v = parseInt(PALETTE[idx].hex.slice(1), 16); rgbs[idx] = [(v>>16)&0xff, (v>>8)&0xff, v&0xff]; });
    for(let i=0; i<usedArr.length; i++) { for(let j=i+1; j<usedArr.length; j++) { const c1 = rgbs[usedArr[i]], c2 = rgbs[usedArr[j]]; const dist = Math.sqrt((c1[0]-c2[0])**2 + (c1[1]-c2[1])**2 + (c1[2]-c2[2])**2); if(dist < minDiff) { minDiff = dist; mergePair = [usedArr[i], usedArr[j]]; } } }
    const [keep, remove] = mergePair;
    let count = 0; for(let k in state.pixels) { if(state.pixels[k] === remove) { state.pixels[k] = keep; count++; } }
    draw(); alert(`已合并 [${PALETTE[remove].name}] 到 [${PALETTE[keep].name}]`);
}
function exportSlices() {
    const layers = state.maxLayers; const unit = 20; const w = state.gridW * unit; const h = state.gridH * unit; const margin = 40;
    const expCv = document.createElement('canvas'); expCv.width = w + margin*2; expCv.height = (h + margin) * layers + margin;
    const ctx = expCv.getContext('2d'); ctx.fillStyle = 'white'; ctx.fillRect(0,0,expCv.width, expCv.height);
    // V10.3 修正:同步导出形状
    const shape = document.getElementById('shapeSelect').value;
    
    for(let l=1; l<=layers; l++) {
        const startY = (l-1)*(h+margin) + margin;
        ctx.fillStyle = '#000'; ctx.font = '20px Arial'; ctx.textAlign = 'left'; ctx.fillText(`第 ${l} 层 (Layer ${l})`, margin, startY - 10);
        ctx.translate(margin, startY);
        for(let key in state.pixels) {
            const hVal = state.heightMap[key] || 1;
            if(hVal >= l) {
                const [x, y] = key.split(',').map(Number); const p = PALETTE[state.pixels[key]];
                ctx.fillStyle = p.hex; 
                if (shape === 'circle') {
                    ctx.beginPath(); ctx.arc(x*unit + unit/2, y*unit + unit/2, unit/2 - 1, 0, Math.PI*2); ctx.fill();
                    ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(x*unit + unit/2, y*unit + unit/2, unit/6, 0, Math.PI*2); ctx.fill();
                } else {
                    ctx.fillRect(x*unit, y*unit, unit, unit);
                }
            }
        }
        ctx.strokeStyle = '#ddd'; ctx.lineWidth=1;
        for(let i=0; i<=state.gridW; i++) { ctx.moveTo(i*unit, 0); ctx.lineTo(i*unit, h); } for(let i=0; i<=state.gridH; i++) { ctx.moveTo(0, i*unit); ctx.lineTo(w, i*unit); } ctx.stroke();
        ctx.translate(-margin, -startY);
    }
    const link = document.createElement('a'); link.download = `立体拼豆_分层图纸.png`; link.href = expCv.toDataURL(); link.click();
}
function exportImageWithRuler() {
    const beadSizeMM = 5; const pxPerMM = 11.8; const unit = Math.round(beadSizeMM * pxPerMM); const margin = unit * 3;
    const expCvs = document.createElement('canvas'); expCvs.width = state.gridW * unit + margin; expCvs.height = state.gridH * unit + margin;
    const eCtx = expCvs.getContext('2d'); eCtx.fillStyle = 'white'; eCtx.fillRect(0, 0, expCvs.width, expCvs.height);
    eCtx.fillStyle = '#000'; eCtx.font = `bold ${unit*0.8}px Arial`; eCtx.textAlign = 'center'; eCtx.textBaseline = 'middle';
    
    // V10.3 修正:同步导出形状
    const shape = document.getElementById('shapeSelect').value;

    for(let i=0; i<=state.gridW; i++) { if(i%5===0) { const x = margin + i*unit; eCtx.fillText(i, x, margin/2); eCtx.fillRect(x, margin-unit, 4, unit); } }
    for(let i=0; i<=state.gridH; i++) { if(i%5===0) { const y = margin + i*unit; eCtx.fillText(i, margin/2, y); eCtx.fillRect(margin-unit, y, unit, 4); } }
    eCtx.translate(margin, margin);
    for(let key in state.pixels) {
        const [x, y] = key.split(',').map(Number); const p = PALETTE[state.pixels[key]]; eCtx.fillStyle = p.hex;
        if (shape === 'circle') {
            eCtx.beginPath(); eCtx.arc(x*unit + unit/2, y*unit + unit/2, unit/2 - unit*0.05, 0, Math.PI*2); eCtx.fill();
            eCtx.fillStyle = '#fff'; eCtx.beginPath(); eCtx.arc(x*unit + unit/2, y*unit + unit/2, unit*0.15, 0, Math.PI*2); eCtx.fill();
        } else {
            eCtx.fillRect(x*unit, y*unit, unit, unit);
        }
        eCtx.fillStyle = getContrastColor(p.hex) === '#fff' ? '#fff' : '#000'; eCtx.font = `bold ${unit*0.35}px Arial`; eCtx.fillText(p.id, x*unit + unit/2, y*unit + unit/2);
    }
    eCtx.strokeStyle = '#999'; eCtx.lineWidth = 3; for(let i=0; i<=state.gridW; i++) { eCtx.moveTo(i*unit, 0); eCtx.lineTo(i*unit, state.gridH*unit); } for(let i=0; i<=state.gridH; i++) { eCtx.moveTo(0, i*unit); eCtx.lineTo(state.gridW*unit, i*unit); } eCtx.stroke();
    const link = document.createElement('a'); link.download = `拼豆工程图.png`; link.href = expCvs.toDataURL(); link.click();
}

// 裁剪复用 (整数修复版)
const modal = document.getElementById('cropModal'); const cropImg = document.getElementById('crop-img'); const cropBox = document.getElementById('crop-box'); let cropState = { startX:0, startY:0 };
function handleFile(input) {
    if(!input.files[0]) return; const reader = new FileReader();
    reader.onload = e => { cropImg.src = e.target.result; cropImg.onload = () => { modal.style.display = 'flex'; cropBox.style.display = 'block'; cropBox.style.left = '50px'; cropBox.style.top = '50px'; cropBox.style.width = '100px'; cropBox.style.height = '100px'; } };
    reader.readAsDataURL(input.files[0]); input.value = '';
}
function closeModal() { modal.style.display = 'none'; }
function startCropDrag(e) { if(e.target.classList.contains('resize-handle')) return; const rect = cropBox.getBoundingClientRect(); if(e.clientX>rect.left && e.clientX<rect.right && e.clientY>rect.top && e.clientY<rect.bottom) { cropState.isDrag = true; cropState.startX = e.clientX - cropBox.offsetLeft; cropState.startY = e.clientY - cropBox.offsetTop; document.onmousemove = e => { cropBox.style.left = (e.clientX - cropState.startX) + 'px'; cropBox.style.top = (e.clientY - cropState.startY) + 'px'; }; document.onmouseup = () => { document.onmousemove=null; }; } }
function startCropResize(e) { e.stopPropagation(); const startX = e.clientX; const startY = e.clientY; const startW = cropBox.offsetWidth; const startH = cropBox.offsetHeight; document.onmousemove = e => { cropBox.style.width = (startW + e.clientX - startX) + 'px'; cropBox.style.height = (startH + e.clientY - startY) + 'px'; }; document.onmouseup = () => { document.onmousemove=null; }; }

function confirmCrop() {
    try {
        const btn = document.getElementById('btn-confirm-import'); btn.innerText = "处理中...";
        const factor = cropImg.naturalWidth / cropImg.width;
        // 强制取整修复
        const cx = Math.floor((cropBox.offsetLeft - cropImg.offsetLeft) * factor);
        const cy = Math.floor((cropBox.offsetTop - cropImg.offsetTop) * factor);
        const cw = Math.floor(cropBox.offsetWidth * factor);
        const ch = Math.floor(cropBox.offsetHeight * factor);
        if (cw <= 0 || ch <= 0) throw new Error("选区太小");

        const targetW = parseInt(document.getElementById('targetRes').value) || 60;
        const targetH = Math.floor(targetW * (ch / cw));
        document.getElementById('gridW').value = targetW; document.getElementById('gridH').value = targetH;
        state.gridW = targetW; state.gridH = targetH;

        const tmpCv = document.createElement('canvas'); tmpCv.width = cw; tmpCv.height = ch;
        const tmpCtx = tmpCv.getContext('2d');
        tmpCtx.drawImage(cropImg, cx, cy, cw, ch, 0, 0, cw, ch);
        
        state.sourceImgData = tmpCtx.getImageData(0, 0, cw, ch); state.sourceW = cw; state.sourceH = ch;
        reprocessCurrentImg(); closeModal(); btn.innerText = "✅ 确认导入";
    } catch(e) { alert("导入出错: " + e.message); console.error(e); document.getElementById('btn-confirm-import').innerText = "✅ 确认导入"; }
}

// 通用交互
viewport.onmousedown = e => { if(state.tool === 'move' || e.button === 1) { state.isDrag = true; state.lastX = e.clientX; state.lastY = e.clientY; return; } paint(e); viewport.onmousemove = paint; };
window.onmouseup = () => { state.isDrag = false; viewport.onmousemove = null; };
window.onmousemove = e => { if(state.isDrag) { state.offsetX += e.clientX - state.lastX; state.offsetY += e.clientY - state.lastY; state.lastX = e.clientX; state.lastY = e.clientY; draw(); } updateInfo(e); };
function paint(e) {
    const rect = viewport.getBoundingClientRect(); const x = Math.floor((e.clientX - rect.left - state.offsetX) / state.scale); const y = Math.floor((e.clientY - rect.top - state.offsetY) / state.scale);
    if(x<0 || x>=state.gridW || y<0 || y>=state.gridH) return;
    const key = `${x},${y}`;
    if(state.tool === 'pencil') state.pixels[key] = state.curColorIdx;
    else if(state.tool === 'eraser') delete state.pixels[key];
    else if(state.tool === 'bucket') floodFill(x, y, state.curColorIdx);
    else if(state.tool === 'picker') { if(state.pixels[key] !== undefined) selectColor(state.pixels[key]); setTool('pencil'); }
    draw();
}
function floodFill(x, y, targetIdx) {
    const oldIdx = state.pixels[`${x},${y}`]; if(oldIdx === targetIdx) return;
    const q = [[x,y]]; let count = 0;
    while(q.length && count < state.gridW * state.gridH) {
        count++; const [cx, cy] = q.pop(); const k = `${cx},${cy}`;
        if(cx<0 || cx>=state.gridW || cy<0 || cy>=state.gridH) continue;
        if(state.pixels[k] !== oldIdx) continue;
        state.pixels[k] = targetIdx; q.push([cx+1,cy], [cx-1,cy], [cx,cy+1], [cx,cy-1]);
    }
    draw();
}
function setTool(t) { state.tool = t; document.querySelectorAll('.tool-btn').forEach(b => b.classList.remove('active')); document.getElementById(`t-${t}`).classList.add('active'); viewport.style.cursor = t==='move' ? 'grab' : 'crosshair'; }
function resizeGrid() { state.gridW = parseInt(document.getElementById('gridW').value) || 60; state.gridH = parseInt(document.getElementById('gridH').value) || 60; draw(); }
function clearCanvas() { if(confirm('确定清空画布吗?')) { state.pixels={}; draw(); } }
function updateInfo(e) { document.getElementById('info-zoom').innerText = `Zoom: ${state.scale}px`; if(e) { const rect = viewport.getBoundingClientRect(); const x = Math.floor((e.clientX - rect.left - state.offsetX) / state.scale); const y = Math.floor((e.clientY - rect.top - state.offsetY) / state.scale); if(x>=0 && x<state.gridW && y>=0 && y<state.gridH) document.getElementById('info-coord').innerText = `XY: (${x}, ${y})`; } }

init();
</script>
</body>
</html>