File size: 33,397 Bytes
6e204a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>FloorGen Interactive Reverse Diffusion Player & CAD Sandbox</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <!-- Three.js for 3D Viewport -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>

  <style>
    :root {
      --bg-dark: #080C16;
      --bg-panel: rgba(15, 23, 42, 0.85);
      --border-subtle: rgba(255, 255, 255, 0.1);
      --accent-cyan: #06B6D4;
      --accent-blue: #3B82F6;
      --accent-emerald: #10B981;
      --accent-amber: #F59E0B;
      --accent-rose: #F43F5E;
      --text-main: #F8FAFC;
      --text-muted: #94A3B8;
    }

    * { box-sizing: border-box; margin: 0; padding: 0; }

    body {
      font-family: 'Plus Jakarta Sans', sans-serif;
      background: var(--bg-dark);
      color: var(--text-main);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      min-height: 100vh;
      overflow-x: hidden;
      padding: 12px;
    }

    .app-container {
      width: 100%;
      max-width: 960px;
      background: var(--bg-panel);
      border: 1px solid var(--border-subtle);
      border-radius: 16px;
      padding: 20px;
      box-shadow: 0 25px 60px rgba(0, 0, 0, 0.6);
      backdrop-filter: blur(16px);
      display: flex;
      flex-direction: column;
      gap: 16px;
    }

    /* Header & Mode Selectors */
    .header-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      gap: 10px;
      border-bottom: 1px solid var(--border-subtle);
      padding-bottom: 12px;
    }

    .brand-title {
      font-size: 16px;
      font-weight: 800;
      color: #FFF;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .brand-title i {
      color: var(--accent-cyan);
    }

    .badge-phase {
      font-size: 11px;
      font-family: 'JetBrains Mono', monospace;
      padding: 4px 10px;
      border-radius: 6px;
      font-weight: 700;
      background: rgba(6, 182, 212, 0.15);
      border: 1px solid rgba(6, 182, 212, 0.35);
      color: #38BDF8;
    }

    /* Controls Grid */
    .controls-row {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 10px;
    }

    .select-box {
      background: rgba(10, 15, 30, 0.8);
      border: 1px solid var(--border-subtle);
      border-radius: 10px;
      padding: 8px 12px;
      display: flex;
      flex-direction: column;
      gap: 4px;
    }

    .select-label {
      font-size: 11px;
      font-weight: 700;
      color: var(--text-muted);
      text-transform: uppercase;
      letter-spacing: 0.05em;
    }

    select {
      background: transparent;
      border: none;
      color: #FFF;
      font-family: inherit;
      font-size: 13px;
      font-weight: 600;
      cursor: pointer;
      outline: none;
    }

    select option {
      background: #0F172A;
      color: #FFF;
    }

    /* Main Viewport & Stage */
    .viewport-wrapper {
      display: grid;
      grid-template-columns: 1fr 280px;
      gap: 16px;
    }

    @media (max-width: 768px) {
      .viewport-wrapper { grid-template-columns: 1fr; }
    }

    .canvas-stage {
      height: 380px;
      background: #FAFAFA;
      border-radius: 12px;
      position: relative;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: inset 0 0 20px rgba(0, 0, 0, 0.08);
    }

    #threeCanvas {
      width: 100%;
      height: 100%;
      display: none;
    }

    /* Sidebar Telemetry */
    .sidebar-panel {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .telemetry-card {
      background: rgba(10, 15, 30, 0.6);
      border: 1px solid var(--border-subtle);
      border-radius: 10px;
      padding: 12px;
      display: flex;
      flex-direction: column;
      gap: 6px;
    }

    .telemetry-title {
      font-size: 11px;
      font-weight: 700;
      color: var(--text-muted);
      text-transform: uppercase;
      letter-spacing: 0.05em;
    }

    .metric-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12.5px;
    }

    .metric-val {
      font-family: 'JetBrains Mono', monospace;
      font-weight: 700;
      color: #38BDF8;
    }

    .phase-explainer {
      font-size: 11.5px;
      line-height: 1.45;
      color: #CBD5E1;
      background: rgba(59, 130, 246, 0.1);
      border-left: 3px solid var(--accent-cyan);
      padding: 8px 10px;
      border-radius: 4px;
    }

    /* Bottom Scrubber & Buttons */
    .scrubber-panel {
      background: rgba(10, 15, 30, 0.7);
      border: 1px solid var(--border-subtle);
      border-radius: 12px;
      padding: 12px 16px;
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .scrubber-labels {
      display: flex;
      justify-content: space-between;
      font-size: 11.5px;
      font-family: 'JetBrains Mono', monospace;
      color: var(--text-muted);
    }

    input[type=range] {
      width: 100%;
      height: 6px;
      accent-color: var(--accent-cyan);
      cursor: pointer;
    }

    .btn-toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      gap: 8px;
    }

    .btn-group-left, .btn-group-right {
      display: flex;
      gap: 8px;
    }

    button {
      background: rgba(255, 255, 255, 0.06);
      border: 1px solid var(--border-subtle);
      color: #F8FAFC;
      padding: 8px 14px;
      border-radius: 8px;
      font-size: 12px;
      font-weight: 600;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      gap: 6px;
      transition: all 0.2s;
    }

    button:hover {
      background: rgba(255, 255, 255, 0.15);
      border-color: rgba(255, 255, 255, 0.3);
    }

    .btn-primary {
      background: linear-gradient(135deg, #2563EB, #06B6D4);
      border: none;
      font-weight: 700;
    }

    .btn-primary:hover {
      opacity: 0.9;
    }

    .view-pill {
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid var(--border-subtle);
      padding: 6px 12px;
      border-radius: 20px;
      font-size: 11px;
      font-weight: 700;
      cursor: pointer;
    }

    .view-pill.active {
      background: var(--accent-blue);
      border-color: var(--accent-blue);
      color: white;
    }
  </style>
</head>
<body>

  <div class="app-container">

    <!-- Top Header -->
    <div class="header-bar">
      <div class="brand-title">
        <i class="fas fa-layer-group"></i>
        <span>FloorGen Reverse Diffusion Sandbox</span>
      </div>
      <div style="display: flex; gap: 8px; align-items: center;">
        <span class="view-pill active" id="pill2D" onclick="switchView('2d')">2D Vector CAD</span>
        <span class="view-pill" id="pill3D" onclick="switchView('3d')">3D Isometric</span>
        <span class="badge-phase" id="phaseBadge">T = 0 | Regularized CAD (100%)</span>
      </div>
    </div>

    <!-- Parameter Controls Grid -->
    <div class="controls-row">
      <div class="select-box">
        <span class="select-label">1. Architectural Archetype</span>
        <select id="archetypeSelect" onchange="onArchetypeChange()">
          <option value="standard_2b1b">2B1B Standard Urban Apartment (Living Core)</option>
          <option value="executive_3b2b" selected>3B2B Family Executive Suite (Ensuite + Study)</option>
          <option value="micro_1b1b">1B1B Micro-Loft Studio (Metropolitan)</option>
          <option value="penthouse_4b3b">4B3B Luxury Penthouse (Wraparound Balcony)</option>
          <option value="corner_2b2b">2B2B Dual-Balcony Corner Unit (Cross-Breeze)</option>
          <option value="multigen_3b2b">3B2.5B Multi-Generational Villa (Dual Master)</option>
        </select>
      </div>

      <div class="select-box">
        <span class="select-label">2. Generative Diffusion Core</span>
        <select id="modelModeSelect" onchange="updateSimulation()">
          <option value="floorgen_rag" selected>FloorGen RAG-Diffusion (Ours, k=5 Exemplars)</option>
          <option value="housediff_k0">HouseDiffusion Baseline (k=0, Unconstrained)</option>
          <option value="housegan_pp">House-GAN++ Baseline (Relational GAN Jitter)</option>
        </select>
      </div>

      <div class="select-box">
        <span class="select-label">3. Site Footprint Boundary</span>
        <select id="boundarySelect" onchange="updateSimulation()">
          <option value="rectangular">Standard Rectangular (Aspect 1.2:1)</option>
          <option value="wide">Wide Horizon (Aspect 1.6:1)</option>
          <option value="corner">L-Shape Corner Profile</option>
        </select>
      </div>
    </div>

    <!-- Main Viewport + Telemetry Panel -->
    <div class="viewport-wrapper">
      
      <!-- Stage -->
      <div class="canvas-stage" id="canvasStage">
        <div id="svgContainer" style="width: 100%; height: 100%;"></div>
        <div id="threeCanvas"></div>
      </div>

      <!-- Telemetry Sidebar -->
      <div class="sidebar-panel">
        <div class="telemetry-card">
          <span class="telemetry-title">Trajectory Telemetry</span>
          <div class="metric-row">
            <span>Denoising Step:</span>
            <span class="metric-val" id="valStep">t = 0 / 30</span>
          </div>
          <div class="metric-row">
            <span>Graph Compatibility:</span>
            <span class="metric-val" id="valCompat" style="color: #34D399;">84.7%</span>
          </div>
          <div class="metric-row">
            <span>Graph Edit Dist (GED):</span>
            <span class="metric-val" id="valGED">0.18</span>
          </div>
          <div class="metric-row">
            <span>Inter-Room Overlap:</span>
            <span class="metric-val" id="valOverlap" style="color: #10B981;">0.00 sq.ft</span>
          </div>
          <div class="metric-row">
            <span>Total Floor Area:</span>
            <span class="metric-val" id="valArea">1,280 sq.ft</span>
          </div>
        </div>

        <div class="telemetry-card">
          <span class="telemetry-title">Diffusion Phase Explanation</span>
          <div class="phase-explainer" id="phaseExplanation">
            <strong>Phase 4: Manhattan CAD Vectorization</strong><br>
            Continuous denoised coordinates are snapped to regular Manhattan grid axes. Contact interfaces infer architectural door openings with quarter-circle clearance arcs.
          </div>
        </div>
      </div>

    </div>

    <!-- Scrubber & Controls Toolbar -->
    <div class="scrubber-panel">
      <div class="scrubber-labels">
        <span><i class="fas fa-random"></i> Gaussian Noise ($T=30$)</span>
        <span id="progressText" style="color: var(--accent-cyan); font-weight: bold;">Step 30/30 (100% Converged)</span>
        <span><i class="fas fa-drafting-compass"></i> Manhattan CAD ($T=0$)</span>
      </div>
      <input type="range" id="diffusionSlider" min="0" max="30" value="30" oninput="onScrubStep(this.value)">

      <div class="btn-toolbar">
        <div class="btn-group-left">
          <button class="btn-primary" id="btnPlay" onclick="togglePlay()">
            <i class="fas fa-play"></i> <span>Play Trajectory</span>
          </button>
          <button onclick="stepBackward()"><i class="fas fa-backward-step"></i> Step -1</button>
          <button onclick="stepForward()"><i class="fas fa-forward-step"></i> Step +1</button>
          <button onclick="reseedNoise()"><i class="fas fa-dice"></i> New Noise Seed</button>
        </div>

        <div class="btn-group-right">
          <button onclick="downloadFloorplanSVG()"><i class="fas fa-download"></i> SVG</button>
          <button onclick="exportFloorplanJSON()"><i class="fas fa-file-code"></i> JSON</button>
        </div>
      </div>
    </div>

  </div>

  <script>
    // Architectural Archetype Database
    const ARCHETYPES = {
      executive_3b2b: {
        name: "3B2B Family Executive",
        area_sqft: 1480,
        rooms: [
          { name: "Living Room", box: [80, 75, 185, 180], fill: "#DBEAFE", stroke: "#2563EB", color3d: 0x93C5FD },
          { name: "Dining Room", box: [80, 20, 140, 75], fill: "#EDE9FE", stroke: "#7C3AED", color3d: 0xC4B5FD },
          { name: "Kitchen", box: [15, 20, 80, 100], fill: "#FFEDD5", stroke: "#EA580C", color3d: 0xFDBA74 },
          { name: "Master Suite", box: [185, 75, 245, 180], fill: "#FEF3C7", stroke: "#D97706", color3d: 0xFDE68A },
          { name: "Ensuite Bath", box: [185, 20, 245, 75], fill: "#CCFBF1", stroke: "#0D9488", color3d: 0x99F6E4 },
          { name: "Second Bed", box: [15, 100, 80, 180], fill: "#FEF9C3", stroke: "#CA8A04", color3d: 0xFEF08A },
          { name: "Study / Library", box: [140, 20, 185, 75], fill: "#F1F5F9", stroke: "#475569", color3d: 0xE2E8F0 },
          { name: "Balcony Terrace", box: [80, 180, 185, 225], fill: "#DCFCE7", stroke: "#16A34A", color3d: 0xA7F3D0 }
        ],
        doors: [
          [[80, 50], [80, 62]], [[185, 120], [185, 132]], [[80, 135], [80, 147]], [[185, 45], [185, 57]], [[130, 179], [146, 179]]
        ]
      },
      standard_2b1b: {
        name: "2B1B Standard Urban",
        area_sqft: 980,
        rooms: [
          { name: "Living Room", box: [75, 55, 185, 175], fill: "#DBEAFE", stroke: "#2563EB", color3d: 0x93C5FD },
          { name: "Master Bedroom", box: [185, 55, 245, 135], fill: "#FEF3C7", stroke: "#D97706", color3d: 0xFDE68A },
          { name: "Second Bedroom", box: [185, 135, 245, 215], fill: "#FEF9C3", stroke: "#CA8A04", color3d: 0xFEF08A },
          { name: "Bathroom", box: [15, 135, 75, 210], fill: "#CCFBF1", stroke: "#0D9488", color3d: 0x99F6E4 },
          { name: "Kitchen", box: [15, 55, 75, 135], fill: "#FFEDD5", stroke: "#EA580C", color3d: 0xFDBA74 },
          { name: "Balcony", box: [75, 175, 185, 220], fill: "#DCFCE7", stroke: "#16A34A", color3d: 0xA7F3D0 }
        ],
        doors: [
          [[74, 85], [74, 97]], [[184, 85], [184, 97]], [[184, 160], [184, 172]], [[120, 174], [136, 174]]
        ]
      },
      micro_1b1b: {
        name: "1B1B Micro-Loft",
        area_sqft: 580,
        rooms: [
          { name: "Living Lounge", box: [80, 40, 220, 160], fill: "#DBEAFE", stroke: "#2563EB", color3d: 0x93C5FD },
          { name: "Kitchenette", box: [20, 40, 80, 120], fill: "#FFEDD5", stroke: "#EA580C", color3d: 0xFDBA74 },
          { name: "Bedroom", box: [80, 160, 180, 225], fill: "#FEF3C7", stroke: "#D97706", color3d: 0xFDE68A },
          { name: "Bath & WC", box: [20, 120, 80, 200], fill: "#CCFBF1", stroke: "#0D9488", color3d: 0x99F6E4 },
          { name: "Juliet Balcony", box: [180, 160, 220, 225], fill: "#DCFCE7", stroke: "#16A34A", color3d: 0xA7F3D0 }
        ],
        doors: [
          [[80, 80], [80, 92]], [[80, 180], [80, 192]], [[130, 159], [146, 159]]
        ]
      },
      penthouse_4b3b: {
        name: "4B3B Luxury Penthouse",
        area_sqft: 2250,
        rooms: [
          { name: "Grand Living Room", box: [75, 60, 190, 170], fill: "#DBEAFE", stroke: "#2563EB", color3d: 0x93C5FD },
          { name: "Formal Dining", box: [75, 15, 140, 60], fill: "#EDE9FE", stroke: "#7C3AED", color3d: 0xC4B5FD },
          { name: "Chef's Kitchen", box: [15, 15, 75, 95], fill: "#FFEDD5", stroke: "#EA580C", color3d: 0xFDBA74 },
          { name: "Master Suite", box: [190, 60, 250, 160], fill: "#FEF3C7", stroke: "#D97706", color3d: 0xFDE68A },
          { name: "Master Bath", box: [190, 15, 250, 60], fill: "#CCFBF1", stroke: "#0D9488", color3d: 0x99F6E4 },
          { name: "Guest Bed 1", box: [15, 95, 75, 165], fill: "#FEF9C3", stroke: "#CA8A04", color3d: 0xFEF08A },
          { name: "Guest Bed 2", box: [15, 165, 75, 230], fill: "#FEF9C3", stroke: "#CA8A04", color3d: 0xFEF08A },
          { name: "Study Room", box: [140, 15, 190, 60], fill: "#F1F5F9", stroke: "#475569", color3d: 0xE2E8F0 },
          { name: "Wraparound Deck", box: [75, 170, 250, 230], fill: "#DCFCE7", stroke: "#16A34A", color3d: 0xA7F3D0 }
        ],
        doors: [
          [[75, 40], [75, 52]], [[190, 100], [190, 112]], [[75, 125], [75, 137]], [[125, 169], [145, 169]]
        ]
      },
      corner_2b2b: {
        name: "2B2B Corner Suite",
        area_sqft: 1150,
        rooms: [
          { name: "Corner Living", box: [75, 45, 185, 165], fill: "#DBEAFE", stroke: "#2563EB", color3d: 0x93C5FD },
          { name: "Master Bed", box: [15, 45, 75, 145], fill: "#FEF3C7", stroke: "#D97706", color3d: 0xFDE68A },
          { name: "Master Bath", box: [15, 145, 75, 215], fill: "#CCFBF1", stroke: "#0D9488", color3d: 0x99F6E4 },
          { name: "Kitchen/Dining", box: [75, 165, 140, 225], fill: "#FFEDD5", stroke: "#EA580C", color3d: 0xFDBA74 },
          { name: "Second Bed", box: [185, 45, 245, 145], fill: "#FEF9C3", stroke: "#CA8A04", color3d: 0xFEF08A },
          { name: "Corner Balcony", box: [185, 145, 245, 225], fill: "#DCFCE7", stroke: "#16A34A", color3d: 0xA7F3D0 }
        ],
        doors: [
          [[75, 90], [75, 102]], [[185, 90], [185, 102]], [[140, 164], [156, 164]]
        ]
      },
      multigen_3b2b: {
        name: "3B2.5B Multi-Gen Villa",
        area_sqft: 1620,
        rooms: [
          { name: "Central Great Room", box: [80, 60, 180, 175], fill: "#DBEAFE", stroke: "#2563EB", color3d: 0x93C5FD },
          { name: "Senior Master Suite", box: [15, 60, 80, 160], fill: "#FEF3C7", stroke: "#D97706", color3d: 0xFDE68A },
          { name: "Senior Bath", box: [15, 160, 80, 225], fill: "#CCFBF1", stroke: "#0D9488", color3d: 0x99F6E4 },
          { name: "Open Kitchen/Dining", box: [15, 15, 80, 60], fill: "#FFEDD5", stroke: "#EA580C", color3d: 0xFDBA74 },
          { name: "Primary Master", box: [180, 60, 245, 160], fill: "#FEF3C7", stroke: "#D97706", color3d: 0xFDE68A },
          { name: "Children's Bed", box: [180, 160, 245, 225], fill: "#FEF9C3", stroke: "#CA8A04", color3d: 0xFEF08A },
          { name: "Study / Office", box: [140, 15, 180, 60], fill: "#F1F5F9", stroke: "#475569", color3d: 0xE2E8F0 },
          { name: "Garden Veranda", box: [80, 175, 180, 225], fill: "#DCFCE7", stroke: "#16A34A", color3d: 0xA7F3D0 }
        ],
        doors: [
          [[80, 105], [80, 117]], [[180, 105], [180, 117]], [[125, 174], [141, 174]]
        ]
      }
    };

    let currentArchetypeKey = "executive_3b2b";
    let isPlaying = false;
    let playInterval = null;
    let noiseSeed = 42;
    let is3D = false;
    let scene, camera, renderer, controls, roomMeshes = [];

    function onArchetypeChange() {
      currentArchetypeKey = document.getElementById("archetypeSelect").value;
      if (is3D) init3D();
      updateSimulation();
    }

    function reseedNoise() {
      noiseSeed = Math.floor(Math.random() * 10000);
      updateSimulation();
    }

    function onScrubStep(val) {
      updateSimulation(parseInt(val));
    }

    function stepForward() {
      let cur = parseInt(document.getElementById("diffusionSlider").value);
      if (cur < 30) {
        document.getElementById("diffusionSlider").value = cur + 1;
        updateSimulation(cur + 1);
      }
    }

    function stepBackward() {
      let cur = parseInt(document.getElementById("diffusionSlider").value);
      if (cur > 0) {
        document.getElementById("diffusionSlider").value = cur - 1;
        updateSimulation(cur - 1);
      }
    }

    function togglePlay() {
      const btn = document.getElementById("btnPlay");
      if (isPlaying) {
        clearInterval(playInterval);
        isPlaying = false;
        btn.innerHTML = '<i class="fas fa-play"></i> <span>Play Trajectory</span>';
      } else {
        isPlaying = true;
        btn.innerHTML = '<i class="fas fa-pause"></i> <span>Pause</span>';
        let cur = parseInt(document.getElementById("diffusionSlider").value);
        if (cur >= 30) cur = 0;
        playInterval = setInterval(() => {
          cur++;
          if (cur > 30) {
            clearInterval(playInterval);
            isPlaying = false;
            btn.innerHTML = '<i class="fas fa-play"></i> <span>Play Trajectory</span>';
            return;
          }
          document.getElementById("diffusionSlider").value = cur;
          updateSimulation(cur);
        }, 80);
      }
    }

    function updateSimulation(stepVal = null) {
      if (stepVal === null) {
        stepVal = parseInt(document.getElementById("diffusionSlider").value);
      }

      const progress = stepVal / 30.0; // 0.0 (Pure Noise) -> 1.0 (Full Converged CAD)
      const t_val = 30 - stepVal;
      const modelMode = document.getElementById("modelModeSelect").value;
      const arch = ARCHETYPES[currentArchetypeKey];

      // Update Phase Badge & Explanations
      let phaseName = "";
      let phaseDesc = "";
      let gedVal = 0.18;
      let compatVal = 84.7;
      let overlapSqft = 0.0;

      if (progress < 0.25) {
        phaseName = `T = ${t_val} | Pure Gaussian Noise (0-25%)`;
        phaseDesc = `<strong>Phase 1: Initial Gaussian Coordinate Sampling</strong><br>Room bounding box vertices are sampled from standard normal Gaussian noise $x_T \\sim \\mathcal{N}(0, I)$. Shapes are chaotic with high spatial entropy and non-physical overlaps.`;
        gedVal = (1.85 - progress * 1.5).toFixed(2);
        compatVal = (15.0 + progress * 60).toFixed(1);
        overlapSqft = (420 * (1.0 - progress)).toFixed(1);
      } else if (progress < 0.65) {
        phaseName = `T = ${t_val} | Semantic Regional Clustering (25-65%)`;
        phaseDesc = `<strong>Phase 2: Semantic Regional Clustering</strong><br>The neural network eliminates global noise. Living and private bedroom clusters gravitate toward their respective public and quiet structural zones.`;
        gedVal = (0.95 - progress * 0.8).toFixed(2);
        compatVal = (45.0 + progress * 40).toFixed(1);
        overlapSqft = (180 * (1.0 - progress)).toFixed(1);
      } else if (progress < 0.90) {
        phaseName = `T = ${t_val} | Topological Contact Resolution (65-90%)`;
        phaseDesc = `<strong>Phase 3: Relational Graph Contact Resolution</strong><br>Interleaved RGCN message passing and Cross-Attention to top-k retrieved exemplars resolve room interfaces, eliminating dead corridors and locking functional adjacencies.`;
        gedVal = (0.42 - (progress - 0.65) * 0.8).toFixed(2);
        compatVal = (75.0 + (progress - 0.65) * 40).toFixed(1);
        overlapSqft = (45 * (1.0 - progress)).toFixed(1);
      } else {
        phaseName = `T = 0 | Manhattan CAD Vectorization (100%)`;
        phaseDesc = `<strong>Phase 4: Manhattan CAD Vectorization</strong><br>Continuous denoised coordinates are snapped to regular Manhattan grid axes. Contact interfaces infer architectural door openings with quarter-circle clearance arcs.`;
        gedVal = modelMode === "floorgen_rag" ? "0.18" : (modelMode === "housediff_k0" ? "0.72" : "1.84");
        compatVal = modelMode === "floorgen_rag" ? "84.7%" : (modelMode === "housediff_k0" ? "58.1%" : "35.2%");
        overlapSqft = modelMode === "floorgen_rag" ? "0.00" : (modelMode === "housediff_k0" ? "38.50" : "112.40");
      }

      document.getElementById("phaseBadge").innerText = phaseName;
      document.getElementById("phaseExplanation").innerHTML = phaseDesc;
      document.getElementById("progressText").innerText = `Step ${stepVal}/30 (${Math.round(progress * 100)}% Denoised)`;
      document.getElementById("valStep").innerText = `t = ${t_val} / 30`;
      document.getElementById("valCompat").innerText = `${compatVal}%`;
      document.getElementById("valGED").innerText = gedVal;
      document.getElementById("valOverlap").innerText = `${overlapSqft} sq.ft`;
      document.getElementById("valArea").innerText = `${arch.area_sqft} sq.ft`;

      // Render 2D SVG
      render2DSVG(arch, progress, modelMode);

      // Render 3D if active
      if (is3D) {
        update3D(arch, progress, modelMode);
      }
    }

    function render2DSVG(arch, progress, modelMode) {
      let noiseScale = (1.0 - progress) * 38.0;
      if (modelMode === "housediff_k0" && progress > 0.85) noiseScale = 8.0;
      if (modelMode === "housegan_pp" && progress > 0.85) noiseScale = 14.0;

      let svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 260 250" width="100%" height="100%" style="background-color: #FAFAFA; font-family: 'Plus Jakarta Sans', sans-serif;">
        <!-- Exterior Site Boundary -->
        <polygon points="10,12 250,12 250,238 10,238" fill="#F8FAFC" stroke="#94A3B8" stroke-width="1.8" stroke-dasharray="4,4"/>`;

      arch.rooms.forEach((r, idx) => {
        // Deterministic pseudo-random jitter function for smooth trajectory
        const s = noiseSeed + idx * 17;
        const jx1 = Math.sin(s + (1.0 - progress) * 7.5) * noiseScale;
        const jy1 = Math.cos(s * 1.3 + (1.0 - progress) * 7.5) * noiseScale;
        const jx2 = Math.cos(s * 2.1 + (1.0 - progress) * 7.5) * noiseScale;
        const jy2 = Math.sin(s * 2.7 + (1.0 - progress) * 7.5) * noiseScale;

        const x1 = Math.max(10, Math.min(235, r.box[0] + jx1));
        const y1 = Math.max(12, Math.min(220, r.box[1] + jy1));
        const x2 = Math.max(x1 + 16, Math.min(250, r.box[2] + jx2));
        const y2 = Math.max(y1 + 16, Math.min(238, r.box[3] + jy2));

        const w = x2 - x1;
        const h = y2 - y1;
        const alpha = Math.min(1.0, 0.35 + 0.65 * progress);
        const strokeW = progress > 0.85 ? 2.4 : 1.5;

        svg += `<rect x="${x1.toFixed(1)}" y="${y1.toFixed(1)}" width="${w.toFixed(1)}" height="${h.toFixed(1)}" fill="${r.fill}" stroke="${r.stroke}" stroke-width="${strokeW}" fill-opacity="${alpha.toFixed(2)}"/>`;

        if (progress > 0.35) {
          const cx = (x1 + x2) / 2;
          const cy = (y1 + y2) / 2;
          const sqft = Math.round(w * h * 0.42);
          svg += `
            <text x="${cx.toFixed(1)}" y="${(cy - 2).toFixed(1)}" text-anchor="middle" font-size="7.5" font-weight="700" fill="#0F172A" fill-opacity="${alpha.toFixed(2)}">${r.name.toUpperCase()}</text>
            <text x="${cx.toFixed(1)}" y="${(cy + 8).toFixed(1)}" text-anchor="middle" font-size="6" fill="#64748B" fill-opacity="${alpha.toFixed(2)}">${sqft} sq.ft</text>
          `;
        }
      });

      // Doors and clearances on converged step
      if (progress > 0.85 && modelMode === "floorgen_rag" && arch.doors) {
        arch.doors.forEach(([p1, p2]) => {
          const dx = p2[0] - p1[0];
          const dy = p2[1] - p1[1];
          svg += `<line x1="${p1[0]}" y1="${p1[1]}" x2="${p2[0]}" y2="${p2[1]}" stroke="#2563EB" stroke-width="3" stroke-linecap="round"/>`;
          // Quarter arc door swing
          const r = Math.max(Math.abs(dx), Math.abs(dy), 10);
          svg += `<path d="M ${p1[0]} ${p1[1]} A ${r} ${r} 0 0 1 ${p2[0]} ${p2[1]}" fill="none" stroke="#EF4444" stroke-width="1.2" stroke-dasharray="2,2"/>`;
        });
      }

      svg += `</svg>`;
      document.getElementById("svgContainer").innerHTML = svg;
    }

    // Three.js 3D Viewport
    function init3D() {
      const container = document.getElementById("threeCanvas");
      container.innerHTML = "";

      scene = new THREE.Scene();
      scene.background = new THREE.Color(0x0F172A);

      camera = new THREE.PerspectiveCamera(45, container.clientWidth / container.clientHeight, 1, 1000);
      camera.position.set(180, 240, 260);

      renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setSize(container.clientWidth, container.clientHeight);
      renderer.shadowMap.enabled = true;
      container.appendChild(renderer.domElement);

      controls = new THREE.OrbitControls(camera, renderer.domElement);
      controls.enableDamping = true;
      controls.autoRotate = true;
      controls.autoRotateSpeed = 1.0;

      // Lights
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.8);
      scene.add(ambientLight);

      const dirLight = new THREE.DirectionalLight(0xffffff, 0.85);
      dirLight.position.set(120, 220, 100);
      dirLight.castShadow = true;
      scene.add(dirLight);

      // Floor plane
      const floorGeo = new THREE.PlaneGeometry(300, 300);
      const floorMat = new THREE.MeshStandardMaterial({ color: 0x1E293B, roughness: 0.8 });
      const floor = new THREE.Mesh(floorGeo, floorMat);
      floor.rotation.x = -Math.PI / 2;
      scene.add(floor);

      function animate() {
        requestAnimationFrame(animate);
        controls.update();
        renderer.render(scene, camera);
      }
      animate();
    }

    function update3D(arch, progress, modelMode) {
      if (!scene) init3D();

      // Remove existing room meshes
      roomMeshes.forEach(m => scene.remove(m));
      roomMeshes = [];

      const noiseScale = (1.0 - progress) * 35.0;

      arch.rooms.forEach((r, idx) => {
        const s = noiseSeed + idx * 17;
        const jx1 = Math.sin(s + (1.0 - progress) * 7.5) * noiseScale;
        const jz1 = Math.cos(s * 1.3 + (1.0 - progress) * 7.5) * noiseScale;
        const jx2 = Math.cos(s * 2.1 + (1.0 - progress) * 7.5) * noiseScale;
        const jz2 = Math.sin(s * 2.7 + (1.0 - progress) * 7.5) * noiseScale;

        const x1 = r.box[0] + jx1;
        const z1 = r.box[1] + jz1;
        const x2 = r.box[2] + jx2;
        const z2 = r.box[3] + jz2;

        const w = Math.max(12, Math.abs(x2 - x1));
        const d = Math.max(12, Math.abs(z2 - z1));
        const cx = (x1 + x2) / 2 - 130;
        const cz = (z1 + z2) / 2 - 130;

        // Room Floor Tile
        const floorTileGeo = new THREE.BoxGeometry(w, 2, d);
        const floorTileMat = new THREE.MeshStandardMaterial({ color: r.color3d, roughness: 0.4 });
        const floorTile = new THREE.Mesh(floorTileGeo, floorTileMat);
        floorTile.position.set(cx, 1, cz);
        scene.add(floorTile);
        roomMeshes.push(floorTile);

        // Extruded Walls (rise up as diffusion denoises)
        const wallH = Math.max(2, 22 * progress);
        const wallThick = 2.5;
        const wallMat = new THREE.MeshStandardMaterial({ color: 0xFFFFFF, roughness: 0.3, transparent: true, opacity: 0.4 + 0.6 * progress });

        // N, S, W, E walls
        const wn = new THREE.Mesh(new THREE.BoxGeometry(w, wallH, wallThick), wallMat);
        wn.position.set(cx, wallH/2, cz - d/2);
        const ws = new THREE.Mesh(new THREE.BoxGeometry(w, wallH, wallThick), wallMat);
        ws.position.set(cx, wallH/2, cz + d/2);
        const ww = new THREE.Mesh(new THREE.BoxGeometry(wallThick, wallH, d), wallMat);
        ww.position.set(cx - w/2, wallH/2, cz);
        const we = new THREE.Mesh(new THREE.BoxGeometry(wallThick, wallH, d), wallMat);
        we.position.set(cx + w/2, wallH/2, cz);

        [wn, ws, ww, we].forEach(wall => {
          scene.add(wall);
          roomMeshes.push(wall);
        });
      });
    }

    function switchView(mode) {
      if (mode === "3d") {
        document.getElementById("svgContainer").style.display = "none";
        document.getElementById("threeCanvas").style.display = "block";
        document.getElementById("pill3D").classList.add("active");
        document.getElementById("pill2D").classList.remove("active");
        is3D = true;
        if (!scene) init3D();
        updateSimulation();
      } else {
        document.getElementById("svgContainer").style.display = "block";
        document.getElementById("threeCanvas").style.display = "none";
        document.getElementById("pill2D").classList.add("active");
        document.getElementById("pill3D").classList.remove("active");
        is3D = false;
        updateSimulation();
      }
    }

    function downloadFloorplanSVG() {
      const svgData = document.getElementById("svgContainer").innerHTML;
      const blob = new Blob([svgData], { type: "image/svg+xml" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `floorgen_${currentArchetypeKey}_plan.svg`;
      a.click();
    }

    function exportFloorplanJSON() {
      const arch = ARCHETYPES[currentArchetypeKey];
      const data = {
        meta: {
          system: "FloorGen",
          author: "Kumar Mrinal (IIIT Delhi)",
          archetype: arch.name,
          area_sqft: arch.area_sqft,
          status: "Converged Manhattan Vector CAD"
        },
        rooms: arch.rooms
      };
      const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `floorgen_${currentArchetypeKey}.json`;
      a.click();
    }

    // Initialize on load
    updateSimulation(30);
  </script>
</body>
</html>